+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>feature-repo-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-config-persister</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-manager-facade-xml</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-persister</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-persister-all</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-startup</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-manager-facade-xml</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>Opendaylight :: Config Persister:: Mapping for Config Subsystem</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-core</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-manager-facade-xml</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-persister-all</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: Config Persister:: All</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-persister</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-startup</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-persister</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: Config Persister</name>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-artifacts</artifactId>
- <version>2.5.0-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>${project.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-api</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-core</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-manager</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-manager-facade-xml</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>odl-mdsal-binding-runtime</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-feature-adapter</artifactId>
- </dependency>
- <!-- For some reason config-persister-feature-adapter needs this -->
- <dependency>
- <groupId>org.apache.karaf</groupId>
- <artifactId>org.apache.karaf.util</artifactId>
- <version>${karaf.version}</version>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-startup</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <name>OpenDaylight :: Config Persister:: Config Startup</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-persister</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-config-persister-aggregator</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>pom</packaging>
-
- <modules>
- <module>features-config-persister</module>
- <module>odl-config-manager-facade-xml</module>
- <module>odl-config-persister</module>
- <module>odl-config-persister-all</module>
- <module>odl-config-startup</module>
- </modules>
-
- <scm>
- <connection>scm:git:http://git.opendaylight.org/gerrit/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</url>
- </scm>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>feature-repo-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-config</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-all</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-api</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-core</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-manager</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-netty-config-api</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-util</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-all</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-api</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-netty-config-api</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-core</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-manager</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-api</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>odl-mdsal-binding-base</artifactId>
- <version>2.5.0-SNAPSHOT</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-core</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-artifacts</artifactId>
- <version>2.5.0-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>${project.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>odl-mdsal-binding-runtime</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-util</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-jmx-generator</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>shutdown-api</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>shutdown-impl</artifactId>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-manager</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-core</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-manager</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2017 Pantheon Technologies, s.r.o. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0" name="odl-config-manager">
- <repository>mvn:org.opendaylight.controller/odl-config-core/${project.version}/xml/features</repository>
- <feature name="odl-config-manager" description="odl-config-manager" version="${project.version}">
- <bundle start-level="35">mvn:org.opendaylight.controller/config-manager/${project.version}</bundle>
- </feature>
-</features>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-netty-config-api</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-api</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odl-netty-4</artifactId>
- <version>3.1.0</version>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netty-config-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ Copyright © 2017 Red Hat, Inc. and others.
- ~
- ~ This program and the accompanying materials are made available under the
- ~ terms of the Eclipse Public License v1.0 which accompanies this distribution,
- ~ and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<features name="odl-controller-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.4.0">
- <feature name="odl-config-netty-config-api" version="${project.version}">
- <feature version="[3.1.0,4)">odl-netty-4</feature>
- </feature>
-</features>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2018 Pantheon Technologies, s.r.o. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-config-util</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>feature</packaging>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yangtools-artifacts</artifactId>
- <version>2.0.5</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>${project.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>odl-yangtools-data-api</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-api</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-util</artifactId>
- </dependency>
- </dependencies>
-
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ Copyright © 2018 Pantheon Technologies, s.r.o. and others.
- ~
- ~ This program and the accompanying materials are made available under the
- ~ terms of the Eclipse Public License v1.0 which accompanies this distribution,
- ~ and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<features name="odl-controller-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.4.0">
- <feature name="odl-config-util" version="${project.version}">
- <feature version="[2.0.5,3)">odl-yangtools-data-api</feature>
- </feature>
-</features>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-config-aggregator</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>pom</packaging>
-
- <modules>
- <module>features-config</module>
- <module>odl-config-all</module>
- <module>odl-config-api</module>
- <module>odl-config-core</module>
- <module>odl-config-manager</module>
- <module>odl-config-netty-config-api</module>
- <module>odl-config-util</module>
- </modules>
-
- <scm>
- <connection>scm:git:http://git.opendaylight.org/gerrit/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</url>
- </scm>
-</project>
<packaging>pom</packaging>
<modules>
- <module>config</module>
- <module>config-persister</module>
<module>config-netty</module>
<module>mdsal</module>
<module>extras</module>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<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.mdsal</groupId>
- <artifactId>binding-parent</artifactId>
- <version>0.13.0-SNAPSHOT</version>
- <relativePath />
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <version>0.9.0-SNAPSHOT</version>
- <artifactId>config-api</artifactId>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>yang-binding</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-common</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
-
- <!-- We are adding generated code which is bound to OSGi, so we need
- to make sure anyone dependending on this artifact inherits it -->
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import java.util.List;
-import java.util.Set;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.constants.ConfigRegistryConstants;
-
-/**
- * Provides functionality for working with configuration registry - mainly
- * creating and committing config transactions.
- */
-public interface ConfigRegistry extends LookupRegistry, ServiceReferenceReadableRegistry {
-
- /**
- * Only well-known ObjectName in configuration system, under which
- * ConfigRegistry is registered.
- */
- ObjectName OBJECT_NAME = ConfigRegistryConstants.OBJECT_NAME;
- ObjectName OBJECT_NAME_NO_NOTIFICATIONS = ConfigRegistryConstants.OBJECT_NAME_NO_NOTIFICATIONS;
-
- /**
- * Opens new configuration transaction.
- *
- * @return {@link ObjectName} of
- * {@link org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean}
- */
- ObjectName beginConfig();
-
- /**
- * Verifies and commits transaction.
- *
- * @param transactionControllerON
- * {@link ObjectName} of
- * {@link org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean}
- * that was received in {@link #beginConfig()} method call.
- * @return CommitStatus
- * @throws ValidationException
- * if validation fails
- * @throws ConflictingVersionException
- * if configuration state was changed
- */
- CommitStatus commitConfig(ObjectName transactionControllerON)
- throws ConflictingVersionException, ValidationException;
-
- /**
- * List of open configuration transactions.
- *
- * @return list of open configuration transactions.
- */
- List<ObjectName> getOpenConfigs();
-
- /**
- * Will return true unless there was a transaction that succeeded during
- * validation but failed in second phase of commit. In this case the server is
- * unstable and its state is undefined.
- */
- boolean isHealthy();
-
- /**
- * Get the module names available in the system.
- *
- * @return module factory names available in the system
- */
- Set<String> getAvailableModuleNames();
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-/**
- * Service interface for the config system.
- *
- * @author Thomas Pantelis
- */
-public interface ConfigSystemService {
- /**
- * This method closes all the config system modules. This method should only be called on process
- * shutdown and is provided as a hook to control the shutdown sequence.
- */
- void closeAllConfigModules();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import java.util.Set;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-
-/**
- * Represents functionality provided by configuration transaction.
- */
-public interface ConfigTransactionController extends LookupRegistry, ServiceReferenceWritableRegistry {
-
- /**
- * Create new configuration bean.
- *
- * @param moduleName
- * name of the module
- * @param instanceName
- * name of the instance
- * @return ObjectName of newly created module
- * @throws InstanceAlreadyExistsException
- * if given ifcName and instanceName is already registered
- */
- ObjectName createModule(String moduleName, String instanceName) throws InstanceAlreadyExistsException;
-
- /**
- * Re-creates an existing module configuration bean.
- *
- * @param objectName
- * can be either read-only module name that can be obtained using
- * {@link ConfigRegistry#lookupConfigBean(String, String)} or
- * writable module name that must contain current transaction name.
- * @throws InstanceNotFoundException
- * if module is not found
- * @throws IllegalArgumentException
- * if object name contains wrong transaction name or domain
- */
- void reCreateModule(ObjectName objectName) throws InstanceNotFoundException;
-
- /**
- * Destroy existing module.
- *
- * @param objectName
- * can be either read-only module name that can be obtained using
- * {@link ConfigRegistry#lookupConfigBean(String, String)} or
- * writable module name that must contain current transaction name.
- * @throws InstanceNotFoundException
- * if module is not found
- * @throws IllegalArgumentException
- * if object name contains wrong transaction name or domain
- */
- void destroyModule(ObjectName objectName) throws InstanceNotFoundException;
-
- /**
- * Destroy current transaction.
- */
- void abortConfig();
-
- /**
- * This method can be called multiple times, has no side effects.
- *
- * @throws ValidationException
- * if validation fails
- */
- void validateConfig() throws ValidationException;
-
- /**
- * Get the name of the transaction.
- *
- * @return transactionName
- */
- String getTransactionName();
-
- /**
- * Get the names of all available modules.
- *
- * @return all known module factory names as reported by
- * {@link org.opendaylight.controller.config.spi.ModuleFactory#getImplementationName()}
- */
- Set<String> getAvailableModuleNames();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-/**
- * Can be thrown during
- * {@link ConfigRegistry#commitConfig(javax.management.ObjectName)} to indicate
- * that the transaction cannot be committed due to the fact that another
- * transaction was committed after creating this transaction. Clients can create
- * new transaction and merge the changes.
- */
-public class ConflictingVersionException extends Exception {
- private static final long serialVersionUID = 1L;
-
- public ConflictingVersionException() {
- }
-
- public ConflictingVersionException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
- public ConflictingVersionException(final String message) {
- super(message);
- }
-
- public ConflictingVersionException(final Throwable cause) {
- super(cause);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import javax.management.AttributeNotFoundException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-
-/**
- * Each new {@link org.opendaylight.controller.config.spi.Module} can receive
- * resolver from {@link org.opendaylight.controller.config.spi.ModuleFactory}
- * for looking up dependencies during validation and second phase commit.
- *
- * @see org.opendaylight.controller.config.spi.Module
- */
-public interface DependencyResolver extends Identifiable<ModuleIdentifier> {
-
- /**
- * To be used during validation phase to validate service interface of dependent
- * module.
- *
- * @param expectedServiceInterface
- * MBean/MXBean interface which will back the proxy object.
- * @param objectName
- * ObjectName of dependent module without transaction name
- * (platformON).
- * @param jmxAttribute
- * for reporting
- * @throws IllegalArgumentException
- * when module is not found
- * @throws IllegalStateException
- * if module does not export this service interface.
- */
- void validateDependency(Class<? extends AbstractServiceInterface> expectedServiceInterface, ObjectName objectName,
- JmxAttribute jmxAttribute);
-
- /**
- * To be used during commit phase to wire actual dependencies.
- *
- * @return dependency instance using
- * {@link org.opendaylight.controller.config.spi.Module#getInstance()}
- * @throws IllegalArgumentException
- * when module is not found
- */
- <T> T resolveInstance(Class<T> expectedType, ObjectName objectName, JmxAttribute jmxAttribute);
-
- /**
- * To be used during commit phase to resolve identity-ref config attributes.
- *
- * @return actual class object generated from identity
- */
- <T extends BaseIdentity> Class<? extends T> resolveIdentity(IdentityAttributeRef identityRef,
- Class<T> expectedBaseClass);
-
- /**
- * Validate identity-ref config attribute.
- */
- <T extends BaseIdentity> void validateIdentity(IdentityAttributeRef identityRef, Class<T> expectedBaseClass,
- JmxAttribute jmxAttribute);
-
- /**
- * Can be used during validation or commit phase to get attribute value of
- * dependent module.
- *
- * @param name
- * either direct ObjectName of a Module (type=Module) or service
- * reference (type=ServiceReference) of dependent Module
- * @param attribute
- * String identifying attribute name in JMX. Note that attributes
- * start with upper case. See
- * {@link org.opendaylight.controller.config.api.JmxAttribute#getAttributeName()}
- */
- Object getAttribute(ObjectName name, String attribute)
- throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException;
-
- /**
- * Helper method around.
- * {@link javax.management
- * .JMX#newMXBeanProxy(javax.management.MBeanServerConnection, javax.management.ObjectName, Class)}}.
- *
- * Returns MXBean proxy for dependent module. Can be used during validation or
- * commit phase to inspect dependent module's attributes.
- *
- * @param objectName
- * either direct ObjectName of a Module (type=Module) or service
- * reference (type=ServiceReference) of dependent Module
- * @param interfaceClass
- * MXBean interface to be used as a proxy
- * @param <T>
- * type of proxy for type safe return value
- * @return instance of MXBean proxy
- */
- <T> T newMXBeanProxy(ObjectName objectName, Class<T> interfaceClass);
-
- /**
- * Check whether a dependency will be reused or (re)created. Useful when
- * deciding if current module could be also reused.
- *
- * @param objectName
- * ObjectName ID of a dependency
- * @param jmxAttribute
- * JMXAttribute ID of a dependency
- * @return true if the dependency will be reused false otherwise
- */
- boolean canReuseDependency(ObjectName objectName, JmxAttribute jmxAttribute);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-public interface DependencyResolverFactory {
-
- DependencyResolver createDependencyResolver(ModuleIdentifier moduleIdentifier);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import javax.management.DynamicMBean;
-import org.opendaylight.controller.config.spi.Module;
-
-/**
- * Each {@link org.opendaylight.controller.config.spi.Module} that is committed
- * will be wrapped into this interface.
- */
-public interface DynamicMBeanWithInstance extends DynamicMBean {
-
- /**
- * Get original module that is wrapped with this instance.
- */
- Module getModule();
-
- /**
- * Gets 'live object' associated with current config object. Useful when
- * reconfiguring {@link org.opendaylight.controller.config.spi.Module}
- * instances.
- */
- AutoCloseable getInstance();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import java.beans.ConstructorProperties;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-
-public final class IdentityAttributeRef {
-
- public static final String QNAME_ATTR_NAME = "qNameOfIdentity";
-
- private final String qualifiedNameOfIdentity;
-
- @ConstructorProperties(QNAME_ATTR_NAME)
- public IdentityAttributeRef(final String qualifiedNameOfIdentity) {
- if (qualifiedNameOfIdentity == null) {
- throw new NullPointerException("Parameter " + QNAME_ATTR_NAME + " is null");
- }
- this.qualifiedNameOfIdentity = qualifiedNameOfIdentity;
- }
-
- public String getqNameOfIdentity() {
- return qualifiedNameOfIdentity;
- }
-
- public <T extends BaseIdentity> Class<? extends T> resolveIdentity(final DependencyResolver resolver,
- final Class<T> baseIdentity) {
- return resolver.resolveIdentity(this, baseIdentity);
- }
-
- public <T extends BaseIdentity> void validateIdentity(final DependencyResolver resolver,
- final Class<T> baseIdentity, final JmxAttribute jmxAttribute) {
- resolver.validateIdentity(this, baseIdentity, jmxAttribute);
- }
-
- @Override
- public String toString() {
- return "IdentityAttributeRef{" + "qualifiedNameOfIdentity='" + qualifiedNameOfIdentity + "'}";
- }
-
- @Override
- public boolean equals(final Object object) {
- if (this == object) {
- return true;
- }
- if (!(object instanceof IdentityAttributeRef)) {
- return false;
- }
-
- IdentityAttributeRef that = (IdentityAttributeRef) object;
-
- if (!qualifiedNameOfIdentity.equals(that.qualifiedNameOfIdentity)) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- return qualifiedNameOfIdentity.hashCode();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-/**
- * Wrapper around strings to make {@link JmxAttributeValidationException} type
- * safe.
- */
-public class JmxAttribute {
- private final String attributeName;
-
- public JmxAttribute(final String attributeName) {
- if (attributeName == null) {
- throw new NullPointerException("Parameter 'attributeName' is null");
- }
- this.attributeName = attributeName;
- }
-
- /**
- * Name of attribute in JMX.
- */
- public String getAttributeName() {
- return attributeName;
- }
-
- @Override
- public boolean equals(final Object object) {
- if (this == object) {
- return true;
- }
- if (object == null || getClass() != object.getClass()) {
- return false;
- }
-
- JmxAttribute that = (JmxAttribute) object;
-
- if (!attributeName.equals(that.attributeName)) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- return attributeName.hashCode();
- }
-
- @Override
- public String toString() {
- return "JmxAttribute{'" + attributeName + "'}";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Exception that can be thrown during validation phase. This allows for
- * pointing user to a specific list of parameters that fail the validation. Note
- * that {@link org.opendaylight.controller.config.spi.Module#validate()} can
- * throw any runtime exception to trigger validation failure.
- */
-public class JmxAttributeValidationException extends RuntimeException {
- private static final long serialVersionUID = 1L;
- private final List<JmxAttribute> attributeNames;
-
- public JmxAttributeValidationException(final JmxAttribute jmxAttribute) {
- this(Arrays.asList(jmxAttribute));
- }
-
- public JmxAttributeValidationException(final List<JmxAttribute> jmxAttribute) {
- this.attributeNames = jmxAttribute;
- }
-
- public JmxAttributeValidationException(final String message,
- final JmxAttribute jmxAttribute) {
- this(message, Arrays.asList(jmxAttribute));
- }
-
- public JmxAttributeValidationException(final String message,
- final List<JmxAttribute> jmxAttributes) {
- super(message);
- this.attributeNames = jmxAttributes;
- }
-
- public JmxAttributeValidationException(final String message, final Throwable cause,
- final JmxAttribute jmxAttribute) {
- this(message, cause, Arrays.asList(jmxAttribute));
- }
-
- public JmxAttributeValidationException(final String message, final Throwable cause,
- final List<JmxAttribute> jmxAttributes) {
- super(message, cause);
- this.attributeNames = jmxAttributes;
- }
-
- public List<JmxAttribute> getAttributeNames() {
- return attributeNames;
- }
-
- public static <T> T checkNotNull(final T param, final JmxAttribute jmxAttribute) {
- String message = "is null";
- return checkNotNull(param, message, jmxAttribute);
- }
-
- public static <T> T checkNotNull(final T param, final String message,
- final JmxAttribute jmxAttribute) {
- if (param == null) {
- throw new JmxAttributeValidationException(
- jmxAttribute.getAttributeName() + " " + message,
- jmxAttribute);
- }
- return param;
- }
-
- public static JmxAttributeValidationException wrap(final Throwable throwable,
- final JmxAttribute jmxAttribute) throws JmxAttributeValidationException {
- return wrap(throwable, throwable.getMessage(), jmxAttribute);
- }
-
- public static JmxAttributeValidationException wrap(final Throwable throwable,
- final String message, final JmxAttribute jmxAttribute) {
-
- throw new JmxAttributeValidationException(
- jmxAttribute.getAttributeName() + " " + message, throwable,
- jmxAttribute);
- }
-
- public static void checkCondition(final boolean condition, final String message,
- final JmxAttribute jmxAttribute) throws JmxAttributeValidationException {
- if (!condition) {
- throw new JmxAttributeValidationException(
- jmxAttribute.getAttributeName() + " " + message,
- jmxAttribute);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import java.util.Set;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-
-public interface LookupRegistry {
-
- /**
- * Find all modules. Same Module can be registered multiple times.
- *
- * @return objectNames
- */
- Set<ObjectName> lookupConfigBeans();
-
- /**
- * Find modules with given module name.
- *
- * @param moduleName
- * name of module
- * @return objectNames
- */
- Set<ObjectName> lookupConfigBeans(String moduleName);
-
- /**
- * Find read modules.
- *
- * @param moduleName
- * exact match for searched module name, can contain '*' to match all
- * values.
- * @param instanceName
- * exact match for searched instance name, can contain '*' to match
- * all values.
- * @return objectNames
- */
- Set<ObjectName> lookupConfigBeans(String moduleName, String instanceName);
-
- /**
- * Find read module.
- *
- * @param moduleName
- * exact match for searched module name, can contain '*' to match all
- * values.
- * @param instanceName
- * exact match for searched instance name, can contain '*' to match
- * all values.
- * @return objectNames
- * @throws InstanceNotFoundException
- * if search did not find exactly one instance
- */
- ObjectName lookupConfigBean(String moduleName, String instanceName) throws InstanceNotFoundException;
-
- /**
- * Check that object name corresponds with existing module.
- *
- * @throws InstanceNotFoundException
- * if search did not find exactly one instance
- */
- void checkConfigBeanExists(ObjectName objectName) throws InstanceNotFoundException;
-
- /**
- * Get the qNames of all ModuleFactory instances in the system.
- *
- * @return qNames of all ModuleFactory instances in the system
- */
- Set<String> getAvailableModuleFactoryQNames();
-
- /**
- * Find all runtime beans.
- *
- * @return objectNames
- */
- Set<ObjectName> lookupRuntimeBeans();
-
- /**
- * Find all runtime of specified module.
- *
- * @param moduleName
- * of bean
- * @param instanceName
- * of bean
- * @return objectNames
- */
- Set<ObjectName> lookupRuntimeBeans(String moduleName, String instanceName);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-/**
- * Exception thrown when a ModuleFactory is not found while pushing a config.
- *
- * @author Thomas Pantelis
- */
-public class ModuleFactoryNotFoundException extends RuntimeException {
- private static final long serialVersionUID = 1L;
-
- private final String moduleName;
-
- public ModuleFactoryNotFoundException(final String moduleName) {
- super("ModuleFactory not found for module name: " + moduleName);
- this.moduleName = moduleName;
- }
-
- public String getModuleName() {
- return moduleName;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import org.opendaylight.yangtools.concepts.Identifier;
-
-public class ModuleIdentifier implements Identifier {
- private static final long serialVersionUID = 1L;
- private final String factoryName;
- private final String instanceName;
-
- public ModuleIdentifier(final String factoryName, final String instanceName) {
- if (factoryName == null) {
- throw new IllegalArgumentException("Parameter 'factoryName' is null");
- }
- if (instanceName == null) {
- throw new IllegalArgumentException("Parameter 'instanceName' is null");
- }
- this.factoryName = factoryName;
- this.instanceName = instanceName;
- }
-
- public String getFactoryName() {
- return factoryName;
- }
-
- public String getInstanceName() {
- return instanceName;
- }
-
- @Override
- public boolean equals(final Object object) {
- if (this == object) {
- return true;
- }
- if (object == null || getClass() != object.getClass()) {
- return false;
- }
-
- ModuleIdentifier that = (ModuleIdentifier) object;
-
- if (!factoryName.equals(that.factoryName)) {
- return false;
- }
- if (!instanceName.equals(that.instanceName)) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = factoryName.hashCode();
- result = 31 * result + instanceName.hashCode();
- return result;
- }
-
- @Override
- public String toString() {
- return "ModuleIdentifier{" + "factoryName='" + factoryName + '\''
- + ", instanceName='" + instanceName + '\'' + '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
-import org.opendaylight.controller.config.spi.Module;
-
-/**
- * Module implementing this interface will receive
- * {@link RootRuntimeBeanRegistrator} before getInstance() is invoked.
- */
-public interface RuntimeBeanRegistratorAwareModule extends Module {
- /**
- * Configuration framework will call this setter on all modules implementing
- * this interface. It is responsibility of modules or rather their instances
- * to close registrator in their {@link java.io.Closeable#close()} method. Same
- * module will get the same registrator during reconfiguration.
- *
- * @param rootRuntimeBeanRegistrator root bean
- */
- void setRuntimeBeanRegistrator(
- RootRuntimeBeanRegistrator rootRuntimeBeanRegistrator);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import java.util.Map;
-import java.util.Set;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-
-public interface ServiceReferenceReadableRegistry {
-
- /**
- * Lookup object name by fully qualified service interface name and service
- * reference name.
- *
- * @param serviceInterfaceQName
- * service interface name
- * @param refName
- * service reference name supplied in
- * {@link org.opendaylight.controller.config
- * .api .ConfigTransactionController#saveServiceReference(String, String, javax.management.ObjectName)}
- * @throws java.lang.IllegalArgumentException
- * if module not found
- */
- ObjectName lookupConfigBeanByServiceInterfaceName(String serviceInterfaceQName, String refName);
-
- /**
- * Get mapping of services to reference names and module object names.
- */
- Map<String /* serviceInterfaceQName */, Map<String/* refName */, ObjectName>> getServiceMapping();
-
- /**
- * Get current mapping between reference names and module object names for given
- * service interface name.
- *
- * @param serviceInterfaceQName
- * service interface name
- * @throws IllegalArgumentException
- * if there is a mismatch between serviceInterfaceName and
- * objectName
- */
- Map<String /* refName */, ObjectName> lookupServiceReferencesByServiceInterfaceName(String serviceInterfaceQName);
-
- /**
- * Find all available service interface names of a module.
- *
- * @param objectName
- * module object name
- * @throws InstanceNotFoundException
- * if search did not find exactly one instance
- */
- Set<String> lookupServiceInterfaceNames(ObjectName objectName) throws InstanceNotFoundException;
-
- /**
- * Get the name of the service interface.
- *
- * @param namespace
- * service interface namespace
- * @param localName
- * service interface local name
- * @return fully qualified name needed by all other service reference mapping
- * methods.
- * @throws java.lang.IllegalArgumentException
- * if namespace or localName is not found
- */
- String getServiceInterfaceName(String namespace, String localName);
-
- /**
- * Get the reference to that service.
- *
- * @return ObjectName with type=Service that was created using
- * {@link org.opendaylight.controller
- * .config .api.ServiceReferenceWritableRegistry#saveServiceReference(String,
- * String, javax.management.ObjectName)}
- */
- ObjectName getServiceReference(String serviceInterfaceQName, String refName) throws InstanceNotFoundException;
-
- void checkServiceReferenceExists(ObjectName objectName) throws InstanceNotFoundException;
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-
-public interface ServiceReferenceWritableRegistry extends ServiceReferenceReadableRegistry {
- /**
- * Create or update reference name to objectName. Reference name is unique per
- * service interface name.
- *
- * @return created or updated object name containing service name and reference
- * name
- * @throws IllegalArgumentException
- * if there is a mismatch between serviceInterfaceName and
- * objectName
- * @throws InstanceNotFoundException
- * if search did not find exactly one instance
- */
- ObjectName saveServiceReference(String serviceInterfaceName, String refName, ObjectName moduleON)
- throws InstanceNotFoundException;
-
- /**
- * Remove service reference.
- *
- * @throws IllegalArgumentException
- * if service interface name is not advertised by any module
- */
- void removeServiceReference(String serviceInterfaceName, String refName) throws InstanceNotFoundException;
-
- /**
- * Remove all service references.
- */
- void removeAllServiceReferences();
-
- /**
- * Remove all service references attached to given module.
- *
- * @return true iif at least one reference was removed
- */
- boolean removeServiceReferences(ObjectName objectName) throws InstanceNotFoundException;
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-/**
- * This exception is not intended to be used while implementing modules, it
- * aggregates validation exceptions and sends them back to the user. Use
- * {@link org.opendaylight.controller.config.api.JmxAttributeValidationException}
- * for validating modules instead.
- */
-public class ValidationException extends Exception {
- private static final long serialVersionUID = -6072893219820274247L;
-
- private final Map<String/* module name */,
- Map<String/* instance name */,
- ExceptionMessageWithStackTrace>> failedValidations;
-
- public ValidationException(
- final Map<String /* module name */,
- Map<String /* instance name */,
- ExceptionMessageWithStackTrace>> failedValidations) {
- super(failedValidations.toString());
- this.failedValidations = Collections.unmodifiableMap(failedValidations);
- }
-
- public static ValidationException createFromCollectedValidationExceptions(
- final List<ValidationException> collectedExceptions) {
- Map<String, Map<String, ExceptionMessageWithStackTrace>> failedValidations = new HashMap<>();
- for (ValidationException ve : collectedExceptions) {
- for (Entry<String, Map<String, ExceptionMessageWithStackTrace>> outerEntry : ve.getFailedValidations()
- .entrySet()) {
- for (Entry<String, ExceptionMessageWithStackTrace> innerEntry : outerEntry.getValue().entrySet()) {
- String moduleName = outerEntry.getKey();
- String instanceName = innerEntry.getKey();
- ExceptionMessageWithStackTrace ex = innerEntry.getValue();
- Map<String, ExceptionMessageWithStackTrace> instanceToExMap = failedValidations
- .computeIfAbsent(moduleName, k -> new HashMap<>());
- if (instanceToExMap.containsKey(instanceName)) {
- throw new IllegalArgumentException("Cannot merge with same module name " + moduleName
- + " and instance name " + instanceName);
- }
- instanceToExMap.put(instanceName, ex);
- }
- }
- }
- return new ValidationException(failedValidations);
- }
-
- public static ValidationException createForSingleException(final ModuleIdentifier moduleIdentifier,
- final Exception exception) {
- Map<String, Map<String, ExceptionMessageWithStackTrace>> failedValidations = new HashMap<>();
- Map<String, ExceptionMessageWithStackTrace> innerMap = new HashMap<>();
-
- failedValidations.put(moduleIdentifier.getFactoryName(), innerMap);
- innerMap.put(moduleIdentifier.getInstanceName(), new ExceptionMessageWithStackTrace(exception));
- return new ValidationException(failedValidations);
- }
-
- public Map<String/* module name */,
- Map<String/* instance name */,
- ExceptionMessageWithStackTrace>> getFailedValidations() {
- return failedValidations;
- }
-
- public static class ExceptionMessageWithStackTrace {
- private String message;
- private String stackTrace;
-
- public ExceptionMessageWithStackTrace() {
- }
-
- public ExceptionMessageWithStackTrace(final String message, final String stackTrace) {
- this.message = message;
- this.stackTrace = stackTrace;
- }
-
- public ExceptionMessageWithStackTrace(final Exception exception) {
- this(exception.getMessage(), Arrays.toString(exception.getStackTrace()));
- }
-
- public String getMessage() {
- return message;
- }
-
- public String getTrace() {
- return stackTrace;
- }
-
- public void setMessage(final String message) {
- this.message = message;
- }
-
- public void setStackTrace(final String trace) {
- this.stackTrace = trace;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (message == null ? 0 : message.hashCode());
- result = prime * result + (stackTrace == null ? 0 : stackTrace.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- ExceptionMessageWithStackTrace other = (ExceptionMessageWithStackTrace) obj;
- if (message == null) {
- if (other.message != null) {
- return false;
- }
- } else if (!message.equals(other.message)) {
- return false;
- }
- if (stackTrace == null) {
- if (other.stackTrace != null) {
- return false;
- }
- } else if (!stackTrace.equals(other.stackTrace)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- return message;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.annotations;
-
-/**
- * Marker interface on all Service Interface annotated classes, each Service
- * Interface must extend this interface. Service Intefaces can form hierarchies,
- * one SI can extend another one, in which case all annotations in hierarchy
- * will be observed.
- */
-public interface AbstractServiceInterface {
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Exports attribute and module class descriptions. Description annotation can
- * be applied to module directly or to its super class or MXBean interface.
- */
-@Target({ ElementType.TYPE, ElementType.METHOD })
-@Retention(RetentionPolicy.RUNTIME)
-public @interface Description {
- /**
- * Returns a human-readable description of the annotated attribute.
- * Descriptions should be clear and concise, describing what the attribute
- * affects.
- *
- * @return attribute description
- */
- String value();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Indicates what service interface is expected to be obtained as a dependency
- * of a module. This annotation must be present for each dependency setter in
- * {@link org.opendaylight.controller.config.spi.Module} M(X)Bean interface.
- * Together with name of dependent bean the {@link #value()} will be used to get
- * {@link javax.management.ObjectName} of dependency.
- *
- * <p>
- * Example:<br>
- *
- * <code>
- * {@literal @}RequireInterface(value = ThreadPoolServiceInterface.class, optional = false)<br>
- * void setThreadPool(ObjectName on);
- * </code>
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.METHOD)
-public @interface RequireInterface {
-
- /**
- * Declares dependency on service interface.
- */
- Class<? extends AbstractServiceInterface> value();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Marks an interface implemented by
- * {@link org.opendaylight.controller.config.spi.Module} as a Service Interface.
- * Each service interface is identified by globally unique and human readable
- * name. By convention the name is all lower case without spaces.
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target(ElementType.TYPE)
-public @interface ServiceInterfaceAnnotation {
-
- /**
- * Fully qualified name of a service that must be globally unique.
- * When generating service interfaces from yang, this will be QName of
- * identity extending service-type.
- */
- String value();
-
- /**
- * Mandatory class which will be used as key for OSGi service registration
- * once {@link org.opendaylight.controller.config.spi.Module#getInstance()}
- * is called.
- */
- Class<?> osgiRegistrationType();
-
- /**
- * Determines whether or not the service instance should be registered with OSGi.
- */
- boolean registerToOsgi() default true;
-
- /**
- * Get namespace of {@link #value()}.
- */
- String namespace();
-
- /**
- * Get revision of {@link #value()}.
- */
- String revision();
-
- /**
- * Get local name of {@link #value()}.
- */
- String localName();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.jmx;
-
-import java.beans.ConstructorProperties;
-import java.util.Collections;
-import java.util.List;
-import javax.annotation.concurrent.Immutable;
-import javax.management.ObjectName;
-
-@Immutable
-public class CommitStatus {
- private final List<ObjectName> newInstances;
- private final List<ObjectName> reusedInstances;
- private final List<ObjectName> recreatedInstances;
-
- /**
- * Constructor.
- *
- * @param newInstances
- * newly created instances
- * @param reusedInstances
- * reused instances
- * @param recreatedInstances
- * recreated instances
- */
- @ConstructorProperties({ "newInstances", "reusedInstances", "recreatedInstances" })
- public CommitStatus(final List<ObjectName> newInstances, final List<ObjectName> reusedInstances,
- final List<ObjectName> recreatedInstances) {
- this.newInstances = Collections.unmodifiableList(newInstances);
- this.reusedInstances = Collections.unmodifiableList(reusedInstances);
- this.recreatedInstances = Collections.unmodifiableList(recreatedInstances);
- }
-
- public List<ObjectName> getNewInstances() {
- return newInstances;
- }
-
- public List<ObjectName> getReusedInstances() {
- return reusedInstances;
- }
-
- public List<ObjectName> getRecreatedInstances() {
- return recreatedInstances;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (newInstances == null ? 0 : newInstances.hashCode());
- result = prime * result + (recreatedInstances == null ? 0 : recreatedInstances.hashCode());
- result = prime * result + (reusedInstances == null ? 0 : reusedInstances.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- CommitStatus other = (CommitStatus) obj;
- if (newInstances == null) {
- if (other.newInstances != null) {
- return false;
- }
- } else if (!newInstances.equals(other.newInstances)) {
- return false;
- }
- if (recreatedInstances == null) {
- if (other.recreatedInstances != null) {
- return false;
- }
- } else if (!recreatedInstances.equals(other.recreatedInstances)) {
- return false;
- }
- if (reusedInstances == null) {
- if (other.reusedInstances != null) {
- return false;
- }
- } else if (!reusedInstances.equals(other.reusedInstances)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- return "CommitStatus [newInstances=" + newInstances + ", reusedInstances=" + reusedInstances
- + ", recreatedInstances=" + recreatedInstances + "]";
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.jmx;
-
-import org.opendaylight.controller.config.api.ConfigRegistry;
-
-/**
- * Represents entry point of configuration management. Note: Reason for having
- * methods in super interface is that JMX allows only one MXBean to be
- * implemented and implementations can expose additional methods to be exported.<br>
- * Implementation of {@link ConfigRegistry} is not required to implement this
- * interface, but is required to export all methods of ConfigRegistry to JMX so
- * that this interface can be used as a proxy.
- */
-public interface ConfigRegistryMXBean extends ConfigRegistry {
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.jmx;
-
-import org.opendaylight.controller.config.api.ConfigTransactionController;
-
-/**
- * Those are executed by Jolokia clients on configuration transaction
- * represented by <code>ConfigMBeanServer</code> instance. Note: Reason for having
- * methods in super interface is that JMX allows only one MXBean to be
- * implemented and implementations can expose additional methods to be exported. <br>
- * Implementation of {@link ConfigTransactionController} is not required to
- * implement this interface, but is required to export all methods of
- * ConfigTransactionController to JMX so that this interface can be used as a
- * proxy.
- */
-public interface ConfigTransactionControllerMXBean extends
- ConfigTransactionController {
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.jmx;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import javax.annotation.concurrent.ThreadSafe;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.jmx.constants.ConfigRegistryConstants;
-
-/**
- * Provides ObjectName creation. Each created ObjectName consists of domain that
- * is defined as {@link #ON_DOMAIN} and at least one key-value pair. The only
- * mandatory property is {@link #TYPE_KEY}. All transaction related mbeans have
- * {@link #TRANSACTION_NAME_KEY} property set.
- */
-@ThreadSafe
-public final class ObjectNameUtil {
-
- public static final String ON_DOMAIN = ConfigRegistryConstants.ON_DOMAIN;
- public static final String MODULE_FACTORY_NAME_KEY = "moduleFactoryName";
- public static final String SERVICE_QNAME_KEY = "serviceQName";
- public static final String INSTANCE_NAME_KEY = "instanceName";
- public static final String TYPE_KEY = ConfigRegistryConstants.TYPE_KEY;
- public static final String TYPE_CONFIG_TRANSACTION = "ConfigTransaction";
- public static final String TYPE_MODULE = "Module";
- public static final String TYPE_SERVICE_REFERENCE = "ServiceReference";
- public static final String TYPE_RUNTIME_BEAN = "RuntimeBean";
- public static final String TRANSACTION_NAME_KEY = "TransactionName";
- public static final String REF_NAME_KEY = "RefName";
- private static final String REPLACED_QUOTATION_MARK = "\\?";
- public static final String ON_WILDCARD = "*";
-
- private ObjectNameUtil() {
- }
-
- public static ObjectName createON(final String on) {
- try {
- return new ObjectName(on);
- } catch (final MalformedObjectNameException e) {
- throw new IllegalArgumentException(e);
- }
- }
-
- public static ObjectName createON(final String name, final String key, final String value) {
- return ConfigRegistryConstants.createON(name, key, value);
- }
-
- public static ObjectName createON(final String domain, final Map<String, String> attribs) {
- Hashtable<String, String> table = new Hashtable<>(attribs);
- try {
- return new ObjectName(domain, table);
- } catch (final MalformedObjectNameException e) {
- throw new IllegalArgumentException(e);
- }
-
- }
-
- public static ObjectName createONWithDomainAndType(final String type) {
- return ConfigRegistryConstants.createONWithDomainAndType(type);
- }
-
- public static ObjectName createTransactionControllerON(final String transactionName) {
- Map<String, String> onParams = new HashMap<>();
- onParams.put(TRANSACTION_NAME_KEY, transactionName);
- onParams.put(TYPE_KEY, TYPE_CONFIG_TRANSACTION);
- return createON(ON_DOMAIN, onParams);
- }
-
- public static ObjectName createTransactionModuleON(final String transactionName,
- final ModuleIdentifier moduleIdentifier) {
- return createTransactionModuleON(transactionName, moduleIdentifier.getFactoryName(),
- moduleIdentifier.getInstanceName());
- }
-
- public static ObjectName createTransactionModuleON(final String transactionName, final String moduleName,
- final String instanceName) {
- Map<String, String> onParams = createModuleMap(moduleName, instanceName);
- onParams.put(TRANSACTION_NAME_KEY, transactionName);
- return createON(ON_DOMAIN, onParams);
- }
-
- public static ObjectName createTransactionModuleON(final String transactionName, final ObjectName on) {
- return createTransactionModuleON(transactionName, getFactoryName(on), getInstanceName(on));
- }
-
- public static ObjectName createReadOnlyModuleON(final ModuleIdentifier moduleIdentifier) {
- return createReadOnlyModuleON(moduleIdentifier.getFactoryName(), moduleIdentifier.getInstanceName());
- }
-
- public static ObjectName createReadOnlyModuleON(final String moduleName, final String instanceName) {
- Map<String, String> onParams = createModuleMap(moduleName, instanceName);
- return createON(ON_DOMAIN, onParams);
- }
-
- public static ObjectName createReadOnlyServiceON(final String serviceQName, final String refName) {
- Map<String, String> onParams = createServiceMap(serviceQName, refName);
- return createON(ON_DOMAIN, onParams);
- }
-
- public static ObjectName createTransactionServiceON(final String transactionName, final String serviceQName,
- final String refName) {
- Map<String, String> onParams = createServiceON(transactionName, serviceQName, refName);
- return createON(ON_DOMAIN, onParams);
- }
-
- public static String getServiceQName(final ObjectName objectName) {
- checkType(objectName, TYPE_SERVICE_REFERENCE);
- String quoted = objectName.getKeyProperty(SERVICE_QNAME_KEY);
- return unquoteAndUnescape(objectName, quoted);
- }
-
- // ObjectName supports quotation and ignores tokens like =, but fails to ignore
- // ? sign.
- // It must be replaced with another character that hopefully does not collide
- // with actual value.
- private static String unquoteAndUnescape(final ObjectName objectName, final String quoted) {
- if (quoted == null) {
- throw new IllegalArgumentException("Cannot find " + SERVICE_QNAME_KEY + " in " + objectName);
- }
- if (!quoted.startsWith("\"") || !quoted.endsWith("\"")) {
- throw new IllegalArgumentException("Quotes not found in " + objectName);
- }
- String substring = quoted.substring(1);
- substring = substring.substring(0, substring.length() - 1);
- substring = substring.replace(REPLACED_QUOTATION_MARK, "?");
- return substring;
- }
-
- private static String quoteAndEscapeValue(final String serviceQName) {
- return "\"" + serviceQName.replace("?", REPLACED_QUOTATION_MARK) + "\"";
- }
-
- public static String getReferenceName(final ObjectName objectName) {
- checkType(objectName, TYPE_SERVICE_REFERENCE);
- return objectName.getKeyProperty(REF_NAME_KEY);
- }
-
- private static Map<String, String> createServiceON(final String transactionName, final String serviceQName,
- final String refName) {
- Map<String, String> result = new HashMap<>(createServiceMap(serviceQName, refName));
- result.put(TRANSACTION_NAME_KEY, transactionName);
- return result;
- }
-
- private static Map<String, String> createServiceMap(final String serviceQName, final String refName) {
- Map<String, String> onParams = new HashMap<>();
- onParams.put(TYPE_KEY, TYPE_SERVICE_REFERENCE);
- onParams.put(SERVICE_QNAME_KEY, quoteAndEscapeValue(serviceQName));
- onParams.put(REF_NAME_KEY, refName);
- return onParams;
- }
-
- private static Map<String, String> createModuleMap(final String moduleName, final String instanceName) {
- Map<String, String> onParams = new HashMap<>();
- onParams.put(TYPE_KEY, TYPE_MODULE);
- onParams.put(MODULE_FACTORY_NAME_KEY, moduleName);
- onParams.put(INSTANCE_NAME_KEY, instanceName);
- return onParams;
- }
-
- public static String getFactoryName(final ObjectName objectName) {
- checkTypeOneOf(objectName, TYPE_MODULE, TYPE_RUNTIME_BEAN);
- return objectName.getKeyProperty(MODULE_FACTORY_NAME_KEY);
- }
-
- public static String getInstanceName(final ObjectName objectName) {
- checkTypeOneOf(objectName, TYPE_MODULE, TYPE_RUNTIME_BEAN);
- return objectName.getKeyProperty(INSTANCE_NAME_KEY);
- }
-
- public static String getTransactionName(final ObjectName objectName) {
- return objectName.getKeyProperty(TRANSACTION_NAME_KEY);
- }
-
- /**
- * Sanitize on: keep only mandatory attributes of module + metadata.
- */
- public static ObjectName withoutTransactionName(final ObjectName inputON) {
- checkTypeOneOf(inputON, TYPE_MODULE, TYPE_SERVICE_REFERENCE);
- if (getTransactionName(inputON) == null) {
- throw new IllegalArgumentException("Expected ObjectName with transaction:" + inputON);
- }
- if (!ON_DOMAIN.equals(inputON.getDomain())) {
- throw new IllegalArgumentException("Expected different domain: " + inputON);
- }
- Map<String, String> outputProperties;
- if (inputON.getKeyProperty(TYPE_KEY).equals(TYPE_MODULE)) {
- String moduleName = getFactoryName(inputON);
- String instanceName = getInstanceName(inputON);
- outputProperties = new HashMap<>(createModuleMap(moduleName, instanceName));
- } else {
- String serviceQName = getServiceQName(inputON);
- String refName = getReferenceName(inputON);
- outputProperties = new HashMap<>(createServiceMap(serviceQName, refName));
- }
- Map<String, String> allProperties = getAdditionalProperties(inputON);
- for (Entry<String, String> entry : allProperties.entrySet()) {
- if (entry.getKey().startsWith("X-")) {
- outputProperties.put(entry.getKey(), entry.getValue());
- }
- }
- return createON(ON_DOMAIN, outputProperties);
- }
-
- public static ObjectName withTransactionName(final ObjectName inputON, final String transactionName) {
- Map<String, String> additionalProperties = getAdditionalProperties(inputON);
- additionalProperties.put(TRANSACTION_NAME_KEY, transactionName);
- return createON(inputON.getDomain(), additionalProperties);
-
- }
-
- private static void assertDoesNotContain(final Map<String, String> additionalProperties, final String key) {
- if (additionalProperties.containsKey(key)) {
- throw new IllegalArgumentException("Map 'additionalProperties' cannot overwrite attribute " + key);
- }
- }
-
- public static ObjectName createRuntimeBeanName(final String moduleName, final String instanceName,
- final Map<String, String> additionalProperties) {
- // check that there is no overwriting of default attributes
- assertDoesNotContain(additionalProperties, MODULE_FACTORY_NAME_KEY);
- assertDoesNotContain(additionalProperties, INSTANCE_NAME_KEY);
- assertDoesNotContain(additionalProperties, TYPE_KEY);
- assertDoesNotContain(additionalProperties, TRANSACTION_NAME_KEY);
- Map<String, String> map = new HashMap<>(additionalProperties);
- map.put(MODULE_FACTORY_NAME_KEY, moduleName);
- map.put(INSTANCE_NAME_KEY, instanceName);
- map.put(TYPE_KEY, TYPE_RUNTIME_BEAN);
- return createON(ON_DOMAIN, map);
- }
-
- private static Set<String> blacklist = new HashSet<>(
- Arrays.asList(MODULE_FACTORY_NAME_KEY, INSTANCE_NAME_KEY, TYPE_KEY));
-
- public static Map<String, String> getAdditionalPropertiesOfRuntimeBeanName(final ObjectName on) {
- checkType(on, TYPE_RUNTIME_BEAN);
- Map<String, String> allProperties = getAdditionalProperties(on);
- Map<String, String> result = new HashMap<>();
- for (Entry<String, String> entry : allProperties.entrySet()) {
- if (!blacklist.contains(entry.getKey())) {
- result.put(entry.getKey(), entry.getValue());
- }
- }
- return result;
- }
-
- public static Map<String, String> getAdditionalProperties(final ObjectName on) {
- Map<String, String> keyPropertyList = on.getKeyPropertyList();
- Map<String, String> result = new HashMap<>();
- for (Entry<String, String> entry : keyPropertyList.entrySet()) {
- result.put(entry.getKey(), entry.getValue());
- }
- return result;
- }
-
- public static void checkDomain(final ObjectName objectName) {
- if (!ON_DOMAIN.equals(objectName.getDomain())) {
- throw new IllegalArgumentException("Wrong domain " + objectName);
- }
-
- }
-
- public static void checkType(final ObjectName objectName, final String type) {
- if (!type.equals(objectName.getKeyProperty(TYPE_KEY))) {
- throw new IllegalArgumentException("Wrong type, expected '" + type + "', got " + objectName);
- }
- }
-
- public static void checkTypeOneOf(final ObjectName objectName, final String... types) {
- for (String type : types) {
- if (type.equals(objectName.getKeyProperty(TYPE_KEY))) {
- return;
- }
- }
- throw new IllegalArgumentException(
- "Wrong type, expected one of " + Arrays.asList(types) + ", got " + objectName);
- }
-
- public static ObjectName createModulePattern(final String moduleName, final String instanceName) {
- String finalModuleName = moduleName == null ? ON_WILDCARD : moduleName;
- String finalInstanceName = instanceName == null ? ON_WILDCARD : instanceName;
-
- // do not return object names containing transaction name
- ObjectName namePattern = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN + ":" + ObjectNameUtil.TYPE_KEY + "="
- + ObjectNameUtil.TYPE_MODULE + "," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY + "=" + finalModuleName
- + "," + "" + ObjectNameUtil.INSTANCE_NAME_KEY + "=" + finalInstanceName);
- return namePattern;
- }
-
- public static ObjectName createModulePattern(final String ifcName, final String instanceName,
- final String transactionName) {
- String finalIfcName = ifcName == null ? ON_WILDCARD : ifcName;
- String finalInstanceName = instanceName == null ? ON_WILDCARD : instanceName;
- String finalTransactionName = transactionName == null ? ON_WILDCARD : transactionName;
-
- return ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN + ":type=Module,"
- + ObjectNameUtil.MODULE_FACTORY_NAME_KEY + "=" + finalIfcName + "," + ObjectNameUtil.INSTANCE_NAME_KEY
- + "=" + finalInstanceName + "," + ObjectNameUtil.TRANSACTION_NAME_KEY + "=" + finalTransactionName);
- }
-
- public static ObjectName createRuntimeBeanPattern(final String moduleName, final String instanceName) {
- String finalModuleName = moduleName == null ? ON_WILDCARD : moduleName;
- String finalInstanceName = instanceName == null ? ON_WILDCARD : instanceName;
-
- return ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN + ":" + ObjectNameUtil.TYPE_KEY + "="
- + ObjectNameUtil.TYPE_RUNTIME_BEAN + "," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY + "="
- + finalModuleName + "," + ObjectNameUtil.INSTANCE_NAME_KEY + "=" + finalInstanceName + ",*");
-
- }
-
- public static ModuleIdentifier fromON(final ObjectName objectName, final String expectedType) {
- checkType(objectName, expectedType);
- String factoryName = getFactoryName(objectName);
- if (factoryName == null) {
- throw new IllegalArgumentException("ObjectName does not contain module name");
- }
- String instanceName = getInstanceName(objectName);
- if (instanceName == null) {
- throw new IllegalArgumentException("ObjectName does not contain instance name");
- }
- return new ModuleIdentifier(factoryName, instanceName);
- }
-
- public static boolean isServiceReference(final ObjectName objectName) {
- return TYPE_SERVICE_REFERENCE.equals(objectName.getKeyProperty(TYPE_KEY));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.jmx;
-
-import javax.management.ObjectName;
-
-public interface ServiceReferenceMXBean {
-
- ObjectName getCurrentImplementation();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.jmx.constants;
-
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-public final class ConfigRegistryConstants {
-
- private ConfigRegistryConstants() {
- }
-
- public static final String TYPE_CONFIG_REGISTRY = "ConfigRegistry";
-
- public static final String TYPE_CONFIG_REGISTRY_NO_NOTIFICATIONS = "ConfigRegistryNoNotifications";
-
- public static final String ON_DOMAIN = "org.opendaylight.controller";
-
- public static final String TYPE_KEY = "type";
-
- public static final ObjectName OBJECT_NAME = createONWithDomainAndType(TYPE_CONFIG_REGISTRY);
-
- public static final ObjectName OBJECT_NAME_NO_NOTIFICATIONS = createONWithDomainAndType(
- TYPE_CONFIG_REGISTRY_NO_NOTIFICATIONS);
-
- public static final String GET_AVAILABLE_MODULE_NAMES_ATTRIBUT_NAME = "AvailableModuleNames";
-
- public static ObjectName createONWithDomainAndType(final String type) {
- return createON(ON_DOMAIN, TYPE_KEY, type);
- }
-
- public static ObjectName createON(final String name, final String key, final String value) {
- try {
- return new ObjectName(name, key, value);
- } catch (final MalformedObjectNameException e) {
- throw new IllegalArgumentException(e);
- }
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.api.jmx.notifications;
-
-import javax.management.NotificationBroadcasterSupport;
-
-public class CommitJMXNotification extends ConfigJMXNotification {
-
- private static final String AFTER_COMMIT_MESSAGE_TEMPLATE = "Commit successful: %s";
-
- CommitJMXNotification(final NotificationBroadcasterSupport source, final String message) {
- super(ConfigJMXNotification.NotificationType.COMMIT, source,
- String.format(AFTER_COMMIT_MESSAGE_TEMPLATE, message));
- }
-
- @Override
- public String toString() {
- return "CommitJMXNotification{}";
- }
-
- private static final long serialVersionUID = -8587623362011695514L;
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.api.jmx.notifications;
-
-import javax.management.Notification;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-public abstract class ConfigJMXNotification extends Notification {
-
- private static final long serialVersionUID = 6754474563863772845L;
-
- private static long sequenceNumber = 1;
-
- public static final String TYPE_NAME = "configfNotificationProvider";
- public static final ObjectName OBJECT_NAME = ObjectNameUtil.createONWithDomainAndType(TYPE_NAME);
-
- private final NotificationType type;
-
- protected ConfigJMXNotification(final NotificationType type, final NotificationBroadcasterSupport source,
- final String message) {
- super(type.toString(), source, sequenceNumber++, System.nanoTime(), message);
- this.type = type;
- }
-
- @Override
- public String toString() {
- return "TransactionProviderJMXNotification [type=" + type + "]";
- }
-
- /**
- * Sends this notification using source that created it.
- */
- public void send() {
- ((NotificationBroadcasterSupport) getSource()).sendNotification(this);
- }
-
- /**
- * Creates notification about successful commit execution. Intended for
- * config-persister.
- */
- public static CommitJMXNotification afterCommit(final NotificationBroadcasterSupport source,
- final String messages) {
- return new CommitJMXNotification(source, messages);
- }
-
- enum NotificationType {
- COMMIT
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.osgi;
-
-/**
- * RuntimeException thrown when an OSGi service lookup fails.
- *
- * @author Thomas Pantelis
- */
-public class ServiceNotFoundException extends RuntimeException {
- private static final long serialVersionUID = 1L;
-
- public ServiceNotFoundException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
- public ServiceNotFoundException(final String message) {
- super(message);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016, 2017 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.osgi;
-
-import java.util.concurrent.TimeUnit;
-import javax.annotation.Nonnull;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.util.tracker.ServiceTracker;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Tracker that waits for an OSGi service.
- *
- * @author Thomas Pantelis
- */
-public final class WaitingServiceTracker<T> implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(WaitingServiceTracker.class);
- public static final long FIVE_MINUTES = TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES);
-
- private final ServiceTracker<T, ?> tracker;
- private final Class<T> serviceInterface;
-
- private WaitingServiceTracker(final Class<T> serviceInterface, final ServiceTracker<T, ?> tracker) {
- this.tracker = tracker;
- this.serviceInterface = serviceInterface;
- }
-
- /**
- * Waits for an OSGi services.
- *
- * @param timeoutInMillis
- * the timeout in millis
- * @return the service instance
- * @throws ServiceNotFoundException
- * if it times out or is interrupted
- */
- @SuppressWarnings("unchecked")
- public T waitForService(final long timeoutInMillis) throws ServiceNotFoundException {
- try {
- T service = (T) tracker.waitForService(timeoutInMillis);
- if (service == null) {
- throw new ServiceNotFoundException(
- String.format("OSGi Service %s was not found after %d ms", serviceInterface, timeoutInMillis));
- }
-
- return service;
- } catch (final InterruptedException e) {
- throw new ServiceNotFoundException(
- String.format("Wait for OSGi service %s was interrrupted", serviceInterface), e);
- }
- }
-
- /**
- * Creates an instance.
- *
- * @param serviceInterface
- * the service interface
- * @param context
- * the BundleContext
- * @return new WaitingServiceTracker instance
- */
- public static <T> WaitingServiceTracker<T> create(@Nonnull final Class<T> serviceInterface,
- @Nonnull final BundleContext context) {
- ServiceTracker<T, ?> tracker = new ServiceTracker<>(context, serviceInterface, null);
- tracker.open();
- return new WaitingServiceTracker<>(serviceInterface, tracker);
- }
-
- /**
- * Creates an instance.
- *
- * @param serviceInterface
- * the service interface
- * @param context
- * the BundleContext
- * @param filter
- * the OSGi service filter
- * @return new WaitingServiceTracker instance
- */
- public static <T> WaitingServiceTracker<T> create(@Nonnull final Class<T> serviceInterface,
- @Nonnull final BundleContext context, @Nonnull final String filter) {
- String newFilter = String.format("(&(%s=%s)%s)", Constants.OBJECTCLASS, serviceInterface.getName(), filter);
- try {
- ServiceTracker<T, ?> tracker = new ServiceTracker<>(context, context.createFilter(newFilter), null);
- tracker.open();
- return new WaitingServiceTracker<>(serviceInterface, tracker);
- } catch (final InvalidSyntaxException e) {
- throw new IllegalArgumentException(String.format("Invalid OSGi filter %s", newFilter), e);
- }
- }
-
- @Override
- public void close() {
- tracker.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.runtime;
-
-import javax.management.ObjectName;
-
-public interface HierarchicalRuntimeBeanRegistration extends AutoCloseable {
-
- ObjectName getObjectName();
-
- HierarchicalRuntimeBeanRegistration register(String key, String value,
- RuntimeBean mxBean);
-
- /**
- * Unregister beans that were registered using this registrator and its
- * child registrators. This method is not idempotent, it is not allowed to
- * use this instance or child registrators after they are closed.
- */
- @Override
- void close();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.runtime;
-
-import java.io.Closeable;
-
-/**
- * Entry point for runtime bean functionality. Allows for registering root
- * runtime bean, returning an object that allows for hierarchical registrations.
- */
-public interface RootRuntimeBeanRegistrator extends Closeable {
-
- HierarchicalRuntimeBeanRegistration registerRoot(RuntimeBean mxBean);
-
- /**
- * Close all runtime beans. This method is idempotent. It is allowed to use
- * this instance to register root or create new child registrators
- * afterwards, but it is not allowed to use closed registrations.
- */
- @Override
- void close();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.runtime;
-
-/**
- * Marker interface for all runtime beans.
- */
-
-public interface RuntimeBean {
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.spi;
-
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Base implementation of Module. This implementation contains base logic for
- * Module reconfiguration with associated fields.
- *
- * @param <M>
- * Type of module implementation. Enables easier implementation for
- * the <code>isSame()</code> method
- */
-public abstract class AbstractModule<M extends AbstractModule<M>>
- implements org.opendaylight.controller.config.spi.Module {
-
- private static final Logger LOG = LoggerFactory.getLogger(AbstractModule.class);
-
- protected final DependencyResolver dependencyResolver;
- protected final ModuleIdentifier identifier;
-
- private AutoCloseable oldInstance;
- private M oldModule;
- private AutoCloseable instance;
- private boolean canReuseInstance = true;
-
- /**
- * Called when module is configured.
- *
- * @param identifier
- * id of current instance.
- * @param dependencyResolver
- * resolver used in dependency injection and validation.
- */
- public AbstractModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver) {
- this(identifier, dependencyResolver, null, null);
- }
-
- /**
- * Called when module is reconfigured.
- *
- * @param identifier
- * id of current instance.
- * @param dependencyResolver
- * resolver used in dependency injection and validation.
- * @param oldModule
- * old instance of module that is being reconfigred(replaced) by
- * current instance. The old instance can be examined for reuse.
- * @param oldInstance
- * old instance wrapped by the old module. This is the resource that
- * is actually being reused if possible or closed otherwise.
- */
- public AbstractModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver,
- final M oldModule, final AutoCloseable oldInstance) {
- this.identifier = identifier;
- this.dependencyResolver = dependencyResolver;
- this.oldModule = oldModule;
- this.oldInstance = oldInstance;
- }
-
- @Override
- public ModuleIdentifier getIdentifier() {
- return identifier;
- }
-
- public final void setCanReuseInstance(final boolean canReuseInstance) {
- this.canReuseInstance = canReuseInstance;
- }
-
- /**
- * General algorithm for spawning/closing and reusing wrapped instances.
- *
- * @return current instance of wrapped resource either by reusing the old one
- * (if present) or constructing a brand new.
- */
- @Override
- @SuppressWarnings("IllegalCatch")
- public final AutoCloseable getInstance() {
- if (instance == null) {
- if (oldInstance != null && canReuseInstance && canReuseInstance(oldModule)) {
- resolveDependencies();
- instance = reuseInstance(oldInstance);
- } else {
- if (oldInstance != null) {
- try {
- oldInstance.close();
- } catch (final Exception exception) {
- LOG.error("An error occurred while closing old instance {} for module {}", oldInstance,
- getIdentifier(), exception);
- }
- }
- resolveDependencies();
- instance = createInstance();
- if (instance == null) {
- throw new IllegalStateException(
- "Error in createInstance - null is not allowed as return value. Module: "
- + getIdentifier());
- }
- }
-
- // Prevent serial memory leak: clear these references as we will not use them
- // again.
- oldInstance = null;
- oldModule = null;
- }
-
- return instance;
- }
-
- /**
- * Create instance.
- *
- * @return Brand new instance of wrapped class in case no previous instance is
- * present or reconfiguration is impossible.
- */
- protected abstract AutoCloseable createInstance();
-
- @Override
- public final boolean canReuse(final Module prevModule) {
- // Just cast into a specific instance
- // TODO unify this method with canReuseInstance (required Module interface to be
- // generic which requires quite a lot of changes)
- return canReuseInstance && getClass().isInstance(prevModule) ? canReuseInstance((M) prevModule) : false;
- }
-
- /**
- * Users are welcome to override this method to provide custom logic for
- * advanced reusability detection.
- *
- * @param prevModule
- * old instance of a Module
- * @return true if the old instance is reusable false if a new one should be
- * spawned
- */
- protected abstract boolean canReuseInstance(M prevModule);
-
- /**
- * By default the oldInstance is returned since this method is by default called
- * only if the oldModule had the same configuration and dependencies configured.
- * Users are welcome to override this method to provide custom logic for
- * advanced reusability.
- *
- * @param prevInstance
- * old instance of a class wrapped by the module
- * @return reused instance
- */
- protected AutoCloseable reuseInstance(final AutoCloseable prevInstance) {
- // implement if instance reuse should be supported. Override canReuseInstance to
- // change the criteria.
- return prevInstance;
- }
-
- /**
- * Inject all the dependencies using dependency resolver instance.
- */
- protected abstract void resolveDependencies();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.spi;
-
-import javax.annotation.concurrent.NotThreadSafe;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.yangtools.concepts.Identifiable;
-
-/**
- * Represents one service that is to be configured. These methods need to be
- * implemented in addition to the usual attribute getters/setters. Dependencies
- * should always be injected as ObjectName references to the corresponding
- * ConfigBeans.
- * <p>
- * In order to guide dependency resolution, the setter method should be
- * annotated with
- * {@link org.opendaylight.controller.config.api.annotations.RequireInterface}.
- * </p>
- * <p>
- * Thread safety note: implementations of this interface are not required to be
- * thread safe as thread safety is enforced by configuration manager.
- * </p>
- */
-@NotThreadSafe
-public interface Module extends Identifiable<ModuleIdentifier> {
- /**
- * This method will be called as first phase in two phase commit. Instance can
- * check attributes, but is not allowed to do any kind of work that could leave
- * any resources open. It is prohibited to call {@link #getInstance()} on
- * dependent {@link Module} because it would destroy separation between
- * validation and commit phase.
- *
- */
- void validate();
-
- /**
- * Returns 'live' object that was configured using this object. It is allowed to
- * call this method only after all ConfigBeans were validated. In this method
- * new resources might be opened or old instance might be modified. This method
- * must be implemented so that it returns same result for a single transaction.
- * Since Module is created per transaction this means that it must be safe to
- * cache result of first call.
- *
- *
- * @return closeable instance: After bundle update the factory might be able to
- * copy old configuration into new one without being able to cast Module
- * or the instance. Thus to clean up old instance, it will call close().
- */
- AutoCloseable getInstance();
-
- /**
- * Compare current module with oldModule and if the instance/live object
- * produced by the old module can be reused in this module as well return true.
- * Typically true should be returned if the old module had the same
- * configuration.
- *
- *
- * @param oldModule
- * old instance of Module
- * @return true if the instance produced by oldModule can be reused with current
- * instance as well.
- */
- boolean canReuse(Module oldModule);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.spi;
-
-import java.util.Set;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DependencyResolverFactory;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.osgi.framework.BundleContext;
-
-/**
- * Factory which creates {@link Module} instances. An instance of this interface
- * needs to be exported into the OSGi Service Registry. Such an instance
- * provides metadata describing services which can be published from it.
- *
- * <p>
- * Each {@link Module} can optionally be instantiated with a
- * {@link javax.management.DynamicMBean} which represents the configuration of
- * the currently running instance.
- */
-public interface ModuleFactory {
-
- /**
- * Returns the human-friendly implementation name. This value needs to be unique
- * within all implementations of all interfaces returned by
- * getImplementedInterfaces().
- *
- * @return human-friendly implementation name
- */
- String getImplementationName();
-
- /**
- * Create a new Module instance. The returned object is expected to use the
- * dependencyResolver provided when resolving ObjectNames to actual Module
- * instances.
- *
- * @param dependencyResolver
- * This resolver will return actual config mbean based on its
- * ObjectName.
- * @param bundleContext
- * Reference to OSGi bundleContext that can be used to acquire OSGi
- * services, startup configuration and other OSGi related
- * information.
- *
- * @return newly created module
- *
- */
- Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext);
-
- /**
- * Create a new Module instance. The returned object is expected to use the
- * dependencyResolver provided when resolving ObjectNames to actual Module
- * instances. A reference to an abstract view of the previous configuration is
- * also provided in the form of a {@link javax.management.DynamicMBean}.
- * Implementations should use the MBeanInfo interface to understand the
- * structure of the configuration information.
- *
- * <p>
- * Structural information impacts hot-swap operations in that in order to
- * perform such a swap the newly loaded code needs to understand the
- * previously-running instance configuration layout and how to map it onto
- * itself.
- *
- * @param dependencyResolver
- * This resolver will return actual config mbean based on its
- * ObjectName.
- * @param old
- * existing module from platform MBeanServer that is being
- * reconfigured. Implementations should inspect its attributes using
- * {@link javax.management.DynamicMBean#getAttribute(String)} and set
- * those attributes on newly created module. If reconfiguration of
- * live instances is supported, this live instance can be retreived
- * using
- * {@link org.opendaylight.controller.config.api.DynamicMBeanWithInstance#getInstance()}
- * . It is possible that casting this old instance throws
- * {@link ClassCastException} when OSGi bundle is being updated. In
- * this case, implementation should revert to creating new instance.
- * @param bundleContext
- * Reference to OSGi bundleContext that can be used to acquire OSGi
- * services, startup configuration and other OSGi related
- * information.
- *
- * @return newly created module
- * @throws Exception
- * if it is not possible to recover configuration from old. This
- * leaves server in a running state but no configuration transaction
- * can be created.
- */
- Module createModule(String instanceName, DependencyResolver dependencyResolver, DynamicMBeanWithInstance old,
- BundleContext bundleContext) throws Exception;
-
- boolean isModuleImplementingServiceInterface(Class<? extends AbstractServiceInterface> serviceInterface);
-
- Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces();
-
- /**
- * Called when ModuleFactory is registered to config manager. Useful for
- * populating the registry with pre-existing state. Since the method is called
- * for each ModuleFactory separately and transaction is committed automatically,
- * returned modules MUST be valid and commitable without any manual
- * intervention.
- *
- * @param dependencyResolverFactory
- * factory for getting dependency resolvers for each module.
- * @param bundleContext
- * Reference to OSGi bundleContext that can be used to acquire OSGi
- * services, startup configuration and other OSGi related
- * information.
- *
- * @return set of default modules. Null is not allowed.
- */
- Set<? extends Module> getDefaultModules(DependencyResolverFactory dependencyResolverFactory,
- BundleContext bundleContext);
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:config";
- prefix "config";
-
-
- description
- "This module contains the base YANG definitions for NS-OS
- configuration subsystem. The system modeled revolves around two
- major concepts: modules and services.";
-
- revision "2013-04-05" {
- description
- "Reworked to give modules their own space.";
- }
-
- revision "2013-04-03" {
- description
- "Initial revision.";
- }
-
- extension java-class {
- description
- "YANG language extension carrying the fully-qualified name of
- a Java class. Code generation tools use the provided reference
- to tie a specific construct to its Java representation.";
-
- argument "name";
- }
-
- extension disable-osgi-service-registration {
- description
- "YANG language extension that can be associated with a Service identity that
- disables advertising the service instances to the OSGi registry.";
- }
-
- extension required-identity {
- description
- "YANG language extension which indicates that a particular
- leafref, which points to a identityref, should additionally
- require the target node is actually set to a descendant to
- of a particular identity.
-
- This is a workaround to two YANG deficiencies:
- 1) not being able to leafref instances of identityref
- 2) not being able to refine an identityref
-
- This extension takes one argument, name, which MUST be the name
- of an identity. Furthermore, that identity MUST be based,
- directly or indirectly, on the identity, which is referenced by
- the leaf reference, which is annotated with this extension.";
-
- argument "name";
- }
-
- extension inner-state-bean {
- description
- "YANG language extension which indicates that a particular
- list located under module's state should be treated as a list
- of child state beans instead of just an ordinary list attribute";
- }
-
- extension provided-service {
- description
- "YANG language extension which indicates that a particular
- module provides certain service. This extension can be placed
- on identities that are based on module-type. Zero or more services
- can be provided.
- This extension takes one argument - name - which MUST be the name
- of an identity. Furthermore, this identity MUST be based on
- service-type.";
-
- argument "name";
- }
-
- extension java-name-prefix {
- description
- "YANG language extension carrying java simple class name prefix
- that will be taken into account when generating java code from
- identities that are based on module-type.";
- argument "java-prefix";
- }
-
- identity module-type {
- description
- "Module identity base type. All module identities must be derived
- from this type. A module type uniquely defines a single atomic
- component, such as an application. Each such component is assumed
- to have its unique, stable and versioned configuration structure.";
- }
-
- identity service-type {
- description
- "Service identity base type. All service identities must be
- derived from this type. A service type uniquely defines a single
- atomic API contract, such as a Java interface, a set of C
- function declarations, or similar.
-
- If the service type has a corresponding Java interface, the name
- of that interface should be attached to the derived identity MUST
- include a java-class keyword, whose name argument points to that
- interface.";
- }
-
- typedef service-type-ref {
- description
- "Internal type of references to service type identity.";
-
- type identityref {
- base service-type;
- }
- }
-
- grouping service-ref {
- description
- "Type of references to a particular service instance. This type
- can be used when defining module configuration to refer to a
- particular service instance. Containers using this grouping
- should not define anything else. The run-time implementation
- is expected to inject a reference to the service as the value
- of the container.";
-
- leaf type {
- description
- "Type of the service being referenced. Users of this grouping
- should refine this leaf with required-identity pointing to
- the actual service-type which is actually required.";
-
- mandatory true;
- type leafref {
- path "/config:services/config:service/config:type";
- }
- }
-
- leaf name {
- mandatory true;
- type leafref {
- path "/config:services/config:service[config:type=current()/../type]/config:instance/config:name";
- }
- }
- }
-
- container modules {
- description
- "Top level container encapsulating configuration of all modules.";
-
- list module {
- key "type name";
- leaf name {
- description "Unique module instance name";
- type string;
- mandatory true;
- }
-
- leaf type {
- type identityref {
- base module-type;
- }
- mandatory true;
- }
-
- choice configuration {
- mandatory true;
- config true;
- }
-
- choice state {
- config false;
- }
- }
- }
-
-
- container services {
- list service {
- key "type";
- leaf type {
- type service-type-ref;
- }
- list instance {
- key "name";
- leaf name {
- type string;
- }
-
- leaf provider {
- mandatory true;
- type leafref {
- path "/modules/module/name";
- }
- }
- }
- }
- }
-
-
-}
+++ /dev/null
-module rpc-context {
- yang-version 1;
- namespace "urn:ietf:params:xml:ns:yang:rpc-context";
- prefix "rpcx";
-
- organization "TBD";
-
- contact "TBD";
-
- description "";
-
- revision 2013-06-17 {
- description "Initial mock";
- }
-
-
- grouping rpc-context-ref {
- description "A reference to RPC context.";
- leaf context-instance {
- type instance-identifier;
- description "Pointer to the context. ";
- }
- }
-
- extension "rpc-context-instance" {
- description
- "Marks enclosing (parent) schema node as suitable RPC context.
- The argument is identity which is used to identify RPC context
- type.";
- argument "context-type";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.api;
-
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-
-public class IdentityAttributeRefTest {
-
- IdentityAttributeRef attr = new IdentityAttributeRef("attr");
-
- @Test
- public void testConstructor() throws Exception {
- String param = new String("attr");
- Assert.assertEquals(attr.getqNameOfIdentity(), param);
- }
-
- @Test(expected = NullPointerException.class)
- public void testConstructor2() throws Exception {
- new IdentityAttributeRef(null);
- }
-
- @Test
- public void testHashCode() throws Exception {
- Assert.assertEquals(attr.hashCode(), new String("attr").hashCode());
- }
-
- @Test
- public void testEqual() throws Exception {
- Assert.assertEquals(attr, attr);
- }
-
- @Test
- public void testEqual2() throws Exception {
- Assert.assertEquals(attr, new IdentityAttributeRef("attr"));
- }
-
- @Test
- public void testNotEqual() throws Exception {
- Assert.assertNotEquals(attr, new IdentityAttributeRef("different"));
- }
-
- @Test
- public void testResolveIdentity() throws Exception {
- DependencyResolver res = mock(DependencyResolver.class);
- IdentityAttributeRef identityAttributeRef = new IdentityAttributeRef("abcd");
- doReturn(SubIdentity.class).when(res).resolveIdentity(identityAttributeRef, Identity.class);
- identityAttributeRef.resolveIdentity(res, Identity.class);
- verify(res).resolveIdentity(identityAttributeRef, Identity.class);
- }
-
- @Test
- public void testValidateIdentity() throws Exception {
- DependencyResolver res = mock(DependencyResolver.class);
- JmxAttribute jmxAttr = new JmxAttribute("abc");
- doNothing().when(res).validateIdentity(attr, Identity.class, jmxAttr);
- attr.validateIdentity(res, Identity.class, jmxAttr);
- verify(res).validateIdentity(attr, Identity.class, jmxAttr);
- }
-
- interface Identity extends BaseIdentity {}
-
- interface SubIdentity extends Identity {}
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.api;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-
-import org.junit.Test;
-
-public class JmxAttributeTest {
-
- @Test
- public void testJmxAttribute() throws Exception {
- JmxAttribute attr = new JmxAttribute("test");
- assertEquals("test", attr.getAttributeName());
- }
-
- @Test
- public void testToString() throws Exception {
- JmxAttribute attr = new JmxAttribute("test");
- assertEquals(attr.toString(), new JmxAttribute("test").toString());
- }
-
- @Test(expected = NullPointerException.class)
- public void testJmxAttributeInvalid() throws Exception {
- JmxAttribute attr = new JmxAttribute(null);
- }
-
- @Test
- public void testJmxAttributeEqual() throws Exception {
- JmxAttribute a1 = new JmxAttribute("test_string");
- JmxAttribute a2 = new JmxAttribute("test_string");
- assertEquals(a1, a2);
- }
-
- @Test
- public void testJmxAttributeNotEqual() throws Exception {
- JmxAttribute a1 = new JmxAttribute("test_string");
- JmxAttribute a2 = new JmxAttribute("different");
- assertNotEquals(a1, a2);
- }
-
- @Test
- public void testJmxAttributeEqual2() throws Exception {
- JmxAttribute a1 = new JmxAttribute("test_string");
- assertNotNull(a1);
- }
-
- @Test
- public void testJmxAttributeHashCode() throws Exception {
- JmxAttribute a1 = new JmxAttribute("test_string");
- assertEquals(a1.hashCode(), new String("test_string").hashCode());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.api;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-
-import com.google.common.collect.Lists;
-import java.nio.file.AccessDeniedException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import org.hamcrest.CoreMatchers;
-import org.junit.Test;
-
-public class JmxAttributeValidationExceptionTest {
-
- private final JmxAttribute jmxAttribute = new JmxAttribute("attr1");
-
- @Test
- public void testJmxAttributeValidationExceptionElement() throws Exception {
- JmxAttribute attributeName = new JmxAttribute("attr_name");
- JmxAttributeValidationException jmxAttributeValidationException = new JmxAttributeValidationException(
- attributeName);
- assertThat(jmxAttributeValidationException.getAttributeNames(), CoreMatchers.hasItem(attributeName));
- }
-
- @Test
- public void testJmxAttributeValidationExceptionList() throws Exception {
- List<JmxAttribute> attributeNames = new ArrayList<>();
- attributeNames.add(new JmxAttribute("att1"));
- attributeNames.add(new JmxAttribute("att2"));
- attributeNames.add(new JmxAttribute("att3"));
- JmxAttributeValidationException jmxAttributeValidationException = new JmxAttributeValidationException(
- attributeNames);
- assertEquals(jmxAttributeValidationException.getAttributeNames(), attributeNames);
- }
-
- @Test
- public void testJmxAttributeValidationExceptionList2() throws Exception {
- List<JmxAttribute> attributeNames = new ArrayList<>();
- attributeNames.add(new JmxAttribute("att1"));
- attributeNames.add(new JmxAttribute("att2"));
- attributeNames.add(new JmxAttribute("att3"));
- JmxAttributeValidationException jmxAttributeValidationException = new JmxAttributeValidationException(
- "exception str", new AccessDeniedException(""), attributeNames);
- assertEquals(jmxAttributeValidationException.getAttributeNames(), attributeNames);
- }
-
- @Test
- public void testJmxAttributeValidationExceptionJmxElement() throws Exception {
- JmxAttribute attributeName = new JmxAttribute("attr_name");
- JmxAttributeValidationException jmxAttributeValidationException = new JmxAttributeValidationException(
- "exception str", new AccessDeniedException(""), attributeName);
- assertEquals(jmxAttributeValidationException.getAttributeNames(), Arrays.asList(attributeName));
- }
-
- @Test
- public void testCheckNotNull() throws Exception {
- try {
- JmxAttributeValidationException.checkNotNull(false, jmxAttribute);
- } catch (final JmxAttributeValidationException e) {
- assertJmxEx(e, jmxAttribute.getAttributeName() + " " + "message", jmxAttribute);
- }
- }
-
- @Test
- public void testCheckCondition() throws Exception {
- JmxAttributeValidationException.checkCondition(true, "message", jmxAttribute);
- }
-
- @Test(expected = JmxAttributeValidationException.class)
- public void testJmxAttributeValidationException() throws Exception {
- JmxAttributeValidationException.wrap(new Exception("tmp"), jmxAttribute);
- }
-
- @Test(expected = JmxAttributeValidationException.class)
- public void testJmxAttributeValidationException2() throws Exception {
- JmxAttributeValidationException.wrap(new Exception("tmp"), "message", jmxAttribute);
- }
-
- @Test(expected = JmxAttributeValidationException.class)
- public void testCheckConditionFalse() throws Exception {
- JmxAttributeValidationException.checkCondition(false, "message", jmxAttribute);
- }
-
- private void assertJmxEx(final JmxAttributeValidationException jmxAttributeValidationException,
- final String message, final JmxAttribute... attrNames) {
- assertEquals(message, jmxAttributeValidationException.getMessage());
- assertEquals(Lists.newArrayList(attrNames), jmxAttributeValidationException.getAttributeNames());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.api;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-
-import org.junit.Test;
-
-public class ModuleIdentifierTest {
- String fact = new String("factory");
- String inst = new String("instance");
-
- @Test(expected = IllegalArgumentException.class)
- public void testConstructor() throws Exception {
- ModuleIdentifier moduleIdentifier = new ModuleIdentifier(null, "instance");
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testConstructor2() throws Exception {
- ModuleIdentifier moduleIdentifier = new ModuleIdentifier("name", null);
- }
-
- @Test
- public void testEquals() throws Exception {
-
- ModuleIdentifier m1 = new ModuleIdentifier(fact, inst);
- assertEquals(m1, new ModuleIdentifier(fact, inst));
- }
-
- @Test
- public void testEquals2() throws Exception {
- assertNotEquals(new ModuleIdentifier(fact, inst), null);
- }
-
- @Test
- public void testEquals3() throws Exception {
- assertNotEquals(new ModuleIdentifier(fact, inst), new ModuleIdentifier(fact, "i"));
- }
-
- @Test
- public void testEquals4() throws Exception {
- assertNotEquals(new ModuleIdentifier(fact, inst), new ModuleIdentifier("f", inst));
- }
-
- @Test
- public void testEquals5() throws Exception {
- ModuleIdentifier m1 = new ModuleIdentifier(fact, inst);
- assertEquals(m1, m1);
- }
-
- @Test
- public void testHashCode() throws Exception {
- int hash = new ModuleIdentifier(fact, inst).hashCode();
- assertEquals(hash, new ModuleIdentifier("factory", "instance").hashCode());
- }
-
- @Test
- public void testToString() throws Exception {
- assertEquals(new ModuleIdentifier("factory", "instance").toString(),
- new ModuleIdentifier("factory", "instance").toString());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.api;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import com.google.common.collect.Lists;
-import java.util.Map;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class ValidationExceptionTest {
-
- private final String instance = "instance";
- private final ModuleIdentifier mi = new ModuleIdentifier("module", instance);
- private final String instance2 = "instance2";
- private final ModuleIdentifier mi2 = new ModuleIdentifier("module", instance2);
- private final String message = "ex message";
- private final Exception exception = new IllegalStateException(message);
-
- @Test
- public void testCreateFromCollectedValidationExceptions() throws Exception {
- ValidationException single = ValidationException.createForSingleException(mi, exception);
- ValidationException single2 = ValidationException.createForSingleException(mi2, exception);
-
- ValidationException collected = ValidationException
- .createFromCollectedValidationExceptions(Lists.newArrayList(single, single2));
-
- Map<String, Map<String, ValidationException.ExceptionMessageWithStackTrace>> failedMap = collected
- .getFailedValidations();
- assertEquals(1, failedMap.size());
- assertTrue(failedMap.containsKey("module"));
-
- Map<String, ValidationException.ExceptionMessageWithStackTrace> failedModule = failedMap.get("module");
- assertEquals(2, failedModule.size());
- assertTrue(failedModule.containsKey(instance));
- assertEquals(message, failedModule.get(instance).getMessage());
- assertEquals(message, failedModule.get(instance2).getMessage());
- assertEquals(failedModule.get(instance), failedModule.get(instance2));
- }
-
- @Test
- public void testCreateFromCollectedValidationExceptionsWithDuplicate() throws Exception {
- ValidationException single = ValidationException.createForSingleException(mi, exception);
- ValidationException single2 = ValidationException.createForSingleException(mi, exception);
- try {
- ValidationException.createFromCollectedValidationExceptions(Lists.newArrayList(single, single2));
- } catch (final IllegalArgumentException ex) {
- // Duplicate exception
- assertThat(ex.getMessage(), containsString("Cannot merge"));
- return;
- }
- fail("Duplicate exception should have failed");
- }
-
- @Test
- public void testGetTrace() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp =
- new ValidationException.ExceptionMessageWithStackTrace();
- exp.setStackTrace("trace");
- Assert.assertEquals(exp.getTrace(), "trace");
- }
-
- @Test
- public void testSetMessage() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp =
- new ValidationException.ExceptionMessageWithStackTrace();
- exp.setMessage("message");
- Assert.assertEquals(exp.getMessage(), "message");
- }
-
- @Test
- public void testHashCode() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp =
- new ValidationException.ExceptionMessageWithStackTrace();
- Assert.assertEquals(exp.hashCode(), new ValidationException.ExceptionMessageWithStackTrace().hashCode());
- }
-
- @Test
- public void testExceptionMessageWithStackTraceConstructor() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp = new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "string2");
- Assert.assertEquals(exp, exp);
- }
-
- @Test
- public void testExceptionMessageWithStackTraceConstructor2() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp = new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "string2");
- Assert.assertNotEquals(exp, null);
- }
-
- @Test
- public void testExceptionMessageWithStackTraceConstructor3() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp = new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "string2");
- Assert.assertNotEquals(exp, new Exception());
- }
-
- @Test
- public void testExceptionMessageWithStackTraceConstructor4() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp = new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "string2");
- Assert.assertEquals(exp, new ValidationException.ExceptionMessageWithStackTrace("string1", "string2"));
- }
-
- @Test
- public void testEqual() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp = new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "string2");
- ValidationException.ExceptionMessageWithStackTrace exp2 =
- new ValidationException.ExceptionMessageWithStackTrace(
- null, "string2");
- Assert.assertNotEquals(exp, exp2);
- }
-
- @Test
- public void testEqual2() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp = new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "string2");
- ValidationException.ExceptionMessageWithStackTrace exp2 =
- new ValidationException.ExceptionMessageWithStackTrace(
- "different", "string2");
- Assert.assertNotEquals(exp, exp2);
- }
-
- @Test
- public void testEqual3() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp = new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "string2");
- ValidationException.ExceptionMessageWithStackTrace exp2 =
- new ValidationException.ExceptionMessageWithStackTrace(
- "string1", null);
- Assert.assertNotEquals(exp, exp2);
- }
-
- @Test
- public void testEqual4() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp = new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "string2");
- ValidationException.ExceptionMessageWithStackTrace exp2 =
- new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "different");
- Assert.assertNotEquals(exp, exp2);
- }
-
- @Test
- public void testEqual5() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp = new ValidationException.ExceptionMessageWithStackTrace(
- null, "string2");
- ValidationException.ExceptionMessageWithStackTrace exp2 =
- new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "string2");
- Assert.assertNotEquals(exp, exp2);
- }
-
- @Test
- public void testEqual6() throws Exception {
- ValidationException.ExceptionMessageWithStackTrace exp = new ValidationException.ExceptionMessageWithStackTrace(
- "string1", null);
- ValidationException.ExceptionMessageWithStackTrace exp2 =
- new ValidationException.ExceptionMessageWithStackTrace(
- "string1", "string2");
- Assert.assertNotEquals(exp, exp2);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.api.jmx;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.management.ObjectName;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-public class CommitStatusTest {
- List<ObjectName> newInst = new ArrayList<>();
- List<ObjectName> reusedInst = new ArrayList<>();
- List<ObjectName> recreatedInst = new ArrayList<>();
-
- @Before
- public void setUp() throws Exception {
- newInst.add(new ObjectName("domain: key1 = value1 , key2 = value2"));
- reusedInst.add(new ObjectName("o2: key = val"));
- recreatedInst.add(new ObjectName("o3: key = k"));
- }
-
- @Test
- public void testCommitStatus() throws Exception {
- CommitStatus status = new CommitStatus(newInst, reusedInst, recreatedInst);
- Assert.assertEquals(status.getNewInstances(), newInst);
- Assert.assertEquals(status.getRecreatedInstances(), recreatedInst);
- Assert.assertEquals(status.getReusedInstances(), reusedInst);
- }
-
- @Test
- public void testEqual() throws Exception {
- CommitStatus status = new CommitStatus(newInst, reusedInst, recreatedInst);
- Assert.assertEquals(status, new CommitStatus(newInst, reusedInst, recreatedInst));
- Assert.assertEquals(status.toString(), new CommitStatus(newInst, reusedInst, recreatedInst).toString());
- Assert.assertEquals(status, status);
- }
-
- @Test
- public void testHashCode() throws Exception {
- CommitStatus status = new CommitStatus(newInst, reusedInst, recreatedInst);
- Assert.assertEquals(status.hashCode(), new CommitStatus(newInst, reusedInst, recreatedInst).hashCode());
- }
-
- @Test
- public void testNotEqual() throws Exception {
- List<ObjectName> newInst2 = new ArrayList<>();
- List<ObjectName> reusedInst2 = new ArrayList<>();
- List<ObjectName> recreatedInst2 = new ArrayList<>();
-
- newInst2.add(new ObjectName("first: key1 = value1"));
- reusedInst2.add(new ObjectName("second: key = val"));
- recreatedInst2.add(new ObjectName("third: key = k"));
-
- CommitStatus status = new CommitStatus(newInst, reusedInst, recreatedInst);
- Assert.assertNotEquals(status, null);
- Assert.assertNotEquals(status, new Object());
- Assert.assertNotEquals(status, new CommitStatus(newInst2, reusedInst, recreatedInst));
- Assert.assertNotEquals(status, new CommitStatus(newInst, reusedInst2, recreatedInst));
- Assert.assertNotEquals(status, new CommitStatus(newInst, reusedInst, recreatedInst2));
-
- CommitStatus status2 = new CommitStatus(newInst, reusedInst, recreatedInst);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.api.jmx;
-
-import org.junit.Test;
-import org.opendaylight.controller.config.api.jmx.constants.ConfigRegistryConstants;
-
-public class ConfigRegistryConstantsTest {
-
- @Test(expected = IllegalArgumentException.class)
- public void testCreateON() throws Exception {
- ConfigRegistryConstants.createON("test.<:", "asd", "asd");
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.api.jmx;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import com.google.common.base.Throwables;
-import com.google.common.collect.Maps;
-import java.util.HashMap;
-import java.util.Map;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-
-public class ObjectNameUtilTest {
-
- private String moduleName;
- private String instanceName;
-
- @Before
- public void setUp() throws Exception {
- moduleName = "module";
- instanceName = "instance";
- }
-
- @Test
- public void testServiceReferenceName() throws Exception {
- String serviceQName = "(namespace?revision=r)qname";
- String refName = "refName";
- String transaction = "transaction";
-
- ObjectName serviceReferenceON = ObjectNameUtil.createTransactionServiceON(transaction, serviceQName, refName);
- ObjectNameUtil.checkType(serviceReferenceON, ObjectNameUtil.TYPE_SERVICE_REFERENCE);
-
- assertFalse(serviceReferenceON.isPattern());
- assertEquals(serviceQName, ObjectNameUtil.getServiceQName(serviceReferenceON));
- assertEquals(refName, ObjectNameUtil.getReferenceName(serviceReferenceON));
- assertEquals(transaction, ObjectNameUtil.getTransactionName(serviceReferenceON));
- assertEquals(ObjectNameUtil.createReadOnlyServiceON(serviceQName, refName),
- ObjectNameUtil.withoutTransactionName(serviceReferenceON));
-
- serviceReferenceON = ObjectNameUtil.createReadOnlyServiceON(serviceQName, refName);
- assertFalse(serviceReferenceON.isPattern());
- assertEquals(serviceQName, ObjectNameUtil.getServiceQName(serviceReferenceON));
- assertEquals(refName, ObjectNameUtil.getReferenceName(serviceReferenceON));
- assertEquals(null, ObjectNameUtil.getTransactionName(serviceReferenceON));
- }
-
- @Test
- public void testModuleName() throws Exception {
- String txName = "transaction";
-
- ObjectName on = ObjectNameUtil.createTransactionModuleON(txName, moduleName, instanceName);
-
- ObjectNameUtil.checkDomain(on);
- ObjectNameUtil.checkType(on, ObjectNameUtil.TYPE_MODULE);
-
- assertFalse(on.isPattern());
- assertEquals(moduleName, ObjectNameUtil.getFactoryName(on));
- assertEquals(instanceName, ObjectNameUtil.getInstanceName(on));
- assertEquals(txName, ObjectNameUtil.getTransactionName(on));
- assertEquals(4, ObjectNameUtil.getAdditionalProperties(on).size());
-
- ObjectName withoutTx = ObjectNameUtil.withoutTransactionName(on);
- assertEquals(ObjectNameUtil.createReadOnlyModuleON(moduleName, instanceName), withoutTx);
- assertEquals(moduleName, ObjectNameUtil.getFactoryName(withoutTx));
- assertEquals(instanceName, ObjectNameUtil.getInstanceName(withoutTx));
- assertEquals(null, ObjectNameUtil.getTransactionName(withoutTx));
- assertEquals(on, ObjectNameUtil.withTransactionName(withoutTx, txName));
-
- ObjectName pattern = ObjectNameUtil.createModulePattern(moduleName, null);
- assertPattern(withoutTx, pattern);
- pattern = ObjectNameUtil.createModulePattern(moduleName, null, txName);
- assertPattern(on, pattern);
- }
-
- private void assertPattern(final ObjectName test, final ObjectName pattern) {
- assertTrue(pattern.isPattern());
- assertTrue(pattern.apply(test));
- }
-
- @Test
- public void testRuntimeBeanName() throws Exception {
-
- Map<String, String> properties = Maps.newHashMap();
- properties.put("p1", "value");
- properties.put("p2", "value2");
-
- ObjectName on = ObjectNameUtil.createRuntimeBeanName(moduleName, instanceName, properties);
-
- ObjectNameUtil.checkDomain(on);
- ObjectNameUtil.checkTypeOneOf(on, ObjectNameUtil.TYPE_RUNTIME_BEAN);
-
- assertFalse(on.isPattern());
- assertEquals(moduleName, ObjectNameUtil.getFactoryName(on));
- assertEquals(instanceName, ObjectNameUtil.getInstanceName(on));
- assertEquals(2, ObjectNameUtil.getAdditionalPropertiesOfRuntimeBeanName(on).size());
- assertTrue(ObjectNameUtil.getAdditionalPropertiesOfRuntimeBeanName(on).containsKey("p1"));
- assertEquals("value", ObjectNameUtil.getAdditionalPropertiesOfRuntimeBeanName(on).get("p1"));
- assertTrue(ObjectNameUtil.getAdditionalProperties(on).containsKey("p2"));
- assertEquals("value2", ObjectNameUtil.getAdditionalPropertiesOfRuntimeBeanName(on).get("p2"));
-
- ObjectName pattern = ObjectNameUtil.createRuntimeBeanPattern(null, instanceName);
- assertPattern(on, pattern);
- }
-
- @Test
- public void testModuleIdentifier() throws Exception {
- ModuleIdentifier mi = new ModuleIdentifier(moduleName, instanceName);
- ObjectName on = ObjectNameUtil.createReadOnlyModuleON(mi);
- assertEquals(moduleName, ObjectNameUtil.getFactoryName(on));
- assertEquals(instanceName, ObjectNameUtil.getInstanceName(on));
-
- assertEquals(mi, ObjectNameUtil.fromON(on, ObjectNameUtil.TYPE_MODULE));
- }
-
- @Test
- public void testChecks() throws Exception {
- final ObjectName on = ObjectNameUtil.createON("customDomain", ObjectNameUtil.TYPE_KEY,
- ObjectNameUtil.TYPE_MODULE);
-
- assertFailure(() -> ObjectNameUtil.checkTypeOneOf(on, ObjectNameUtil.TYPE_RUNTIME_BEAN,
- ObjectNameUtil.TYPE_CONFIG_TRANSACTION), IllegalArgumentException.class);
-
- assertFailure(() -> ObjectNameUtil.checkType(on, ObjectNameUtil.TYPE_RUNTIME_BEAN),
- IllegalArgumentException.class);
-
- assertFailure(() -> ObjectNameUtil.checkDomain(on), IllegalArgumentException.class);
- }
-
- @SuppressWarnings("IllegalCatch")
- private void assertFailure(final Runnable test, final Class<? extends Exception> ex) {
- try {
- test.run();
- } catch (final Exception e) {
- assertTrue("Failed with wrong exception: " + Throwables.getStackTraceAsString(e),
- e.getClass().isAssignableFrom(ex));
- return;
- }
-
- fail(test + " should have failed on " + ex);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testCreateON() throws Exception {
- ObjectNameUtil.createON(">}+!#");
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testCreateON2() throws Exception {
- Map<String, String> map = new HashMap<>();
- ObjectNameUtil.createON(">}+!#", map);
- }
-}
<dependencyManagement>
<dependencies>
<dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-manager</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-manager</artifactId>
- <version>${project.version}</version>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-netty-config</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-api</artifactId>
- <version>${project.version}</version>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-directory-adapter</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-directory-autodetect-adapter</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-directory-xml-adapter</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-feature-adapter</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-file-adapter</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-file-xml-adapter</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-plugin-parent</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager-facade-xml</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-util</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-util</artifactId>
- <version>${project.version}</version>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netty-config-api</artifactId>
- <version>${project.version}</version>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>netty-config-api</artifactId>
+ <version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netty-timer-config</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>shutdown-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>shutdown-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>threadpool-config-api</artifactId>
<artifactId>threadpool-config-impl</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-jmx-generator</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-jmx-generator</artifactId>
- <version>${project.version}</version>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-jmx-generator-plugin</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-store-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-store-impl</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-test</artifactId>
- <version>${project.version}</version>
- </dependency>
-
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>features-config</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>features-config-netty</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>features-config-persister</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-netty-features</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
-
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-api</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-core</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-manager</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-manager-facade-xml</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-netty</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-netty-config-api</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-persister</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-persister-all</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-startup</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-config-util</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
</dependencies>
</dependencyManagement>
</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>../config-parent</relativePath>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-filtering-parent</artifactId>
- <packaging>pom</packaging>
-
- <properties>
- <config.dir>src/main/config</config.dir>
- <config.filename>default-config.xml</config.filename>
- <config.file>${config.dir}/${config.filename}</config.file>
- <generated.config.dir>${project.build.directory}/generated-config</generated.config.dir>
- <generated.config.file>${generated.config.dir}/${config.filename}</generated.config.file>
- </properties>
-
- <profiles>
- <profile>
- <id>apply-filtering-before-attaching-config</id>
- <activation>
- <file>
- <exists>${config.file}</exists>
- </file>
- </activation>
- <build>
- <pluginManagement>
- <plugins>
- <plugin>
- <artifactId>maven-resources-plugin</artifactId>
- <executions>
- <execution>
- <id>copy-resources</id>
- <phase>validate</phase>
- <goals>
- <goal>copy-resources</goal>
- </goals>
- <configuration>
- <outputDirectory>${generated.config.dir}</outputDirectory>
- <resources>
- <resource>
- <directory>${config.dir}</directory>
- <filtering>true</filtering>
- </resource>
- </resources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-artifacts</id>
- <goals>
- <goal>attach-artifact</goal>
- </goals>
- <phase>package</phase>
- <configuration>
- <artifacts>
- <artifact>
- <file>${generated.config.file}</file>
- <type>xml</type>
- <classifier>config</classifier>
- </artifact>
- </artifacts>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-resources-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
-Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
-
-This program and the accompanying materials are made available under the
-terms of the Eclipse Public License v1.0 which accompanies this distribution,
-and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<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">
-
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>../config-parent</relativePath>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>config-it-base</artifactId>
- <packaging>bundle</packaging>
-
- <properties>
- <opendaylight.karaf.version>3.1.0</opendaylight.karaf.version>
- </properties>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>${project.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>opendaylight-karaf-empty</artifactId>
- <version>3.1.0</version>
- <type>zip</type>
- </dependency>
-
- <!-- Dependencies for pax exam karaf container -->
- <dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam-container-karaf</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam-junit4</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.ops4j.pax.exam</groupId>
- <artifactId>pax-exam</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.ops4j.pax.url</groupId>
- <artifactId>pax-url-aether</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>javax.inject</groupId>
- <artifactId>javax.inject</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.karaf.features</groupId>
- <artifactId>org.apache.karaf.features.core</artifactId>
- <version>${karaf.version}</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>compile</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- </plugins>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- </resource>
- </resources>
- </build>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.it.base;
-
-import static org.ops4j.pax.exam.CoreOptions.composite;
-import static org.ops4j.pax.exam.CoreOptions.maven;
-import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
-import static org.ops4j.pax.exam.CoreOptions.when;
-import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
-import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.features;
-import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration;
-import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
-
-import com.google.common.base.Stopwatch;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.management.ManagementFactory;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.internal.AssumptionViolatedException;
-import org.junit.rules.TestRule;
-import org.junit.rules.TestWatcher;
-import org.junit.runner.Description;
-import org.opendaylight.controller.config.api.ConfigRegistry;
-import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
-import org.ops4j.pax.exam.Configuration;
-import org.ops4j.pax.exam.Option;
-import org.ops4j.pax.exam.OptionUtils;
-import org.ops4j.pax.exam.karaf.options.KarafDistributionOption;
-import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel;
-import org.ops4j.pax.exam.options.MavenArtifactUrlReference;
-import org.ops4j.pax.exam.options.MavenUrlReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class AbstractConfigTestBase {
- private static final String MAVEN_REPO_LOCAL = "maven.repo.local";
- private static final String ORG_OPS4J_PAX_URL_MVN_LOCAL_REPOSITORY = "org.ops4j.pax.url.mvn.localRepository";
- private static final String ETC_ORG_OPS4J_PAX_URL_MVN_CFG = "etc/org.ops4j.pax.url.mvn.cfg";
- private static final String ETC_ORG_OPS4J_PAX_LOGGING_CFG = "etc/org.ops4j.pax.logging.cfg";
-
- private static final String PAX_EXAM_UNPACK_DIRECTORY = "target/exam";
- private static final String KARAF_DEBUG_PORT = "5005";
- private static final String KARAF_DEBUG_PROP = "karaf.debug";
- private static final String KEEP_UNPACK_DIRECTORY_PROP = "karaf.keep.unpack";
- private static final Logger LOG = LoggerFactory.getLogger(AbstractConfigTestBase.class);
- public static final String ORG_OPS4J_PAX_LOGGING_CFG = "etc/org.ops4j.pax.logging.cfg";
-
- /*
- * Default values for karaf distro type, groupId, and artifactId
- */
- private static final String KARAF_DISTRO_TYPE = "zip";
- private static final String KARAF_DISTRO_ARTIFACTID = "opendaylight-karaf-empty";
- private static final String KARAF_DISTRO_GROUPID = "org.opendaylight.odlparent";
-
- /*
- * Property names to override defaults for karaf distro artifactId, groupId,
- * version, and type
- */
- private static final String KARAF_DISTRO_VERSION_PROP = "karaf.distro.version";
- private static final String KARAF_DISTRO_TYPE_PROP = "karaf.distro.type";
- private static final String KARAF_DISTRO_ARTIFACTID_PROP = "karaf.distro.artifactId";
- private static final String KARAF_DISTRO_GROUPID_PROP = "karaf.distro.groupId";
-
- /**
- * Property file used to store the Karaf distribution version.
- */
- private static final String PROPERTIES_FILENAME = "abstractconfigtestbase.properties";
-
- /*
- * Wait up to 10s for our configured module to come up
- */
- private static final int MODULE_TIMEOUT_MILLIS = 60000;
-
- /**
- * This method need only be overridden if using the config system.
- *
- * @deprecated
- *
- * @return the config module name
- */
- @Deprecated
- public String getModuleName() {
- return null;
- }
-
- /**
- * This method need only be overridden if using the config system.
- *
- * @deprecated
- *
- * @return the config module instance name
- */
- @Deprecated
- public String getInstanceName() {
- return null;
- }
-
- public abstract MavenUrlReference getFeatureRepo();
-
- public abstract String getFeatureName();
-
- public Option getLoggingOption() {
- Option option = editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j2.logger.config-it-base.name",
- AbstractConfigTestBase.class.getPackage().getName());
- option = composite(option, editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
- "log4j2.logger.config-it-base.level",
- LogLevel.INFO.name()));
- return option;
- }
-
- /**
- * Override this method to provide more options to config.
- *
- * @return An array of additional config options
- */
- protected Option[] getAdditionalOptions() {
- return null;
- }
-
- /**
- * Returns a Log4J logging configuration property name for the given class's package name of the form
- * "log4j.logger.package_name".
- *
- * @deprecated The karaf logging provider is now Log4J2 so logging configurations must conform to the Log4J2 style.
- * This method is kept for compilation backwards compatibility but will be removed in a future release.
- */
- @Deprecated
- public String logConfiguration(final Class<?> klazz) {
- return "log4j.logger." + klazz.getPackage().getName();
- }
-
- public String getKarafDistro() {
- String groupId = System.getProperty(KARAF_DISTRO_GROUPID_PROP, KARAF_DISTRO_GROUPID);
- String artifactId = System.getProperty(KARAF_DISTRO_ARTIFACTID_PROP, KARAF_DISTRO_ARTIFACTID);
- String version = System.getProperty(KARAF_DISTRO_VERSION_PROP);
- String type = System.getProperty(KARAF_DISTRO_TYPE_PROP, KARAF_DISTRO_TYPE);
- if (version == null) {
- // We use a properties file to retrieve ${karaf.version}, instead of
- // .versionAsInProject()
- // This avoids forcing all users to depend on Karaf in their POMs
- Properties abstractConfigTestBaseProps = new Properties();
- try (InputStream abstractConfigTestBaseInputStream = Thread.currentThread().getContextClassLoader()
- .getResourceAsStream(PROPERTIES_FILENAME)) {
- abstractConfigTestBaseProps.load(abstractConfigTestBaseInputStream);
- } catch (final IOException e) {
- LOG.error("Unable to load {} to determine the Karaf version", PROPERTIES_FILENAME, e);
- }
- version = abstractConfigTestBaseProps.getProperty(KARAF_DISTRO_VERSION_PROP);
- }
- MavenArtifactUrlReference karafUrl = maven().groupId(groupId).artifactId(artifactId).version(version)
- .type(type);
- return karafUrl.getURL();
- }
-
- protected Option mvnLocalRepoOption() {
- String mvnRepoLocal = System.getProperty(MAVEN_REPO_LOCAL, "");
- LOG.info("mvnLocalRepo \"{}\"", mvnRepoLocal);
- return editConfigurationFilePut(ETC_ORG_OPS4J_PAX_URL_MVN_CFG, ORG_OPS4J_PAX_URL_MVN_LOCAL_REPOSITORY,
- mvnRepoLocal);
- }
-
- @Configuration
- public Option[] config() {
- Option[] options = new Option[] {
- when(Boolean.getBoolean(KARAF_DEBUG_PROP))
- .useOptions(KarafDistributionOption.debugConfiguration(KARAF_DEBUG_PORT, true)),
- karafDistributionConfiguration().frameworkUrl(getKarafDistro())
- .unpackDirectory(new File(PAX_EXAM_UNPACK_DIRECTORY)).useDeployFolder(false),
- when(Boolean.getBoolean(KEEP_UNPACK_DIRECTORY_PROP)).useOptions(keepRuntimeFolder()),
- features(getFeatureRepo(), getFeatureName()),
- mavenBundle("org.apache.aries.quiesce", "org.apache.aries.quiesce.api", "1.0.0"), getLoggingOption(),
- mvnLocalRepoOption(),
- editConfigurationFilePut(ETC_ORG_OPS4J_PAX_LOGGING_CFG, "log4j2.rootLogger.level", "INFO") };
- return OptionUtils.combine(options, getAdditionalOptions());
- }
-
- @Before
- @SuppressWarnings("IllegalCatch")
- public void setup() throws Exception {
- String moduleName = getModuleName();
- String instanceName = getInstanceName();
- if (moduleName == null || instanceName == null) {
- return;
- }
-
- LOG.info("Module: {} Instance: {} attempting to configure.", moduleName, instanceName);
- Stopwatch stopWatch = Stopwatch.createStarted();
- ObjectName objectName = null;
- for (int i = 0; i < MODULE_TIMEOUT_MILLIS; i++) {
- try {
- ConfigRegistry configRegistryClient = new ConfigRegistryJMXClient(
- ManagementFactory.getPlatformMBeanServer());
- objectName = configRegistryClient.lookupConfigBean(moduleName, instanceName);
- LOG.info("Module: {} Instance: {} ObjectName: {}.", moduleName, instanceName, objectName);
- break;
- } catch (final Exception e) {
- if (i < MODULE_TIMEOUT_MILLIS) {
- Thread.sleep(1);
- continue;
- } else {
- throw e;
- }
- }
- }
- if (objectName != null) {
- LOG.info("Module: {} Instance: {} configured after {} ms", moduleName, instanceName,
- stopWatch.elapsed(TimeUnit.MILLISECONDS));
- } else {
- throw new RuntimeException("NOT FOUND Module: " + moduleName + " Instance: " + instanceName
- + " configured after " + stopWatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
- }
- }
-
- @Rule
- public TestRule watcher = new TestWatcher() {
- @Override
- protected void starting(final Description description) {
- LOG.info("TestWatcher: Starting test: {}", description.getDisplayName());
- }
-
- @Override
- protected void finished(final Description description) {
- LOG.info("TestWatcher: Finished test: {}", description.getDisplayName());
- }
-
- @Override
- protected void succeeded(final Description description) {
- LOG.info("TestWatcher: Test succeeded: {}", description.getDisplayName());
- }
-
- @Override
- protected void failed(final Throwable ex, final Description description) {
- LOG.info("TestWatcher: Test failed: {}", description.getDisplayName(), ex);
- }
-
- @Override
- protected void skipped(final AssumptionViolatedException ex, final Description description) {
- LOG.info("TestWatcher: Test skipped: {} ", description.getDisplayName(), ex);
- }
- };
-}
+++ /dev/null
-karaf.distro.version=${opendaylight.karaf.version}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <artifactId>config-subsystem</artifactId>
- <groupId>org.opendaylight.controller</groupId>
- <version>0.9.0-SNAPSHOT</version>
- </parent>
- <artifactId>config-manager-facade-xml</artifactId>
- <name>${project.artifactId}</name>
- <packaging>bundle</packaging>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-binding-generator-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-Activator>org.opendaylight.controller.config.facade.xml.osgi.YangStoreActivator</Bundle-Activator>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml;
-
-import java.util.Set;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-
-public class CandidateDatastoreQueryStrategy implements DatastoreQueryStrategy {
-
- private final TransactionProvider transactionProvider;
-
- public CandidateDatastoreQueryStrategy(final TransactionProvider transactionProvider) {
- this.transactionProvider = transactionProvider;
- }
-
- @Override
- public Set<ObjectName> queryInstances(final ConfigRegistryClient configRegistryClient) {
- ObjectName on = transactionProvider.getOrCreateTransaction();
- ConfigTransactionClient proxy = configRegistryClient.getConfigTransactionClient(on);
- return proxy.lookupConfigBeans();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml;
-
-import com.google.common.collect.Multimap;
-import java.util.Map;
-import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementDefinition;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementResolved;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Services;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-
-public class ConfigExecution {
-
- private final TestOption testOption;
- private final EditStrategyType defaultEditStrategyType;
- private final Services services;
- private final Config configResolver;
- private final XmlElement configElement;
-
- public ConfigExecution(final Config configResolver, final XmlElement configElement, final TestOption testOption,
- final EditStrategyType defaultStrategy) throws DocumentedException {
- Config.checkUnrecognisedChildren(configElement);
- this.configResolver = configResolver;
- this.configElement = configElement;
- this.services = configResolver.fromXmlServices(configElement);
- this.testOption = testOption;
- this.defaultEditStrategyType = defaultStrategy;
- }
-
- public boolean shouldTest() {
- return testOption == TestOption.testOnly || testOption == TestOption.testThenSet;
- }
-
- public boolean shouldSet() {
- return testOption == TestOption.set || testOption == TestOption.testThenSet;
- }
-
- public Map<String, Multimap<String, ModuleElementResolved>> getResolvedXmlElements(
- final ServiceReferenceReadableRegistry serviceRegistry) throws DocumentedException {
- return configResolver.fromXmlModulesResolved(configElement, defaultEditStrategyType,
- getServiceRegistryWrapper(serviceRegistry));
- }
-
- public ServiceRegistryWrapper getServiceRegistryWrapper(final ServiceReferenceReadableRegistry serviceRegistry) {
- // TODO cache service registry
- return new ServiceRegistryWrapper(serviceRegistry);
- }
-
- public Map<String, Multimap<String, ModuleElementDefinition>> getModulesDefinition(
- final ServiceReferenceReadableRegistry serviceRegistry) throws DocumentedException {
- return configResolver.fromXmlModulesMap(configElement, defaultEditStrategyType,
- getServiceRegistryWrapper(serviceRegistry));
- }
-
- public EditStrategyType getDefaultStrategy() {
- return defaultEditStrategyType;
- }
-
- public Services getServices() {
- return services;
- }
-
- public XmlElement getConfigElement() {
- return configElement;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Multimap;
-import java.io.Closeable;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
-import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfig;
-import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfigElementResolved;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleConfig;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementDefinition;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementResolved;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Services;
-import org.opendaylight.controller.config.facade.xml.osgi.YangStoreContext;
-import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
-import org.opendaylight.controller.config.facade.xml.runtime.InstanceRuntime;
-import org.opendaylight.controller.config.facade.xml.runtime.ModuleRuntime;
-import org.opendaylight.controller.config.facade.xml.runtime.Runtime;
-import org.opendaylight.controller.config.facade.xml.strategy.EditConfigStrategy;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
-import org.opendaylight.controller.config.util.BeanReader;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-/**
- * Config subsystem facade for xml format.
- *
- * <p>
- * TODO extract generic interface for config subsystem facades
- */
-public class ConfigSubsystemFacade implements Closeable {
-
- private static final Logger LOG = LoggerFactory.getLogger(ConfigSubsystemFacade.class);
- private final YangStoreService yangStoreService;
- private final TransactionProvider transactionProvider;
- private final ConfigRegistryClient configRegistryClient;
- private final ConfigRegistryClient configRegistryClientNoNotifications;
- private final RpcFacade rpcFacade;
-
- public ConfigSubsystemFacade(final ConfigRegistryClient configRegistryClient,
- final ConfigRegistryClient configRegistryClientNoNotifications,
- final YangStoreService yangStoreService,
- final String id) {
- this.configRegistryClient = configRegistryClient;
- this.configRegistryClientNoNotifications = configRegistryClientNoNotifications;
- this.yangStoreService = yangStoreService;
- this.transactionProvider = new TransactionProvider(configRegistryClient, id);
- rpcFacade = new RpcFacade(yangStoreService, configRegistryClient);
- }
-
- public ConfigSubsystemFacade(final ConfigRegistryClient configRegistryClient,
- final ConfigRegistryClient configRegistryClientNoNotifications,
- final YangStoreService yangStoreService,
- final TransactionProvider txProvider) {
- this.configRegistryClient = configRegistryClient;
- this.configRegistryClientNoNotifications = configRegistryClientNoNotifications;
- this.yangStoreService = yangStoreService;
- this.transactionProvider = txProvider;
- rpcFacade = new RpcFacade(yangStoreService, configRegistryClient);
- }
-
- public Element getConfiguration(final Document document, final Datastore source,
- final Optional<String> maybeNamespace) {
-
- final ConfigTransactionClient registryClient;
- // Read current state from a transaction, if running is source, then start new
- // transaction just for reading
- // in case of candidate, get current transaction representing candidate
- if (source == Datastore.running) {
- final ObjectName readTx = transactionProvider.getOrCreateReadTransaction();
- registryClient = configRegistryClient.getConfigTransactionClient(readTx);
- } else {
- registryClient = configRegistryClient
- .getConfigTransactionClient(transactionProvider.getOrCreateTransaction());
- }
-
- try {
- Element dataElement = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY,
- Optional.<String>absent());
- final Set<ObjectName> instances = Datastore.getInstanceQueryStrategy(source, this.transactionProvider)
- .queryInstances(configRegistryClient);
-
- final Config configMapping = new Config(
- transformMbeToModuleConfigs(yangStoreService.getModuleMXBeanEntryMap()),
- yangStoreService.getEnumResolver());
-
- ServiceRegistryWrapper serviceTracker = new ServiceRegistryWrapper(registryClient);
- dataElement = configMapping.toXml(instances, maybeNamespace, document, dataElement, serviceTracker);
-
- return dataElement;
- } finally {
- if (source == Datastore.running) {
- transactionProvider.closeReadTransaction();
- }
- }
- }
-
- public void executeConfigExecution(final ConfigExecution configExecution)
- throws DocumentedException, ValidationException {
- if (configExecution.shouldTest()) {
- executeTests(configExecution);
- }
-
- if (configExecution.shouldSet()) {
- executeSet(configExecution);
- }
- }
-
- public CommitStatus commitTransaction()
- throws DocumentedException, ValidationException, ConflictingVersionException {
- final CommitStatus status = this.transactionProvider.commitTransaction();
- LOG.trace("Transaction committed successfully: {}", status);
- return status;
- }
-
- public CommitStatus commitSilentTransaction()
- throws DocumentedException, ValidationException, ConflictingVersionException {
- final CommitStatus status = this.transactionProvider.commitTransaction(configRegistryClientNoNotifications);
- LOG.trace("Transaction committed successfully: {}", status);
- return status;
- }
-
- private void executeSet(final ConfigExecution configExecution) throws DocumentedException {
- set(configExecution);
- LOG.debug("Set phase for {} operation successful, element: ", configExecution.getDefaultStrategy(),
- configExecution.getConfigElement());
- }
-
- private void executeTests(final ConfigExecution configExecution) throws DocumentedException, ValidationException {
- test(configExecution, configExecution.getDefaultStrategy());
- LOG.debug("Test phase for {} operation successful, element: ", configExecution.getDefaultStrategy(),
- configExecution.getConfigElement());
- }
-
- private void test(final ConfigExecution execution, final EditStrategyType editStrategyType)
- throws ValidationException, DocumentedException {
- ObjectName taON = transactionProvider.getTestTransaction();
- try {
- // default strategy = replace wipes config
- if (editStrategyType == EditStrategyType.replace) {
- transactionProvider.wipeTestTransaction(taON);
- }
-
- ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
-
- handleMisssingInstancesOnTransaction(ta, execution);
- setServicesOnTransaction(ta, execution);
- setOnTransaction(ta, execution);
- transactionProvider.validateTestTransaction(taON);
- } finally {
- transactionProvider.abortTestTransaction(taON);
- }
- }
-
- private void set(final ConfigExecution configExecution) throws DocumentedException {
- ObjectName taON = transactionProvider.getOrCreateTransaction();
-
- // default strategy = replace wipes config
- if (configExecution.getDefaultStrategy() == EditStrategyType.replace) {
- transactionProvider.wipeTransaction();
- }
-
- ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
-
- handleMisssingInstancesOnTransaction(ta, configExecution);
- setServicesOnTransaction(ta, configExecution);
- setOnTransaction(ta, configExecution);
- }
-
- private static void setServicesOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution)
- throws DocumentedException {
- Services services = execution.getServices();
-
- Map<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceNameToRefNameToInstance =
- services.getNamespaceToServiceNameToRefNameToInstance();
-
- for (Map.Entry<String, Map<String, Map<String, Services.ServiceInstance>>>
- namespaceToServiceToRefEntry : namespaceToServiceNameToRefNameToInstance
- .entrySet()) {
- for (Map.Entry<String, Map<String, Services.ServiceInstance>> serviceToRefEntry
- : namespaceToServiceToRefEntry.getValue().entrySet()) {
- String qnameOfService = getQname(ta, namespaceToServiceToRefEntry.getKey(), serviceToRefEntry.getKey());
- Map<String, Services.ServiceInstance> refNameToInstance = serviceToRefEntry.getValue();
-
- for (Map.Entry<String, Services.ServiceInstance> refNameToServiceEntry : refNameToInstance.entrySet()) {
- ObjectName on = refNameToServiceEntry.getValue().getObjectName(ta.getTransactionName());
- try {
- if (Services.ServiceInstance.EMPTY_SERVICE_INSTANCE == refNameToServiceEntry.getValue()) {
- ta.removeServiceReference(qnameOfService, refNameToServiceEntry.getKey());
- LOG.debug("Removing service {} with name {}", qnameOfService,
- refNameToServiceEntry.getKey());
- } else {
- ObjectName saved = ta.saveServiceReference(qnameOfService, refNameToServiceEntry.getKey(),
- on);
- LOG.debug("Saving service {} with on {} under name {} with service on {}", qnameOfService,
- on, refNameToServiceEntry.getKey(), saved);
- }
- } catch (final InstanceNotFoundException e) {
- throw new DocumentedException(
- String.format("Unable to edit ref name " + refNameToServiceEntry.getKey()
- + " for instance " + on, e),
- ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, ErrorSeverity.ERROR);
- }
- }
- }
- }
- }
-
- private static String getQname(final ConfigTransactionClient ta, final String namespace,
- final String serviceName) {
- return ta.getServiceInterfaceName(namespace, serviceName);
- }
-
- private static void setOnTransaction(final ConfigTransactionClient ta, final ConfigExecution execution)
- throws DocumentedException {
-
- for (Multimap<String, ModuleElementResolved> modulesToResolved : execution.getResolvedXmlElements(ta)
- .values()) {
-
- for (Map.Entry<String, ModuleElementResolved> moduleToResolved : modulesToResolved.entries()) {
- String moduleName = moduleToResolved.getKey();
-
- ModuleElementResolved moduleElementResolved = moduleToResolved.getValue();
- String instanceName = moduleElementResolved.getInstanceName();
-
- InstanceConfigElementResolved ice = moduleElementResolved.getInstanceConfigElementResolved();
- EditConfigStrategy strategy = ice.getEditStrategy();
- strategy.executeConfiguration(moduleName, instanceName, ice.getConfiguration(), ta,
- execution.getServiceRegistryWrapper(ta));
- }
- }
- }
-
- private static void handleMisssingInstancesOnTransaction(final ConfigTransactionClient ta,
- final ConfigExecution execution) throws DocumentedException {
-
- for (Multimap<String, ModuleElementDefinition> modulesToResolved : execution.getModulesDefinition(ta)
- .values()) {
- for (Map.Entry<String, ModuleElementDefinition> moduleToResolved : modulesToResolved.entries()) {
- String moduleName = moduleToResolved.getKey();
-
- ModuleElementDefinition moduleElementDefinition = moduleToResolved.getValue();
-
- EditConfigStrategy strategy = moduleElementDefinition.getEditStrategy();
- strategy.executeConfiguration(moduleName, moduleElementDefinition.getInstanceName(), null, ta,
- execution.getServiceRegistryWrapper(ta));
- }
- }
- }
-
- public Config getConfigMapping() {
- final YangStoreContext snapshot = yangStoreService.getCurrentSnapshot();
- Map<String, Map<String, ModuleConfig>> factories = transformMbeToModuleConfigs(
- snapshot.getModuleMXBeanEntryMap());
- Map<String, Map<Optional<Revision>, IdentityMapping>> identitiesMap =
- transformIdentities(snapshot.getModules());
- return new Config(factories, identitiesMap, snapshot.getEnumResolver());
- }
-
- private static Map<String, Map<Optional<Revision>, IdentityMapping>> transformIdentities(
- final Set<Module> modules) {
- Map<String, Map<Optional<Revision>, IdentityMapping>> mappedIds = new HashMap<>();
- for (Module module : modules) {
- String namespace = module.getNamespace().toString();
- Map<Optional<Revision>, IdentityMapping> revisionsByNamespace = mappedIds.computeIfAbsent(namespace,
- k -> new HashMap<>());
-
- Optional<Revision> revision = Optional.fromJavaUtil(module.getRevision());
-
- IdentityMapping identityMapping = revisionsByNamespace.computeIfAbsent(revision,
- k -> new IdentityMapping());
-
- for (IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
- identityMapping.addIdSchemaNode(identitySchemaNode);
- }
-
- }
-
- return mappedIds;
- }
-
- public Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */,
- ModuleConfig>> transformMbeToModuleConfigs(
- final Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */,
- ModuleMXBeanEntry>> mbeanentries) {
- return transformMbeToModuleConfigs(configRegistryClient, mbeanentries);
- }
-
- public Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */,
- ModuleConfig>> transformMbeToModuleConfigs(
- final BeanReader reader,
- final Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mbeanentries) {
- Map<String, Map<String, ModuleConfig>> namespaceToModuleNameToModuleConfig = new HashMap<>();
-
- for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleToMbe : mbeanentries.entrySet()) {
- for (Map.Entry<String, ModuleMXBeanEntry> moduleNameToMbe : namespaceToModuleToMbe.getValue().entrySet()) {
- String moduleName = moduleNameToMbe.getKey();
- ModuleMXBeanEntry moduleMXBeanEntry = moduleNameToMbe.getValue();
-
- ModuleConfig moduleConfig = new ModuleConfig(moduleName, new InstanceConfig(reader,
- moduleMXBeanEntry.getAttributes(), moduleMXBeanEntry.getNullableDummyContainerName()));
-
- Map<String, ModuleConfig> moduleNameToModuleConfig = namespaceToModuleNameToModuleConfig
- .computeIfAbsent(namespaceToModuleToMbe.getKey(), k -> new HashMap<>());
-
- moduleNameToModuleConfig.put(moduleName, moduleConfig);
- }
- }
-
- return namespaceToModuleNameToModuleConfig;
- }
-
- public ConfigExecution getConfigExecution(final Config configMapping, final Element xmlToBePersisted)
- throws DocumentedException {
- return new ConfigExecution(configMapping, XmlElement.fromDomElement(xmlToBePersisted), TestOption.testThenSet,
- EditStrategyType.getDefaultStrategy());
- }
-
- private Map<String, Map<String, ModuleRuntime>> createModuleRuntimes(
- final ConfigRegistryClient client,
- final Map<String, Map<String, ModuleMXBeanEntry>> mbeanentries) {
- Map<String, Map<String, ModuleRuntime>> retVal = new HashMap<>();
-
- for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : mbeanentries.entrySet()) {
-
- Map<String, ModuleRuntime> innerMap = new HashMap<>();
- Map<String, ModuleMXBeanEntry> entriesFromNamespace = namespaceToModuleEntry.getValue();
- for (Map.Entry<String, ModuleMXBeanEntry> moduleToMXEntry : entriesFromNamespace.entrySet()) {
-
- ModuleMXBeanEntry mbe = moduleToMXEntry.getValue();
-
- Map<RuntimeBeanEntry, InstanceConfig> cache = new HashMap<>();
- RuntimeBeanEntry root = null;
- for (RuntimeBeanEntry rbe : mbe.getRuntimeBeans()) {
- cache.put(rbe, new InstanceConfig(client, rbe.getYangPropertiesToTypesMap(),
- mbe.getNullableDummyContainerName()));
- if (rbe.isRoot()) {
- root = rbe;
- }
- }
-
- if (root == null) {
- continue;
- }
-
- InstanceRuntime rootInstanceRuntime = createInstanceRuntime(root, cache);
- ModuleRuntime moduleRuntime = new ModuleRuntime(rootInstanceRuntime);
- innerMap.put(moduleToMXEntry.getKey(), moduleRuntime);
- }
-
- retVal.put(namespaceToModuleEntry.getKey(), innerMap);
- }
- return retVal;
- }
-
- private InstanceRuntime createInstanceRuntime(final RuntimeBeanEntry root,
- final Map<RuntimeBeanEntry, InstanceConfig> cache) {
- Map<String, InstanceRuntime> children = new HashMap<>();
- for (RuntimeBeanEntry child : root.getChildren()) {
- children.put(child.getJavaNamePrefix(), createInstanceRuntime(child, cache));
- }
-
- return new InstanceRuntime(cache.get(root), children, createJmxToYangMap(root.getChildren()));
- }
-
- private Map<String, String> createJmxToYangMap(final List<RuntimeBeanEntry> children) {
- Map<String, String> jmxToYangNamesForChildRbe = new HashMap<>();
- for (RuntimeBeanEntry rbe : children) {
- jmxToYangNamesForChildRbe.put(rbe.getJavaNamePrefix(), rbe.getYangName());
- }
- return jmxToYangNamesForChildRbe;
- }
-
- public Element get(final Document document) throws DocumentedException {
- final ObjectName testTransaction = transactionProvider.getOrCreateReadTransaction();
- final ConfigTransactionClient txClient = configRegistryClient.getConfigTransactionClient(testTransaction);
-
- try {
- // Runtime beans are not parts of transactions and have to be queried against
- // the central registry
- final Set<ObjectName> runtimeBeans = configRegistryClient.lookupRuntimeBeans();
-
- final Set<ObjectName> configBeans = Datastore
- .getInstanceQueryStrategy(Datastore.running, transactionProvider)
- .queryInstances(configRegistryClient);
-
- final Map<String, Map<String, ModuleRuntime>> moduleRuntimes = createModuleRuntimes(configRegistryClient,
- yangStoreService.getModuleMXBeanEntryMap());
-
- final YangStoreContext yangStoreSnapshot = yangStoreService.getCurrentSnapshot();
- final Map<String, Map<String, ModuleConfig>> moduleConfigs = transformMbeToModuleConfigs(txClient,
- yangStoreSnapshot.getModuleMXBeanEntryMap());
-
- final org.opendaylight.controller.config.facade.xml.runtime.Runtime runtime = new Runtime(moduleRuntimes,
- moduleConfigs);
-
- return runtime.toXml(runtimeBeans, configBeans, document, yangStoreSnapshot.getEnumResolver());
- } finally {
- transactionProvider.closeReadTransaction();
- }
- }
-
- public void abortConfiguration() {
- if (transactionProvider.getTransaction().isPresent()) {
- this.transactionProvider.abortTransaction();
- }
- }
-
- public void validateConfiguration() throws ValidationException {
- transactionProvider.validateTransaction();
- }
-
- @Override
- public void close() {
- transactionProvider.close();
- }
-
- public RpcFacade getRpcFacade() {
- return rpcFacade;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml;
-
-import com.google.common.collect.Sets;
-import java.util.Set;
-import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.controller.config.util.capability.YangModuleCapability;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-
-public class ConfigSubsystemFacadeFactory {
-
- private final ConfigRegistryClient cfgRegClient;
- private final ConfigRegistryJMXClient cfgRegClientNoNotifications;
- private final YangStoreService yangStoreService;
-
- public ConfigSubsystemFacadeFactory(final ConfigRegistryClient cfgRegClient,
- final ConfigRegistryJMXClient jmxClientNoNotifications, final YangStoreService yangStoreService) {
- this.cfgRegClient = cfgRegClient;
- this.cfgRegClientNoNotifications = jmxClientNoNotifications;
- this.yangStoreService = yangStoreService;
- }
-
- /**
- * Create new instance of ConfigSubsystemFacade. Each instance works with a
- * dedicated transaction provider, making the instances suitable for
- * facade-per-client use.
- */
- public ConfigSubsystemFacade createFacade(final String id) {
- return new ConfigSubsystemFacade(cfgRegClient, cfgRegClientNoNotifications, yangStoreService, id);
- }
-
- public YangStoreService getYangStoreService() {
- return yangStoreService;
- }
-
- public Set<Capability> getCurrentCapabilities() {
- Set<Module> modules = yangStoreService.getModules();
- final Set<Capability> capabilities = Sets.newHashSet();
- for (Module module : modules) {
- capabilities.add(new YangModuleCapability(module, yangStoreService.getModuleSource(
- RevisionSourceIdentifier.create(module.getName(), module.getRevision()))));
- }
- return capabilities;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml;
-
-import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
-
-public enum Datastore {
-
- running, candidate;
-
- public static DatastoreQueryStrategy getInstanceQueryStrategy(final Datastore source,
- final TransactionProvider transactionProvider) {
- switch (source) {
- case running:
- return new RunningDatastoreQueryStrategy(transactionProvider);
- case candidate:
- return new CandidateDatastoreQueryStrategy(transactionProvider);
- default:
- throw new UnsupportedOperationException("Unimplemented datastore query strategy for " + source);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml;
-
-import java.util.Set;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-
-public interface DatastoreQueryStrategy {
- Set<ObjectName> queryInstances(ConfigRegistryClient configRegistryClient);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import javax.management.ObjectName;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.AttributeMappingStrategy;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.ObjectMapper;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml.ObjectXmlWriter;
-import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
-import org.opendaylight.controller.config.facade.xml.rpc.InstanceRuntimeRpc;
-import org.opendaylight.controller.config.facade.xml.rpc.ModuleRpcs;
-import org.opendaylight.controller.config.facade.xml.rpc.Rpcs;
-import org.opendaylight.controller.config.facade.xml.rpc.RuntimeRpcElementResolved;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.VoidAttribute;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class RpcFacade {
-
- public static final String CONTEXT_INSTANCE = "context-instance";
- private final YangStoreService yangStoreService;
- private final ConfigRegistryClient configRegistryClient;
-
- public RpcFacade(final YangStoreService yangStoreService, final ConfigRegistryClient configRegistryClient) {
- this.yangStoreService = yangStoreService;
- this.configRegistryClient = configRegistryClient;
- }
-
- public Rpcs mapRpcs() {
-
- final Map<String, Map<String, ModuleRpcs>> map = new HashMap<>();
-
- for (final Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : yangStoreService
- .getModuleMXBeanEntryMap().entrySet()) {
-
- Map<String, ModuleRpcs> namespaceToModules = map.computeIfAbsent(namespaceToModuleEntry.getKey(),
- k -> new HashMap<>());
-
- for (final Map.Entry<String, ModuleMXBeanEntry> moduleEntry : namespaceToModuleEntry.getValue()
- .entrySet()) {
-
- ModuleRpcs rpcMapping = namespaceToModules.computeIfAbsent(moduleEntry.getKey(),
- k -> new ModuleRpcs(yangStoreService.getEnumResolver()));
-
- final ModuleMXBeanEntry entry = moduleEntry.getValue();
-
- for (final RuntimeBeanEntry runtimeEntry : entry.getRuntimeBeans()) {
- rpcMapping.addNameMapping(runtimeEntry);
- for (final RuntimeBeanEntry.Rpc rpc : runtimeEntry.getRpcs()) {
- rpcMapping.addRpc(runtimeEntry, rpc);
- }
- }
- }
- }
-
- return new Rpcs(map);
- }
-
- public OperationExecution fromXml(final XmlElement xml) throws DocumentedException {
- final String namespace;
- namespace = xml.getNamespace();
-
- final XmlElement contextInstanceElement = xml.getOnlyChildElement(CONTEXT_INSTANCE);
- final String operationName = xml.getName();
-
- final RuntimeRpcElementResolved id = RuntimeRpcElementResolved
- .fromXpath(contextInstanceElement.getTextContent(), operationName, namespace);
-
- final Rpcs rpcs = mapRpcs();
-
- final ModuleRpcs rpcMapping = rpcs.getRpcMapping(id);
- final InstanceRuntimeRpc instanceRuntimeRpc = rpcMapping.getRpc(id.getRuntimeBeanName(), operationName);
-
- // TODO move to Rpcs after xpath attribute is redesigned
-
- final ObjectName on = id.getObjectName(rpcMapping);
- Map<String, AttributeConfigElement> attributes = instanceRuntimeRpc.fromXml(xml);
- attributes = sortAttributes(attributes, xml);
-
- return new OperationExecution(on, instanceRuntimeRpc.getName(), attributes, instanceRuntimeRpc.getReturnType(),
- namespace);
- }
-
- private Map<String, AttributeConfigElement> sortAttributes(final Map<String, AttributeConfigElement> attributes,
- final XmlElement xml) {
- final Map<String, AttributeConfigElement> sorted = new LinkedHashMap<>();
-
- for (XmlElement xmlElement : xml.getChildElements()) {
- final String name = xmlElement.getName();
- if (!CONTEXT_INSTANCE.equals(name)) { // skip context
- // instance child node
- // because it
- // specifies
- // ObjectName
- final AttributeConfigElement value = attributes.get(name);
- if (value == null) {
- throw new IllegalArgumentException("Cannot find yang mapping for node " + xmlElement);
- }
- sorted.put(name, value);
- }
- }
-
- return sorted;
- }
-
- public Object executeOperation(final OperationExecution execution) {
- final Object[] params = new Object[execution.attributes.size()];
- final String[] signature = new String[execution.attributes.size()];
-
- int index = 0;
- for (final AttributeConfigElement attribute : execution.attributes.values()) {
- final Optional<?> resolvedValueOpt = attribute.getResolvedValue();
-
- params[index] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get() : attribute.getResolvedDefaultValue();
- signature[index] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get().getClass().getName()
- : attribute.getResolvedDefaultValue().getClass().getName();
- index++;
- }
-
- return configRegistryClient.invokeMethod(execution.on, execution.operationName, params, signature);
- }
-
- public Element toXml(final Document doc, final Object result, final OperationExecution execution)
- throws DocumentedException {
- AttributeMappingStrategy<?, ? extends OpenType<?>> mappingStrategy = new ObjectMapper()
- .prepareStrategy(execution.getReturnType());
- Optional<?> mappedAttributeOpt = mappingStrategy.mapAttribute(result);
- Preconditions.checkState(mappedAttributeOpt.isPresent(), "Unable to map return value %s as %s", result,
- execution.getReturnType().getOpenType());
-
- // FIXME: multiple return values defined as leaf-list and list in yang should
- // not be wrapped in output xml element,
- // they need to be appended directly under rpc-reply element
- //
- // Either allow List of Elements to be returned from NetconfOperation or
- // pass reference to parent output xml element for netconf operations to
- // append result(s) on their own
- Element tempParent = XmlUtil.createElement(doc, "output",
- Optional.of(XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
- new ObjectXmlWriter().prepareWritingStrategy(execution.getReturnType().getAttributeYangName(),
- execution.getReturnType(), doc)
- .writeElement(tempParent, execution.getNamespace(), mappedAttributeOpt.get());
-
- XmlElement xmlElement = XmlElement.fromDomElement(tempParent);
- return xmlElement.getChildElements().size() > 1 ? tempParent : xmlElement.getOnlyChildElement().getDomElement();
- }
-
- public class OperationExecution {
-
- private final ObjectName on;
- private final String operationName;
- private final Map<String, AttributeConfigElement> attributes;
- private final AttributeIfc returnType;
- private final String namespace;
-
- public OperationExecution(final ObjectName on, final String name,
- final Map<String, AttributeConfigElement> attributes, final AttributeIfc returnType,
- final String namespace) {
- this.on = on;
- this.operationName = name;
- this.attributes = attributes;
- this.returnType = returnType;
- this.namespace = namespace;
- }
-
- public boolean isVoid() {
- return returnType == VoidAttribute.getInstance();
- }
-
- public ObjectName getOn() {
- return on;
- }
-
- public String getOperationName() {
- return operationName;
- }
-
- public Map<String, AttributeConfigElement> getAttributes() {
- return attributes;
- }
-
- public AttributeIfc getReturnType() {
- return returnType;
- }
-
- public String getNamespace() {
- return namespace;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml;
-
-import java.util.Set;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-
-public class RunningDatastoreQueryStrategy implements DatastoreQueryStrategy {
-
- private final TransactionProvider transactionProvider;
-
- public RunningDatastoreQueryStrategy(final TransactionProvider transactionProvider) {
- this.transactionProvider = transactionProvider;
- }
-
- @Override
- public Set<ObjectName> queryInstances(final ConfigRegistryClient configRegistryClient) {
- ObjectName on = transactionProvider.getOrCreateReadTransaction();
- ConfigTransactionClient proxy = configRegistryClient.getConfigTransactionClient(on);
- return proxy.lookupConfigBeans();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml;
-
-import java.util.Arrays;
-
-public enum TestOption {
- testOnly, set, testThenSet;
-
- public static TestOption getFromXmlName(final String testOptionXmlName) {
- switch (testOptionXmlName) {
- case "test-only":
- return testOnly;
- case "test-then-set":
- return testThenSet;
- case "set":
- return set;
- default:
- throw new IllegalArgumentException("Unsupported test option " + testOptionXmlName + " supported: "
- + Arrays.toString(TestOption.values()));
- }
- }
-
- public static TestOption getDefault() {
- return testThenSet;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.facade.xml.exception;
-
-import java.util.Collections;
-import java.util.Map;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-
-public class ConfigHandlingException extends DocumentedException {
- private static final long serialVersionUID = 1L;
-
- public ConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity) {
- this(message, null, errorType, errorTag, errorSeverity, Collections.emptyMap());
- }
-
- public ConfigHandlingException(final String message, final Exception cause, final ErrorType errorType,
- final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
- this(message, cause, errorType, errorTag, errorSeverity, Collections.emptyMap());
- }
-
- public ConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
- this(message, null, errorType, errorTag, errorSeverity, errorInfo);
- }
-
- public ConfigHandlingException(final String message, final Exception cause, final ErrorType errorType,
- final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
- super(message, cause, errorType, errorTag, errorSeverity, errorInfo);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.facade.xml.exception;
-
-import java.util.Collections;
-import java.util.Map;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-
-public class OperationNotPermittedException extends DocumentedException {
- private static final long serialVersionUID = 1L;
-
- public OperationNotPermittedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity) {
- this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
- }
-
- public OperationNotPermittedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
- super(message, errorType, errorTag, errorSeverity, errorInfo);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-
-public class IdentityMapping {
- private final Map<String, IdentitySchemaNode> identityNameToSchemaNode;
-
- public IdentityMapping() {
- this.identityNameToSchemaNode = Maps.newHashMap();
- }
-
- public void addIdSchemaNode(final IdentitySchemaNode node) {
- String name = node.getQName().getLocalName();
- Preconditions.checkState(!identityNameToSchemaNode.containsKey(name));
- identityNameToSchemaNode.put(name, node);
- }
-
- public boolean containsIdName(final String idName) {
- return identityNameToSchemaNode.containsKey(idName);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes;
-
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.DependencyAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
-
-public abstract class AttributeIfcSwitchStatement<T> {
-
- private AttributeIfc lastAttribute;
-
- @SuppressWarnings("checkstyle:avoidHidingCauseException")
- public T switchAttribute(final AttributeIfc attributeIfc) {
-
- this.lastAttribute = attributeIfc;
-
- OpenType<?> openType = attributeIfc.getOpenType();
-
- if (attributeIfc instanceof JavaAttribute) {
- try {
- if (((JavaAttribute) attributeIfc).getTypeDefinition() instanceof BinaryTypeDefinition) {
- return caseJavaBinaryAttribute(openType);
- } else if (((JavaAttribute) attributeIfc).isUnion()) {
- return caseJavaUnionAttribute(openType);
- } else if (((JavaAttribute) attributeIfc).isIdentityRef()) {
- return caseJavaIdentityRefAttribute(openType);
- } else if (((JavaAttribute) attributeIfc).isEnum()) {
- return caseJavaEnumAttribute(openType);
- } else {
- return caseJavaAttribute(openType);
- }
- } catch (final UnknownOpenTypeException e) {
- throw getIllegalArgumentException(attributeIfc);
- }
-
- } else if (attributeIfc instanceof DependencyAttribute) {
- return caseDependencyAttribute(((DependencyAttribute) attributeIfc).getOpenType());
- } else if (attributeIfc instanceof ListAttribute) {
- return caseListAttribute((ArrayType<?>) openType);
- } else if (attributeIfc instanceof ListDependenciesAttribute) {
- return caseListDependeciesAttribute((ArrayType<?>) openType);
- } else if (attributeIfc instanceof TOAttribute) {
- return caseTOAttribute(((TOAttribute) attributeIfc).getOpenType());
- }
-
- throw getIllegalArgumentException(attributeIfc);
- }
-
- public AttributeIfc getLastAttribute() {
- return lastAttribute;
- }
-
- protected T caseJavaIdentityRefAttribute(final OpenType<?> openType) {
- return caseJavaAttribute(openType);
- }
-
- protected T caseJavaUnionAttribute(final OpenType<?> openType) {
- return caseJavaAttribute(openType);
- }
-
- protected T caseJavaEnumAttribute(final OpenType<?> openType) {
- return caseJavaAttribute(openType);
- }
-
- protected T caseJavaBinaryAttribute(final OpenType<?> openType) {
- return caseJavaAttribute(openType);
- }
-
- private IllegalArgumentException getIllegalArgumentException(final AttributeIfc attributeIfc) {
- return new IllegalArgumentException("Unknown attribute type " + attributeIfc.getClass() + ", " + attributeIfc
- + " with open type:" + attributeIfc.getOpenType());
- }
-
- public final T caseJavaAttribute(final OpenType<?> openType) {
- if (openType instanceof SimpleType<?>) {
- return caseJavaSimpleAttribute((SimpleType<?>) openType);
- } else if (openType instanceof ArrayType<?>) {
- return caseJavaArrayAttribute((ArrayType<?>) openType);
- } else if (openType instanceof CompositeType) {
- return caseJavaCompositeAttribute((CompositeType) openType);
- }
-
- throw new UnknownOpenTypeException("Unknown attribute open type " + openType);
- }
-
- protected abstract T caseJavaSimpleAttribute(SimpleType<?> openType);
-
- protected abstract T caseJavaArrayAttribute(ArrayType<?> openType);
-
- protected abstract T caseJavaCompositeAttribute(CompositeType openType);
-
- protected abstract T caseDependencyAttribute(SimpleType<?> attributeIfc);
-
- protected abstract T caseTOAttribute(CompositeType openType);
-
- protected abstract T caseListAttribute(ArrayType<?> openType);
-
- protected abstract T caseListDependeciesAttribute(ArrayType<?> openType);
-
- private static class UnknownOpenTypeException extends RuntimeException {
- private static final long serialVersionUID = 1L;
-
- UnknownOpenTypeException(final String message) {
- super(message);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import java.util.List;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-
-public abstract class AbstractAttributeReadingStrategy implements AttributeReadingStrategy {
-
- private final String nullableDefault;
-
- public AbstractAttributeReadingStrategy(final String nullableDefault) {
- this.nullableDefault = nullableDefault;
- }
-
- public String getNullableDefault() {
- return nullableDefault;
- }
-
- @Override
- public AttributeConfigElement readElement(final List<XmlElement> configNodes) throws DocumentedException {
- if (configNodes.isEmpty()) {
- return AttributeConfigElement.createNullValue(postprocessNullableDefault(nullableDefault));
- }
- return readElementHook(configNodes);
- }
-
- abstract AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws DocumentedException;
-
- @SuppressWarnings("checkstyle:hiddenField")
- protected Object postprocessNullableDefault(final String nullableDefault) {
- return nullableDefault;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import com.google.common.collect.Lists;
-import java.util.List;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-
-public class ArrayAttributeReadingStrategy extends AbstractAttributeReadingStrategy {
-
- private final AttributeReadingStrategy innerStrategy;
-
- public ArrayAttributeReadingStrategy(final String nullableDefault, final AttributeReadingStrategy innerStrategy) {
- super(nullableDefault);
- this.innerStrategy = innerStrategy;
- }
-
- @Override
- AttributeConfigElement readElementHook(final List<XmlElement> configNodes) throws DocumentedException {
- List<Object> innerList = Lists.newArrayList();
- EditStrategyType innerEditStrategy = null;
- for (XmlElement configNode : configNodes) {
- final AttributeConfigElement attributeConfigElement = innerStrategy
- .readElement(Lists.newArrayList(configNode));
- if (attributeConfigElement.getEditStrategy().isPresent()) {
- // TODO this sets the last operation for the entire array
- innerEditStrategy = attributeConfigElement.getEditStrategy().get();
- }
- innerList.add(attributeConfigElement.getValue());
- }
- return innerEditStrategy == null ? AttributeConfigElement.create(getNullableDefault(), innerList)
- : AttributeConfigElement.create(getNullableDefault(), innerList, innerEditStrategy);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import com.google.common.base.Optional;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving.AttributeResolvingStrategy;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-
-/**
- * Parsed xml element containing configuration for one attribute of an instance
- * of some module. Contains default value extracted from yang file.
- */
-public class AttributeConfigElement {
- private final Object defaultValue;
- private final Object value;
- private final Optional<EditStrategyType> editStrategy;
-
- private Optional<?> resolvedValue;
- private Object resolvedDefaultValue;
- private String jmxName;
-
- public AttributeConfigElement(final Object defaultValue, final Object value,
- final EditStrategyType editStrategyType) {
- this.defaultValue = defaultValue;
- this.value = value;
- this.editStrategy = Optional.fromNullable(editStrategyType);
- }
-
- public void setJmxName(final String jmxName) {
- this.jmxName = jmxName;
- }
-
- public String getJmxName() {
- return jmxName;
- }
-
- public void resolveValue(final AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy,
- final String attrName) throws DocumentedException {
- resolvedValue = attributeResolvingStrategy.parseAttribute(attrName, value);
- Optional<?> resolvedDefault = attributeResolvingStrategy.parseAttribute(attrName, defaultValue);
- resolvedDefaultValue = resolvedDefault.isPresent() ? resolvedDefault.get() : null;
- }
-
- public Optional<EditStrategyType> getEditStrategy() {
- return editStrategy;
- }
-
- public static AttributeConfigElement create(final Object nullableDefault, final Object value) {
- return new AttributeConfigElement(nullableDefault, value, null);
- }
-
- public static AttributeConfigElement create(final String nullableDefault, final Object value,
- final EditStrategyType editStrategyType) {
- return new AttributeConfigElement(nullableDefault, value, editStrategyType);
- }
-
- public static AttributeConfigElement createNullValue(final Object nullableDefault) {
- return new AttributeConfigElement(nullableDefault, null, null);
- }
-
- public Object getValue() {
- return value;
- }
-
- public Object getDefaultValue() {
- return defaultValue;
- }
-
- public Optional<?> getResolvedValue() {
- return resolvedValue;
- }
-
- public Object getResolvedDefaultValue() {
- return resolvedDefaultValue;
- }
-
- @Override
- public String toString() {
- return "AttributeConfigElement [defaultValue=" + defaultValue + ", value=" + value + "]";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import java.util.List;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-
-public interface AttributeReadingStrategy {
-
- AttributeConfigElement readElement(List<XmlElement> element) throws DocumentedException;
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-
-public class CompositeAttributeReadingStrategy extends AbstractAttributeReadingStrategy {
-
- private final Map<String, AttributeReadingStrategy> innerStrategies;
-
- public CompositeAttributeReadingStrategy(final String nullableDefault,
- final Map<String, AttributeReadingStrategy> innerStrategies) {
- super(nullableDefault);
- this.innerStrategies = innerStrategies;
- }
-
- @Override
- AttributeConfigElement readElementHook(final List<XmlElement> configNodes) throws DocumentedException {
-
- Preconditions.checkState(configNodes.size() == 1, "This element should be present only once %s", configNodes);
-
- XmlElement complexElement = configNodes.get(0);
-
- Map<String, Object> innerMap = Maps.newHashMap();
-
- List<XmlElement> recognisedChildren = Lists.newArrayList();
- for (Entry<String, AttributeReadingStrategy> innerAttrEntry : innerStrategies.entrySet()) {
- List<XmlElement> childItem = complexElement.getChildElementsWithSameNamespace(innerAttrEntry.getKey());
- recognisedChildren.addAll(childItem);
-
- AttributeConfigElement resolvedInner = innerAttrEntry.getValue().readElement(childItem);
-
- Object value = resolvedInner.getValue();
- if (value == null) {
- value = resolvedInner.getDefaultValue();
- }
-
- innerMap.put(innerAttrEntry.getKey(), value);
- }
-
- complexElement.checkUnrecognisedElements(recognisedChildren);
-
- String perInstanceEditStrategy = complexElement.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
- XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
-
- return Strings.isNullOrEmpty(perInstanceEditStrategy)
- ? AttributeConfigElement.create(getNullableDefault(), innerMap)
- : AttributeConfigElement.create(getNullableDefault(), innerMap,
- EditStrategyType.valueOf(perInstanceEditStrategy));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import com.google.common.base.Preconditions;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.ObjectNameAttributeMappingStrategy;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-
-public class ObjectNameAttributeReadingStrategy extends AbstractAttributeReadingStrategy {
-
- private static final Object PREFIX_SEPARATOR = ":";
-
- public ObjectNameAttributeReadingStrategy(final String nullableDefault) {
- super(nullableDefault);
- }
-
- @Override
- AttributeConfigElement readElementHook(final List<XmlElement> configNodes) throws DocumentedException {
-
- XmlElement firstChild = configNodes.get(0);
- Preconditions.checkState(configNodes.size() == 1,
- "This element should be present only once " + firstChild + " but was " + configNodes.size());
-
- Preconditions.checkNotNull(firstChild, "Element %s should be present", firstChild);
- return AttributeConfigElement.create(getNullableDefault(), resolve(firstChild));
- }
-
- private ObjectNameAttributeMappingStrategy.MappedDependency resolve(final XmlElement firstChild)
- throws DocumentedException {
- XmlElement typeElement = firstChild.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY);
- Map.Entry<String, String> prefixNamespace = typeElement.findNamespaceOfTextContent();
-
- String serviceName = checkPrefixAndExtractServiceName(typeElement, prefixNamespace);
-
- XmlElement nameElement = firstChild.getOnlyChildElementWithSameNamespace(XmlMappingConstants.NAME_KEY);
- String dependencyName = nameElement.getTextContent();
-
- return new ObjectNameAttributeMappingStrategy.MappedDependency(prefixNamespace.getValue(), serviceName,
- dependencyName);
- }
-
- public static String checkPrefixAndExtractServiceName(final XmlElement typeElement,
- final Map.Entry<String, String> prefixNamespace) throws DocumentedException {
- String serviceName = typeElement.getTextContent();
- Preconditions.checkNotNull(prefixNamespace.getKey(), "Service %s value cannot be linked to namespace",
- XmlMappingConstants.TYPE_KEY);
- if (prefixNamespace.getKey().isEmpty()) {
- return serviceName;
- } else {
- String prefix = prefixNamespace.getKey() + PREFIX_SEPARATOR;
- Preconditions.checkState(serviceName.startsWith(prefix),
- "Service %s not correctly prefixed, expected %s, but was %s", XmlMappingConstants.TYPE_KEY, prefix,
- serviceName);
- serviceName = serviceName.substring(prefix.length());
- return serviceName;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.AttributeIfcSwitchStatement;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.yangtools.yang.common.Revision;
-
-public class ObjectXmlReader extends AttributeIfcSwitchStatement<AttributeReadingStrategy> {
-
- private String key;
- private Map<String, Map<Optional<Revision>, IdentityMapping>> identityMap;
-
- @SuppressWarnings("checkstyle:hiddenField")
- public Map<String, AttributeReadingStrategy> prepareReading(final Map<String, AttributeIfc> yangToAttrConfig,
- final Map<String, Map<Optional<Revision>, IdentityMapping>> identityMap) {
- Map<String, AttributeReadingStrategy> strategies = Maps.newHashMap();
- this.identityMap = identityMap;
-
- for (Entry<String, AttributeIfc> attributeEntry : yangToAttrConfig.entrySet()) {
- AttributeReadingStrategy strat = prepareReadingStrategy(attributeEntry.getKey(), attributeEntry.getValue());
- strategies.put(attributeEntry.getKey(), strat);
- }
- return strategies;
- }
-
- private AttributeReadingStrategy prepareReadingStrategy(final String attrKey, final AttributeIfc attributeIfc) {
- this.key = attrKey;
- return switchAttribute(attributeIfc);
- }
-
- @Override
- protected AttributeReadingStrategy caseJavaBinaryAttribute(final OpenType<?> openType) {
- return new SimpleBinaryAttributeReadingStrategy(getLastAttribute().getNullableDefault());
- }
-
- @Override
- protected AttributeReadingStrategy caseJavaUnionAttribute(final OpenType<?> openType) {
- String mappingKey = JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION;
- return new SimpleUnionAttributeReadingStrategy(getLastAttribute().getNullableDefault(), mappingKey);
- }
-
- @Override
- public AttributeReadingStrategy caseJavaSimpleAttribute(final SimpleType<?> openType) {
- return new SimpleAttributeReadingStrategy(getLastAttribute().getNullableDefault());
- }
-
- @Override
- public AttributeReadingStrategy caseJavaArrayAttribute(final ArrayType<?> openType) {
- SimpleAttributeReadingStrategy innerStrategy = new SimpleAttributeReadingStrategy(
- getLastAttribute().getNullableDefault());
- return new ArrayAttributeReadingStrategy(getLastAttribute().getNullableDefault(), innerStrategy);
- }
-
- @Override
- public AttributeReadingStrategy caseJavaCompositeAttribute(final CompositeType openType) {
- Preconditions.checkState(openType.keySet().size() == 1,
- "Unexpected number of elements for open type %s, should be 1", openType);
- String mappingKey = openType.keySet().iterator().next();
- return new SimpleCompositeAttributeReadingStrategy(getLastAttribute().getNullableDefault(), mappingKey);
- }
-
- @Override
- protected AttributeReadingStrategy caseJavaIdentityRefAttribute(final OpenType<?> openType) {
- Preconditions.checkState(openType instanceof CompositeType);
- Set<String> keys = ((CompositeType) openType).keySet();
- Preconditions.checkState(keys.size() == 1, "Unexpected number of elements for open type %s, should be 1",
- openType);
- String mappingKey = keys.iterator().next();
- return new SimpleIdentityRefAttributeReadingStrategy(getLastAttribute().getNullableDefault(), mappingKey,
- identityMap);
- }
-
- @Override
- protected AttributeReadingStrategy caseDependencyAttribute(final SimpleType<?> openType) {
- return new ObjectNameAttributeReadingStrategy(getLastAttribute().getNullableDefault());
- }
-
- @Override
- protected AttributeReadingStrategy caseTOAttribute(final CompositeType openType) {
- AttributeIfc lastAttribute = getLastAttribute();
- Preconditions.checkState(lastAttribute instanceof TOAttribute);
- Map<String, AttributeIfc> inner = ((TOAttribute) lastAttribute).getYangPropertiesToTypesMap();
-
- Map<String, AttributeReadingStrategy> innerStrategies = Maps.newHashMap();
-
- for (Entry<String, AttributeIfc> innerAttrEntry : inner.entrySet()) {
- AttributeReadingStrategy innerStrat = prepareReadingStrategy(innerAttrEntry.getKey(),
- innerAttrEntry.getValue());
- innerStrategies.put(innerAttrEntry.getKey(), innerStrat);
- }
- return new CompositeAttributeReadingStrategy(lastAttribute.getNullableDefault(), innerStrategies);
- }
-
- @Override
- protected AttributeReadingStrategy caseListAttribute(final ArrayType<?> openType) {
- AttributeIfc lastAttribute = getLastAttribute();
- Preconditions.checkState(lastAttribute instanceof ListAttribute);
- AttributeReadingStrategy innerStrategy = prepareReadingStrategy(key,
- ((ListAttribute) lastAttribute).getInnerAttribute());
- return new ArrayAttributeReadingStrategy(lastAttribute.getNullableDefault(), innerStrategy);
- }
-
- @Override
- protected AttributeReadingStrategy caseListDependeciesAttribute(final ArrayType<?> openType) {
- AttributeIfc lastAttribute = getLastAttribute();
- Preconditions.checkState(lastAttribute instanceof ListDependenciesAttribute);
- AttributeReadingStrategy innerStrategy = caseDependencyAttribute(SimpleType.OBJECTNAME);
- return new ArrayAttributeReadingStrategy(lastAttribute.getNullableDefault(), innerStrategy);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import com.google.common.base.Preconditions;
-import java.util.List;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-
-public class SimpleAttributeReadingStrategy extends AbstractAttributeReadingStrategy {
- public SimpleAttributeReadingStrategy(final String nullableDefault) {
- super(nullableDefault);
- }
-
- @Override
- AttributeConfigElement readElementHook(final List<XmlElement> configNodes) throws DocumentedException {
- XmlElement xmlElement = configNodes.get(0);
- Preconditions.checkState(configNodes.size() == 1, "This element should be present only once " + xmlElement
- + " but was " + configNodes.size());
-
- String textContent = readElementContent(xmlElement);
- return AttributeConfigElement.create(postprocessNullableDefault(getNullableDefault()),
- postprocessParsedValue(textContent));
- }
-
- protected String readElementContent(final XmlElement xmlElement) throws DocumentedException {
- return xmlElement.getTextContent();
- }
-
- @Override
- protected Object postprocessNullableDefault(final String nullableDefault) {
- return nullableDefault;
- }
-
- protected Object postprocessParsedValue(final String textContent) {
- return textContent;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import com.google.common.collect.Lists;
-import com.google.common.io.BaseEncoding;
-import java.util.List;
-
-public class SimpleBinaryAttributeReadingStrategy extends SimpleAttributeReadingStrategy {
-
- public SimpleBinaryAttributeReadingStrategy(final String nullableDefault) {
- super(nullableDefault);
- }
-
- @Override
- protected Object postprocessParsedValue(final String textContent) {
- BaseEncoding en = BaseEncoding.base64();
- byte[] decode = en.decode(textContent);
- List<String> parsed = Lists.newArrayListWithCapacity(decode.length);
- for (byte b : decode) {
- parsed.add(Byte.toString(b));
- }
- return parsed;
- }
-
- @Override
- protected Object postprocessNullableDefault(final String nullableDefault) {
- return nullableDefault == null ? null : postprocessParsedValue(nullableDefault);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import com.google.common.collect.Maps;
-import java.util.HashMap;
-
-public class SimpleCompositeAttributeReadingStrategy extends SimpleAttributeReadingStrategy {
-
- private final String key;
-
- public SimpleCompositeAttributeReadingStrategy(final String nullableDefault, final String key) {
- super(nullableDefault);
- this.key = key;
- }
-
- @Override
- protected Object postprocessParsedValue(final String textContent) {
- HashMap<String,String> map = Maps.newHashMap();
- map.put(key, textContent);
- return map;
- }
-
- @Override
- protected Object postprocessNullableDefault(final String nullableDefault) {
- return nullableDefault == null ? null : postprocessParsedValue(nullableDefault);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.net.URI;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.Revision;
-
-public class SimpleIdentityRefAttributeReadingStrategy extends SimpleAttributeReadingStrategy {
-
- private final String key;
- private final Map<String, Map<Optional<Revision>, IdentityMapping>> identityMap;
-
- public SimpleIdentityRefAttributeReadingStrategy(final String nullableDefault, final String key,
- final Map<String, Map<Optional<Revision>, IdentityMapping>> identityMap) {
- super(nullableDefault);
- this.key = key;
- this.identityMap = identityMap;
- }
-
- @Override
- protected String readElementContent(final XmlElement xmlElement) throws DocumentedException {
- Map.Entry<String, String> namespaceOfTextContent = xmlElement.findNamespaceOfTextContent();
- String content = xmlElement.getTextContent();
-
- final String namespace;
- final String localName;
- if (namespaceOfTextContent.getKey().isEmpty()) {
- localName = content;
- namespace = xmlElement.getNamespace();
- } else {
- String prefix = namespaceOfTextContent.getKey() + ":";
- Preconditions.checkArgument(content.startsWith(prefix), "Identity ref should be prefixed with \"%s\"",
- prefix);
- localName = content.substring(prefix.length());
- namespace = namespaceOfTextContent.getValue();
- }
-
- Optional<Revision> revision = null;
- Map<Optional<Revision>, IdentityMapping> revisions = identityMap.get(namespace);
- if (revisions.keySet().size() > 1) {
- for (Map.Entry<Optional<Revision>, IdentityMapping> revisionToIdentityEntry : revisions.entrySet()) {
- if (revisionToIdentityEntry.getValue().containsIdName(localName)) {
- Preconditions.checkState(revision == null,
- "Duplicate identity %s, in namespace %s, "
- + "with revisions: %s, %s detected. Cannot map attribute",
- localName, namespace, revision, revisionToIdentityEntry.getKey());
- revision = revisionToIdentityEntry.getKey();
- }
- }
- } else {
- revision = revisions.keySet().iterator().next();
- }
- return QName.create(URI.create(namespace), revision.toJavaUtil(), localName).toString();
- }
-
- @Override
- protected Object postprocessParsedValue(final String textContent) {
- HashMap<String, String> map = Maps.newHashMap();
- map.put(key, textContent);
- return map;
- }
-
- @Override
- protected Object postprocessNullableDefault(final String nullableDefault) {
- return nullableDefault == null ? null : postprocessParsedValue(nullableDefault);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import java.util.List;
-import java.util.Map;
-
-public class SimpleUnionAttributeReadingStrategy extends SimpleAttributeReadingStrategy {
-
- private final String key;
-
- public SimpleUnionAttributeReadingStrategy(final String nullableDefault, final String key) {
- super(nullableDefault);
- this.key = key;
- }
-
- @Override
- protected Object postprocessParsedValue(final String textContent) {
- char[] charArray = textContent.toCharArray();
- List<String> chars = Lists.newArrayListWithCapacity(charArray.length);
-
- for (char c : charArray) {
- chars.add(Character.toString(c));
- }
-
- Map<String, Object> map = Maps.newHashMap();
- map.put(key, chars);
- return map;
- }
-
- @Override
- protected Object postprocessNullableDefault(final String nullableDefault) {
- return nullableDefault == null ? null : postprocessParsedValue(nullableDefault);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
-
-import javax.management.openmbean.OpenType;
-
-public abstract class AbstractAttributeMappingStrategy<T, O extends OpenType<?>> implements
- AttributeMappingStrategy<T, O> {
-
- private final O attrOpenType;
-
- public AbstractAttributeMappingStrategy(final O attributeIfc) {
- this.attrOpenType = attributeIfc;
- }
-
- @Override
- public O getOpenType() {
- return attrOpenType;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import java.lang.reflect.Array;
-import java.util.List;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.OpenType;
-
-public class ArrayAttributeMappingStrategy extends AbstractAttributeMappingStrategy<List<Object>, ArrayType<?>> {
-
- private final AttributeMappingStrategy<?, ? extends OpenType<?>> innerElementStrategy;
-
- public ArrayAttributeMappingStrategy(final ArrayType<?> arrayType,
- final AttributeMappingStrategy<?, ? extends OpenType<?>> innerElementStrategy) {
- super(arrayType);
- this.innerElementStrategy = innerElementStrategy;
- }
-
- @Override
- public Optional<List<Object>> mapAttribute(final Object value) {
- if (value == null) {
- return Optional.absent();
- }
-
- Preconditions.checkArgument(value.getClass().isArray(), "Value has to be instanceof Array ");
-
- List<Object> retVal = Lists.newArrayList();
-
- for (int i = 0; i < Array.getLength(value); i++) {
- Object innerValue = Array.get(value, i);
- Optional<?> mapAttribute = innerElementStrategy.mapAttribute(innerValue);
-
- if (mapAttribute.isPresent()) {
- retVal.add(mapAttribute.get());
- }
- }
- return Optional.of(retVal);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
-
-import com.google.common.base.Optional;
-import javax.management.openmbean.OpenType;
-
-public interface AttributeMappingStrategy<T, O extends OpenType<?>> {
-
- O getOpenType();
-
- Optional<T> mapAttribute(Object object);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-import java.util.Set;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-
-public class CompositeAttributeMappingStrategy
- extends AbstractAttributeMappingStrategy<Map<String, Object>, CompositeType> {
-
- private final Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies;
- private final Map<String, String> jmxToJavaNameMapping;
-
- public CompositeAttributeMappingStrategy(final CompositeType compositeType,
- final Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies,
- final Map<String, String> jmxToJavaNameMapping) {
- super(compositeType);
- this.innerStrategies = innerStrategies;
- this.jmxToJavaNameMapping = jmxToJavaNameMapping;
- }
-
- @Override
- public Optional<Map<String, Object>> mapAttribute(final Object value) {
- if (value == null) {
- return Optional.absent();
- }
-
- Util.checkType(value, CompositeDataSupport.class);
-
- CompositeDataSupport compositeData = (CompositeDataSupport) value;
- CompositeType currentType = compositeData.getCompositeType();
- CompositeType expectedType = getOpenType();
-
- Set<String> expectedCompositeTypeKeys = expectedType.keySet();
- Set<String> currentCompositeTypeKeys = currentType.keySet();
- Preconditions.checkArgument(expectedCompositeTypeKeys.equals(currentCompositeTypeKeys),
- "Composite type mismatch, expected composite type with attributes " + expectedCompositeTypeKeys
- + " but was " + currentCompositeTypeKeys);
-
- Map<String, Object> retVal = Maps.newHashMap();
-
- for (String jmxName : jmxToJavaNameMapping.keySet()) {
- Optional<?> mapped = mapInnerAttribute(compositeData, jmxName, expectedType.getDescription(jmxName));
- if (mapped.isPresent()) {
- retVal.put(jmxToJavaNameMapping.get(jmxName), mapped.get());
- }
- }
-
- return Optional.of(retVal);
- }
-
- protected Optional<?> mapInnerAttribute(final CompositeDataSupport compositeData, final String jmxName,
- final String description) {
- Object innerValue = compositeData.get(jmxName);
-
- AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = innerStrategies.get(jmxName);
- return attributeMappingStrategy.mapAttribute(innerValue);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
-
-import com.google.common.base.Optional;
-import javax.management.openmbean.CompositeType;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-
-public class EnumAttributeMappingStrategy extends AbstractAttributeMappingStrategy<String, CompositeType> {
-
- private final EnumResolver enumResolver;
-
- public EnumAttributeMappingStrategy(final CompositeType openType, final EnumResolver enumResolver) {
- super(openType);
- this.enumResolver = enumResolver;
- }
-
- @Override
- public Optional<String> mapAttribute(final Object value) {
- if (value == null) {
- return Optional.absent();
- }
-
- String expectedClass = getOpenType().getTypeName();
- return Optional.of(enumResolver.toYang(expectedClass, value.toString()));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-import java.util.Map.Entry;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.AttributeIfcSwitchStatement;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.DependencyAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-
-public class ObjectMapper extends AttributeIfcSwitchStatement<AttributeMappingStrategy<?, ? extends OpenType<?>>> {
-
- private EnumResolver enumResolver;
-
- @SuppressWarnings("checkstyle:hiddenField")
- public Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> prepareMapping(
- final Map<String, AttributeIfc> configDefinition, final EnumResolver enumResolver) {
- this.enumResolver = Preconditions.checkNotNull(enumResolver);
- Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> strategies = Maps.newHashMap();
-
- for (Entry<String, AttributeIfc> attrEntry : configDefinition.entrySet()) {
- strategies.put(attrEntry.getKey(), prepareStrategy(attrEntry.getValue()));
- }
- return strategies;
- }
-
- public AttributeMappingStrategy<?, ? extends OpenType<?>> prepareStrategy(final AttributeIfc attributeIfc) {
-
- if (attributeIfc instanceof DependencyAttribute) {
- namespaceOfDepAttr = ((DependencyAttribute) attributeIfc).getDependency().getSie().getQName().getNamespace()
- .toString();
- } else if (attributeIfc instanceof ListDependenciesAttribute) {
- namespaceOfDepAttr = ((ListDependenciesAttribute) attributeIfc).getDependency().getSie().getQName()
- .getNamespace().toString();
- }
- return switchAttribute(attributeIfc);
- }
-
- private Map<String, String> createJmxToYangMapping(final TOAttribute attributeIfc) {
- Map<String, String> retVal = Maps.newHashMap();
- for (Entry<String, AttributeIfc> entry : attributeIfc.getJmxPropertiesToTypesMap().entrySet()) {
- retVal.put(entry.getKey(), entry.getValue().getAttributeYangName());
- }
- return retVal;
- }
-
- @Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaSimpleAttribute(final SimpleType<?> openType) {
- return new SimpleAttributeMappingStrategy(openType);
- }
-
- @Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaEnumAttribute(final OpenType<?> openType) {
- return new EnumAttributeMappingStrategy((CompositeType) openType, enumResolver);
- }
-
- @Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaArrayAttribute(final ArrayType<?> openType) {
-
- AttributeMappingStrategy<?, ? extends OpenType<?>> innerStrategy = new SimpleAttributeMappingStrategy(
- (SimpleType<?>) openType.getElementOpenType());
- return new ArrayAttributeMappingStrategy(openType, innerStrategy);
- }
-
- @Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaCompositeAttribute(
- final CompositeType openType) {
- Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies = Maps.newHashMap();
-
- Map<String, String> attributeMapping = Maps.newHashMap();
-
- for (String innerAttributeKey : openType.keySet()) {
-
- innerStrategies.put(innerAttributeKey, caseJavaAttribute(openType.getType(innerAttributeKey)));
- attributeMapping.put(innerAttributeKey, innerAttributeKey);
- }
- return new CompositeAttributeMappingStrategy(openType, innerStrategies, attributeMapping);
- }
-
- @Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaUnionAttribute(final OpenType<?> openType) {
- Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies = Maps.newHashMap();
-
- Map<String, String> attributeMapping = Maps.newHashMap();
-
- CompositeType compositeType = (CompositeType) openType;
- for (String innerAttributeKey : compositeType.keySet()) {
-
- innerStrategies.put(innerAttributeKey, caseJavaAttribute(compositeType.getType(innerAttributeKey)));
- attributeMapping.put(innerAttributeKey, innerAttributeKey);
- }
- return new UnionCompositeAttributeMappingStrategy(compositeType, innerStrategies, attributeMapping);
- }
-
- private String namespaceOfDepAttr;
-
- @Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseDependencyAttribute(final SimpleType<?> openType) {
- return new ObjectNameAttributeMappingStrategy(openType, namespaceOfDepAttr);
- }
-
- @Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseTOAttribute(final CompositeType openType) {
- Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies = Maps.newHashMap();
-
- Preconditions.checkState(getLastAttribute() instanceof TOAttribute);
- TOAttribute lastTO = (TOAttribute) getLastAttribute();
-
- for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute) getLastAttribute())
- .getJmxPropertiesToTypesMap().entrySet()) {
- innerStrategies.put(innerAttrEntry.getKey(), prepareStrategy(innerAttrEntry.getValue()));
- }
-
- return new CompositeAttributeMappingStrategy(openType, innerStrategies, createJmxToYangMapping(lastTO));
- }
-
- @Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseListAttribute(final ArrayType<?> openType) {
- Preconditions.checkState(getLastAttribute() instanceof ListAttribute);
- return new ArrayAttributeMappingStrategy(openType,
- prepareStrategy(((ListAttribute) getLastAttribute()).getInnerAttribute()));
- }
-
- @Override
- protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseListDependeciesAttribute(
- final ArrayType<?> openType) {
- Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute);
- return new ArrayAttributeMappingStrategy(openType, caseDependencyAttribute(SimpleType.OBJECTNAME));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import javax.management.ObjectName;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.opendaylight.yangtools.yang.common.QName;
-
-public class ObjectNameAttributeMappingStrategy
- extends AbstractAttributeMappingStrategy<ObjectNameAttributeMappingStrategy.MappedDependency, SimpleType<?>> {
-
- private final String namespace;
-
- public ObjectNameAttributeMappingStrategy(final SimpleType<?> openType, final String namespace) {
- super(openType);
- this.namespace = namespace;
- }
-
- @Override
- public Optional<MappedDependency> mapAttribute(final Object value) {
- if (value == null) {
- return Optional.absent();
- }
-
- String expectedClass = getOpenType().getClassName();
- String realClass = value.getClass().getName();
- Preconditions.checkArgument(realClass.equals(expectedClass),
- "Type mismatch, expected " + expectedClass + " but was " + realClass);
- Util.checkType(value, ObjectName.class);
-
- ObjectName on = (ObjectName) value;
-
- String refName = ObjectNameUtil.getReferenceName(on);
-
- // we want to use the exact service name that was configured in xml so services
- // that are referencing it can be resolved
- return Optional.of(new MappedDependency(namespace,
- QName.create(ObjectNameUtil.getServiceQName(on)).getLocalName(), refName));
- }
-
- public static class MappedDependency {
- private final String namespace;
- private final String serviceName;
- private final String refName;
-
- public MappedDependency(final String namespace, final String serviceName, final String refName) {
- this.serviceName = serviceName;
- this.refName = refName;
- this.namespace = namespace;
- }
-
- public String getServiceName() {
- return serviceName;
- }
-
- public String getRefName() {
- return refName;
- }
-
- public String getNamespace() {
- return namespace;
- }
-
- @Override
- public String toString() {
- return "MappedDependency{"
- + "namespace='" + namespace + '\''
- + ", serviceName='" + serviceName + '\''
- + ", refName='" + refName + '\''
- + '}';
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.yangtools.yang.common.Revision;
-
-public class SimpleAttributeMappingStrategy extends AbstractAttributeMappingStrategy<String, SimpleType<?>> {
-
- public SimpleAttributeMappingStrategy(final SimpleType<?> openType) {
- super(openType);
- }
-
- @Override
- public Optional<String> mapAttribute(final Object value) {
- if (value == null) {
- return Optional.absent();
- }
-
- String expectedClass = getOpenType().getClassName();
- String realClass = value.getClass().getName();
- Preconditions.checkArgument(realClass.equals(expectedClass),
- "Type mismatch, expected " + expectedClass + " but was " + realClass);
-
- WriterPlugin prefferedPlugin = WRITER_PLUGINS.get(value.getClass().getCanonicalName());
- prefferedPlugin = prefferedPlugin == null ? WRITER_PLUGINS.get(DEFAULT_WRITER_PLUGIN) : prefferedPlugin;
- return Optional.of(prefferedPlugin.writeObject(value));
- }
-
- private static final String DEFAULT_WRITER_PLUGIN = "default";
- private static final Map<String, WriterPlugin> WRITER_PLUGINS = Maps.newHashMap();
-
- static {
- WRITER_PLUGINS.put(DEFAULT_WRITER_PLUGIN, new DefaultWriterPlugin());
- WRITER_PLUGINS.put(Revision.class.getCanonicalName(), new RevisionPlugin());
- }
-
- /**
- * Custom writer plugins must implement this interface.
- */
- interface WriterPlugin {
- String writeObject(Object value);
- }
-
- static class DefaultWriterPlugin implements WriterPlugin {
-
- @Override
- public String writeObject(final Object value) {
- return value.toString();
- }
- }
-
- static class RevisionPlugin implements WriterPlugin {
-
- @Override
- public String writeObject(final Object value) {
- Preconditions.checkArgument(value instanceof Revision, "Attribute must be Date");
- return ((Revision) value).toString();
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
-
-import com.google.common.base.Optional;
-import java.util.Map;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-
-public class UnionCompositeAttributeMappingStrategy extends CompositeAttributeMappingStrategy {
-
- public UnionCompositeAttributeMappingStrategy(final CompositeType compositeType,
- final Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies,
- final Map<String, String> jmxToJavaNameMapping) {
- super(compositeType, innerStrategies, jmxToJavaNameMapping);
- }
-
- @Override
- protected Optional<?> mapInnerAttribute(final CompositeDataSupport compositeData, final String jmxName,
- final String description) {
- if (!description.equals(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION)) {
- return Optional.absent();
- }
- return super.mapInnerAttribute(compositeData, jmxName, description);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
-
-import javax.management.openmbean.OpenType;
-
-public abstract class AbstractAttributeResolvingStrategy<T, O extends OpenType<?>>
- implements AttributeResolvingStrategy<T, O> {
- private O openType;
-
- public AbstractAttributeResolvingStrategy(final O openType) {
- this.openType = openType;
- }
-
- @Override
- public O getOpenType() {
- return openType;
- }
-
- /**
- * Composite types might change during resolution. Use this setter to update
- * open type
- */
- public void setOpenType(final O openType) {
- this.openType = openType;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
-
-import com.google.common.base.Optional;
-import java.lang.reflect.Array;
-import java.util.List;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class ArrayAttributeResolvingStrategy extends AbstractAttributeResolvingStrategy<Object, ArrayType<?>> {
-
- private final AttributeResolvingStrategy<?, ? extends OpenType<?>> innerTypeResolvingStrategy;
-
- private static final Logger LOG = LoggerFactory.getLogger(ArrayAttributeResolvingStrategy.class);
-
- public ArrayAttributeResolvingStrategy(final AttributeResolvingStrategy<?, ? extends OpenType<?>> innerTypeResolved,
- final ArrayType<?> openType) {
- super(openType);
- this.innerTypeResolvingStrategy = innerTypeResolved;
- }
-
- @Override
- public Optional<Object> parseAttribute(final String attrName, final Object value) throws DocumentedException {
- if (value == null) {
- return Optional.absent();
- }
-
- Util.checkType(value, List.class);
- List<?> valueList = (List<?>) value;
-
- Class<?> innerTypeClass = null;
-
- if (innerTypeResolvingStrategy.getOpenType() instanceof CompositeType) {
- innerTypeClass = CompositeDataSupport.class;
- } else {
- try {
- innerTypeClass = Class.forName(getOpenType().getElementOpenType().getClassName());
- } catch (final ClassNotFoundException e) {
- throw new IllegalStateException(
- "Unable to locate class for " + getOpenType().getElementOpenType().getClassName(), e);
- }
- }
-
- Object parsedArray = null;
-
- if (getOpenType().isPrimitiveArray()) {
- Class<?> primitiveType = getPrimitiveType(innerTypeClass);
- parsedArray = Array.newInstance(primitiveType, valueList.size());
- } else {
- parsedArray = Array.newInstance(innerTypeClass, valueList.size());
- }
-
- int index = 0;
- for (Object innerValue : valueList) {
- Optional<?> parsedElement = innerTypeResolvingStrategy.parseAttribute(attrName + "_" + index, innerValue);
- if (!parsedElement.isPresent()) {
- continue;
- }
- Array.set(parsedArray, index, parsedElement.get());
- index++;
- }
-
- // Rebuild open type. Underlying composite types might have changed
- if (innerTypeResolvingStrategy.getOpenType() instanceof CompositeType) {
- try {
- final ArrayType<?> openType = new ArrayType<>(getOpenType().getDimension(),
- innerTypeResolvingStrategy.getOpenType());
- setOpenType(openType);
- } catch (final OpenDataException e) {
- throw new IllegalStateException("An error occurred during restoration of array type " + this
- + " for attribute " + attrName + " from value " + value, e);
- }
- }
-
- LOG.debug("Attribute {} : {} parsed to type {} as {}", attrName, value, getOpenType(),
- toStringArray(parsedArray));
-
- return Optional.of(parsedArray);
- }
-
- private static String toStringArray(final Object array) {
- StringBuilder build = new StringBuilder(array.toString());
- build.append(" [");
- for (int i = 0; i < Array.getLength(array); i++) {
- build.append(Array.get(array, i).toString());
- build.append(",");
- }
- build.append("]]");
- return build.toString();
- }
-
- private static Class<?> getPrimitiveType(final Class<?> innerTypeClass) {
- try {
- return (Class<?>) innerTypeClass.getField("TYPE").get(null);
- } catch (final IllegalAccessException | IllegalArgumentException | NoSuchFieldException e) {
- throw new IllegalStateException("Unable to determine primitive type to " + innerTypeClass, e);
- }
- }
-
- @Override
- public String toString() {
- return "ResolvedArrayTypeAttributeType [innerTypeResolved=" + innerTypeResolvingStrategy + "]";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
-
-import com.google.common.base.Optional;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-
-/**
- * Create real object from String or Map that corresponds to given opentype.
- */
-public interface AttributeResolvingStrategy<T, O extends OpenType<?>> {
- O getOpenType();
-
- Optional<T> parseAttribute(String attrName, Object value) throws DocumentedException;
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class CompositeAttributeResolvingStrategy
- extends AbstractAttributeResolvingStrategy<CompositeDataSupport, CompositeType> {
- private final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerTypes;
- private final Map<String, String> yangToJavaAttrMapping;
-
- private static final Logger LOG = LoggerFactory.getLogger(CompositeAttributeResolvingStrategy.class);
-
- CompositeAttributeResolvingStrategy(
- final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerTypes,
- final CompositeType openType, final Map<String, String> yangToJavaAttrMapping) {
- super(openType);
- this.innerTypes = innerTypes;
- this.yangToJavaAttrMapping = yangToJavaAttrMapping;
- }
-
- @Override
- public String toString() {
- return "ResolvedCompositeAttribute [" + innerTypes + "]";
- }
-
- @Override
- public Optional<CompositeDataSupport> parseAttribute(final String attrName, final Object value)
- throws DocumentedException {
-
- if (value == null) {
- return Optional.absent();
- }
-
- Util.checkType(value, Map.class);
- Map<?, ?> valueMap = (Map<?, ?>) value;
- valueMap = preprocessValueMap(valueMap);
-
- Map<String, Object> items = Maps.newHashMap();
- Map<String, OpenType<?>> openTypes = Maps.newHashMap();
-
- final String[] names = new String[getOpenType().keySet().size()];
- final String[] descriptions = new String[getOpenType().keySet().size()];
- OpenType<?>[] itemTypes = new OpenType[names.length];
- int index = 0;
-
- for (Object innerAttrName : innerTypes.keySet()) {
- Preconditions.checkState(innerAttrName instanceof String, "Attribute name must be string");
- String innerAttrNameStr = (String) innerAttrName;
-
- AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy = innerTypes
- .get(innerAttrName);
-
- Object valueToParse = valueMap.get(innerAttrName);
-
- Optional<?> parsedInnerValue = attributeResolvingStrategy.parseAttribute(innerAttrNameStr, valueToParse);
-
- if (attributeResolvingStrategy instanceof EnumAttributeResolvingStrategy) {
- // Open type for enum contain the class name necessary for its resolution,
- // however in a DTO
- // the open type need to be just SimpleType.STRING so that JMX is happy
- // After the enum attribute is resolved, change its open type back to STRING
- openTypes.put(innerAttrNameStr, SimpleType.STRING);
- } else {
- openTypes.put(innerAttrNameStr, attributeResolvingStrategy.getOpenType());
- }
-
- items.put(yangToJavaAttrMapping.get(innerAttrNameStr),
- parsedInnerValue.isPresent() ? parsedInnerValue.get() : null);
-
- // fill names + item types in order to reconstruct the open type for current
- // attribute
- names[index] = yangToJavaAttrMapping.get(innerAttrNameStr);
- descriptions[index] = getOpenType().getDescription(names[index]);
- itemTypes[index] = openTypes.get(innerAttrNameStr);
- index++;
- }
-
- CompositeDataSupport parsedValue;
- try {
- LOG.trace("Attribute {} with open type {}. Reconstructing open type.", attrName, getOpenType());
- setOpenType(new CompositeType(getOpenType().getTypeName(), getOpenType().getDescription(), names,
- descriptions, itemTypes));
- LOG.debug("Attribute {}. Open type reconstructed to {}", attrName, getOpenType(), getOpenType());
- parsedValue = new CompositeDataSupport(getOpenType(), items);
- } catch (final OpenDataException e) {
- throw new IllegalStateException("An error occurred during restoration of composite type " + this
- + " for attribute " + attrName + " from value " + value, e);
- }
-
- LOG.debug("Attribute {} : {} parsed to type {} as {}", attrName, value, getOpenType(), parsedValue);
-
- return Optional.of(parsedValue);
- }
-
- protected Map<?, ?> preprocessValueMap(final Map<?, ?> valueMap) {
- return valueMap;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import java.util.Map;
-import javax.management.openmbean.CompositeType;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-final class EnumAttributeResolvingStrategy extends AbstractAttributeResolvingStrategy<Object, CompositeType> {
-
- private static final Logger LOG = LoggerFactory.getLogger(EnumAttributeResolvingStrategy.class);
- private final EnumResolver enumResolver;
-
- EnumAttributeResolvingStrategy(final CompositeType simpleType, final EnumResolver enumResolver) {
- super(simpleType);
- this.enumResolver = enumResolver;
- }
-
- @Override
- public String toString() {
- return "ResolvedEnumAttribute [" + getOpenType().getClassName() + "]";
- }
-
- @Override
- public Optional<Object> parseAttribute(final String attrName, final Object value) throws DocumentedException {
- if (value == null) {
- return Optional.absent();
- }
- Util.checkType(value, Map.class);
- Map<?, ?> valueMap = (Map<?, ?>) value;
- Preconditions.checkArgument(valueMap.size() == 1,
- "Unexpected value size " + value + " should be just 1 foe enum");
- final Object innerValue = valueMap.values().iterator().next();
- Util.checkType(innerValue, String.class);
-
- final String className = getOpenType().getTypeName();
- final Object parsedValue = enumResolver.fromYang(className, (String) innerValue);
-
- LOG.debug("Attribute {} : {} parsed to enum type {} with value {}", attrName, innerValue, getOpenType(),
- parsedValue);
- return Optional.of(parsedValue);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
-
-import com.google.common.base.Optional;
-import javax.management.ObjectName;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.ObjectNameAttributeMappingStrategy;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ObjectNameAttributeResolvingStrategy
- extends AbstractAttributeResolvingStrategy<ObjectName, SimpleType<?>> {
-
- private final ServiceRegistryWrapper serviceTracker;
- private static final Logger LOG = LoggerFactory.getLogger(ObjectNameAttributeResolvingStrategy.class);
-
- ObjectNameAttributeResolvingStrategy(final ServiceRegistryWrapper serviceTracker) {
- super(SimpleType.OBJECTNAME);
- this.serviceTracker = serviceTracker;
- }
-
- @Override
- public Optional<ObjectName> parseAttribute(final String attrName, final Object value) {
- if (value == null) {
- return Optional.absent();
- }
-
- Util.checkType(value, ObjectNameAttributeMappingStrategy.MappedDependency.class);
-
- ObjectNameAttributeMappingStrategy.MappedDependency mappedDep =
- (ObjectNameAttributeMappingStrategy.MappedDependency) value;
- String serviceName = mappedDep.getServiceName();
- String refName = mappedDep.getRefName();
- String namespace = mappedDep.getNamespace();
- LOG.trace("Getting service instance by service name {} : {} and ref name {}", namespace, serviceName, refName);
-
- ObjectName on = serviceTracker.getByServiceAndRefName(namespace, serviceName, refName);
-
- LOG.debug("Attribute {} : {} parsed to type {}", attrName, value, getOpenType());
- return Optional.of(on);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-import java.util.Map.Entry;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.AttributeIfcSwitchStatement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-
-public class ObjectResolver extends AttributeIfcSwitchStatement<AttributeResolvingStrategy<?, ? extends OpenType<?>>> {
-
- private final ServiceRegistryWrapper serviceTracker;
- private EnumResolver enumResolver;
-
- public ObjectResolver(final ServiceRegistryWrapper serviceTracker) {
- this.serviceTracker = serviceTracker;
- }
-
- @SuppressWarnings("checkstyle:hiddenField")
- public Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> prepareResolving(
- final Map<String, AttributeIfc> configDefinition, final EnumResolver enumResolver) {
- this.enumResolver = enumResolver;
-
- Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> strategies = Maps.newHashMap();
-
- for (Entry<String, AttributeIfc> attrEntry : configDefinition.entrySet()) {
- strategies.put(attrEntry.getKey(), prepareStrategy(attrEntry.getValue()));
- }
-
- return strategies;
- }
-
- private AttributeResolvingStrategy<?, ? extends OpenType<?>> prepareStrategy(final AttributeIfc attributeIfc) {
- return switchAttribute(attributeIfc);
- }
-
- private Map<String, String> createYangToJmxMapping(final TOAttribute attributeIfc) {
- Map<String, String> retVal = Maps.newHashMap();
- for (Entry<String, AttributeIfc> entry : attributeIfc.getYangPropertiesToTypesMap().entrySet()) {
- retVal.put(entry.getKey(), entry.getValue().getLowerCaseCammelCase());
- }
- return retVal;
- }
-
- @Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaEnumAttribute(final OpenType<?> openType) {
- return new EnumAttributeResolvingStrategy((CompositeType) openType, enumResolver);
- }
-
- @Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaSimpleAttribute(
- final SimpleType<?> openType) {
- return new SimpleAttributeResolvingStrategy(openType);
- }
-
- @Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaArrayAttribute(final ArrayType<?> openType) {
-
- SimpleType<?> innerType = (SimpleType<?>) openType.getElementOpenType();
- AttributeResolvingStrategy<?, ? extends OpenType<?>> strat = new SimpleAttributeResolvingStrategy(innerType);
- return new ArrayAttributeResolvingStrategy(strat, openType);
- }
-
- @Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaCompositeAttribute(
- final CompositeType openType) {
- Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerMap = Maps.newHashMap();
- Map<String, String> yangToJmxMapping = Maps.newHashMap();
-
- fillMappingForComposite(openType, innerMap, yangToJmxMapping);
- return new CompositeAttributeResolvingStrategy(innerMap, openType, yangToJmxMapping);
- }
-
- private void fillMappingForComposite(final CompositeType openType,
- final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerMap,
- final Map<String, String> yangToJmxMapping) {
- for (String innerAttributeKey : openType.keySet()) {
- innerMap.put(innerAttributeKey, caseJavaAttribute(openType.getType(innerAttributeKey)));
- yangToJmxMapping.put(innerAttributeKey, innerAttributeKey);
- }
- }
-
- @Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseJavaUnionAttribute(final OpenType<?> openType) {
-
- Preconditions.checkState(openType instanceof CompositeType, "Unexpected open type, expected %s but was %s");
- CompositeType compositeType = (CompositeType) openType;
-
- Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerMap = Maps.newHashMap();
- Map<String, String> yangToJmxMapping = Maps.newHashMap();
- fillMappingForComposite(compositeType, innerMap, yangToJmxMapping);
-
- return new UnionCompositeAttributeResolvingStrategy(innerMap, compositeType, yangToJmxMapping);
- }
-
- @Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseDependencyAttribute(
- final SimpleType<?> openType) {
- return new ObjectNameAttributeResolvingStrategy(serviceTracker);
- }
-
- @Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseTOAttribute(final CompositeType openType) {
- Preconditions.checkState(getLastAttribute() instanceof TOAttribute);
- TOAttribute toAttribute = (TOAttribute) getLastAttribute();
-
- Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerMap = Maps.newHashMap();
-
- for (String innerName : openType.keySet()) {
-
- AttributeIfc innerAttributeIfc = toAttribute.getJmxPropertiesToTypesMap().get(innerName);
- innerMap.put(innerAttributeIfc.getAttributeYangName(), prepareStrategy(innerAttributeIfc));
- }
- return new CompositeAttributeResolvingStrategy(innerMap, openType, createYangToJmxMapping(toAttribute));
- }
-
- @Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseListAttribute(final ArrayType<?> openType) {
- Preconditions.checkState(getLastAttribute() instanceof ListAttribute);
- AttributeIfc innerAttribute = ((ListAttribute) getLastAttribute()).getInnerAttribute();
- return new ArrayAttributeResolvingStrategy(prepareStrategy(innerAttribute), openType);
- }
-
- @Override
- protected AttributeResolvingStrategy<?, ? extends OpenType<?>> caseListDependeciesAttribute(
- final ArrayType<?> openType) {
- Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute);
- return new ArrayAttributeResolvingStrategy(caseDependencyAttribute(SimpleType.OBJECTNAME), openType);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Maps;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.time.format.DateTimeParseException;
-import java.util.Date;
-import java.util.Map;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-final class SimpleAttributeResolvingStrategy extends AbstractAttributeResolvingStrategy<Object, SimpleType<?>> {
-
- private static final Logger LOG = LoggerFactory.getLogger(SimpleAttributeResolvingStrategy.class);
-
- SimpleAttributeResolvingStrategy(final SimpleType<?> simpleType) {
- super(simpleType);
- }
-
- @Override
- public String toString() {
- return "ResolvedSimpleAttribute [" + getOpenType().getClassName() + "]";
- }
-
- @Override
- public Optional<Object> parseAttribute(final String attrName, final Object value) throws DocumentedException {
- if (value == null) {
- return Optional.absent();
- }
-
- Class<?> cls;
- try {
- cls = Class.forName(getOpenType().getClassName());
- } catch (final ClassNotFoundException e) {
- throw new RuntimeException("Unable to locate class for " + getOpenType().getClassName(), e);
- }
-
- Util.checkType(value, String.class);
-
- Resolver prefferedPlugin = RESOLVER_PLUGINS.get(cls.getCanonicalName());
- prefferedPlugin = prefferedPlugin == null ? RESOLVER_PLUGINS.get(DEFAULT_RESOLVERS) : prefferedPlugin;
-
- Object parsedValue = prefferedPlugin.resolveObject(cls, attrName, (String) value);
- LOG.debug("Attribute {} : {} parsed to type {} with value {}", attrName, value, getOpenType(), parsedValue);
- return Optional.of(parsedValue);
- }
-
- private static final String DEFAULT_RESOLVERS = "default";
- private static final Map<String, Resolver> RESOLVER_PLUGINS = Maps.newHashMap();
-
- static {
- RESOLVER_PLUGINS.put(DEFAULT_RESOLVERS, new DefaultResolver());
- RESOLVER_PLUGINS.put(String.class.getCanonicalName(), new StringResolver());
- RESOLVER_PLUGINS.put(Date.class.getCanonicalName(), new DateResolver());
- RESOLVER_PLUGINS.put(Character.class.getCanonicalName(), new CharResolver());
- RESOLVER_PLUGINS.put(BigInteger.class.getCanonicalName(), new BigIntegerResolver());
- RESOLVER_PLUGINS.put(BigDecimal.class.getCanonicalName(), new BigDecimalResolver());
- }
-
- interface Resolver {
- Object resolveObject(Class<?> type, String attrName, String value) throws DocumentedException;
- }
-
- static class DefaultResolver implements Resolver {
-
- @Override
- public Object resolveObject(final Class<?> type, final String attrName, final String value)
- throws DocumentedException {
- try {
- return parseObject(type, value);
- } catch (final DocumentedException e) {
- throw new DocumentedException("Unable to resolve attribute " + attrName + " from " + value, e,
- DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
-
- protected Object parseObject(final Class<?> type, final String value) throws DocumentedException {
- Method method = null;
- try {
- method = type.getMethod("valueOf", String.class);
- return method.invoke(null, value);
- } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
- LOG.trace("Error parsing object ", e);
- throw new DocumentedException("Error parsing object.", e, DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorSeverity.ERROR);
- }
- }
- }
-
- static class StringResolver extends DefaultResolver {
-
- @Override
- protected Object parseObject(final Class<?> type, final String value) {
- return value;
- }
- }
-
- static class BigIntegerResolver extends DefaultResolver {
-
- @Override
- protected Object parseObject(final Class<?> type, final String value) {
- return new BigInteger(value);
- }
- }
-
- static class BigDecimalResolver extends DefaultResolver {
-
- @Override
- protected Object parseObject(final Class<?> type, final String value) {
- return new BigDecimal(value);
- }
- }
-
- static class CharResolver extends DefaultResolver {
-
- @Override
- protected Object parseObject(final Class<?> type, final String value) {
- return value.charAt(0);
- }
- }
-
- static class DateResolver extends DefaultResolver {
- @Override
- protected Object parseObject(final Class<?> type, final String value) throws DocumentedException {
- try {
- return Revision.ofNullable(value).orElse(null);
- } catch (final DateTimeParseException e) {
- LOG.trace("Unable parse value {} due to ", value, e);
- throw new DocumentedException("Unable to parse value " + value + " as date.", e,
- DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-
-final class UnionCompositeAttributeResolvingStrategy extends CompositeAttributeResolvingStrategy {
-
- UnionCompositeAttributeResolvingStrategy(
- final Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> innerTypes,
- final CompositeType openType, final Map<String, String> yangToJavaAttrMapping) {
- super(innerTypes, openType, yangToJavaAttrMapping);
- }
-
- @Override
- protected Map<String, Object> preprocessValueMap(final Map<?, ?> valueMap) {
- CompositeType openType = getOpenType();
-
- Preconditions.checkArgument(
- valueMap.size() == 1 && valueMap.containsKey(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION),
- "Unexpected structure of incoming map, expecting one element under %s, but was %s",
- JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION, valueMap);
-
- Map<String, Object> newMap = Maps.newHashMap();
-
- for (String key : openType.keySet()) {
- if (openType.getDescription(key).equals(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION)) {
- newMap.put(key, valueMap.get(JavaAttribute.DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION));
- } else {
- newMap.put(key, null);
- }
- }
- return newMap;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import java.util.List;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.w3c.dom.Element;
-
-public class ArrayAttributeWritingStrategy implements AttributeWritingStrategy {
-
- private final AttributeWritingStrategy innnerStrategy;
-
- public ArrayAttributeWritingStrategy(final AttributeWritingStrategy innerStrategy) {
- this.innnerStrategy = innerStrategy;
- }
-
- @Override
- public void writeElement(final Element parentElement, final String namespace, final Object value) {
- Util.checkType(value, List.class);
-
- for (Object innerObject : ((List<?>) value)) {
- innnerStrategy.writeElement(parentElement, namespace, innerObject);
- }
-
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import org.w3c.dom.Element;
-
-public interface AttributeWritingStrategy {
-
- void writeElement(Element parentElement, String namespace, Object value);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import com.google.common.base.Optional;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class CompositeAttributeWritingStrategy implements AttributeWritingStrategy {
-
- private final String key;
- private final Document document;
- private final Map<String, AttributeWritingStrategy> innerStrats;
-
- public CompositeAttributeWritingStrategy(final Document document, final String key,
- final Map<String, AttributeWritingStrategy> innerStrats) {
- this.document = document;
- this.key = key;
- this.innerStrats = innerStrats;
- }
-
- @Override
- public void writeElement(final Element parentElement, final String namespace, final Object value) {
- Util.checkType(value, Map.class);
-
- Element innerNode = XmlUtil.createElement(document, key, Optional.of(namespace));
-
- Map<?, ?> map = (Map<?, ?>) value;
-
- for (Entry<?, ?> innerObjectEntry : map.entrySet()) {
- Util.checkType(innerObjectEntry.getKey(), String.class);
-
- String innerKey = (String) innerObjectEntry.getKey();
- Object innerValue = innerObjectEntry.getValue();
-
- innerStrats.get(innerKey).writeElement(innerNode, namespace, innerValue);
- }
- parentElement.appendChild(innerNode);
- }
-
- public String getKey() {
- return key;
- }
-
- public Document getDocument() {
- return document;
- }
-
- public Map<String, AttributeWritingStrategy> getInnerStrats() {
- return innerStrats;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.ObjectNameAttributeMappingStrategy;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class ObjectNameAttributeWritingStrategy implements AttributeWritingStrategy {
-
- private final Document document;
- private final String key;
-
- public ObjectNameAttributeWritingStrategy(final Document document, final String key) {
- this.document = document;
- this.key = key;
- }
-
- @Override
- public void writeElement(final Element parentElement, final String namespace, final Object value) {
- Util.checkType(value, ObjectNameAttributeMappingStrategy.MappedDependency.class);
- Element innerNode = XmlUtil.createElement(document, key, Optional.of(namespace));
-
- String moduleName = ((ObjectNameAttributeMappingStrategy.MappedDependency) value).getServiceName();
- String refName = ((ObjectNameAttributeMappingStrategy.MappedDependency) value).getRefName();
- String namespaceForType = ((ObjectNameAttributeMappingStrategy.MappedDependency) value).getNamespace();
-
- Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlMappingConstants.TYPE_KEY,
- XmlMappingConstants.PREFIX, namespaceForType, moduleName);
-
- innerNode.appendChild(typeElement);
-
- final Element nameElement = XmlUtil.createTextElement(document, XmlMappingConstants.NAME_KEY, refName,
- Optional.<String>absent());
- innerNode.appendChild(nameElement);
-
- parentElement.appendChild(innerNode);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-import java.util.Map.Entry;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.AttributeIfcSwitchStatement;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.w3c.dom.Document;
-
-public class ObjectXmlWriter extends AttributeIfcSwitchStatement<AttributeWritingStrategy> {
-
- private Document document;
- private String key;
-
- @SuppressWarnings("checkstyle:hiddenField")
- public Map<String, AttributeWritingStrategy> prepareWriting(final Map<String, AttributeIfc> yangToAttrConfig,
- final Document document) {
-
- Map<String, AttributeWritingStrategy> preparedWriting = Maps.newHashMap();
-
- for (Entry<String, AttributeIfc> mappedAttributeEntry : yangToAttrConfig.entrySet()) {
- String key = mappedAttributeEntry.getKey();
- AttributeIfc value = mappedAttributeEntry.getValue();
- AttributeWritingStrategy strat = prepareWritingStrategy(key, value, document);
- preparedWriting.put(key, strat);
- }
-
- return preparedWriting;
- }
-
- @SuppressWarnings("checkstyle:hiddenField")
- public AttributeWritingStrategy prepareWritingStrategy(final String key, final AttributeIfc expectedAttr,
- final Document document) {
- Preconditions.checkNotNull(expectedAttr, "Mbean attributes mismatch, unable to find expected attribute for %s",
- key);
- this.document = document;
- this.key = key;
- return switchAttribute(expectedAttr);
- }
-
- @Override
- protected AttributeWritingStrategy caseJavaBinaryAttribute(final OpenType<?> openType) {
- return new SimpleBinaryAttributeWritingStrategy(document, key);
- }
-
- @Override
- protected AttributeWritingStrategy caseJavaEnumAttribute(final OpenType<?> openType) {
- return new SimpleAttributeWritingStrategy(document, key);
- }
-
- @Override
- protected AttributeWritingStrategy caseJavaSimpleAttribute(final SimpleType<?> openType) {
- return new SimpleAttributeWritingStrategy(document, key);
- }
-
- @Override
- protected AttributeWritingStrategy caseJavaArrayAttribute(final ArrayType<?> openType) {
- AttributeWritingStrategy innerStrategy = new SimpleAttributeWritingStrategy(document, key);
- return new ArrayAttributeWritingStrategy(innerStrategy);
- }
-
- @Override
- protected AttributeWritingStrategy caseJavaIdentityRefAttribute(final OpenType<?> openType) {
- return new SimpleIdentityRefAttributeWritingStrategy(document, key);
- }
-
- @Override
- protected AttributeWritingStrategy caseJavaCompositeAttribute(final CompositeType openType) {
- return new SimpleCompositeAttributeWritingStrategy(document, key);
- }
-
- @Override
- protected AttributeWritingStrategy caseJavaUnionAttribute(final OpenType<?> openType) {
- return new SimpleUnionAttributeWritingStrategy(document, key);
- }
-
- @Override
- protected AttributeWritingStrategy caseDependencyAttribute(final SimpleType<?> openType) {
- return new ObjectNameAttributeWritingStrategy(document, key);
- }
-
- @Override
- protected AttributeWritingStrategy caseTOAttribute(final CompositeType openType) {
- Preconditions.checkState(getLastAttribute() instanceof TOAttribute);
-
- Map<String, AttributeWritingStrategy> innerStrats = Maps.newHashMap();
- String currentKey = key;
- for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute) getLastAttribute())
- .getYangPropertiesToTypesMap().entrySet()) {
-
- AttributeWritingStrategy innerStrategy = prepareWritingStrategy(innerAttrEntry.getKey(),
- innerAttrEntry.getValue(), document);
- innerStrats.put(innerAttrEntry.getKey(), innerStrategy);
- }
-
- return new CompositeAttributeWritingStrategy(document, currentKey, innerStrats);
- }
-
- @Override
- protected AttributeWritingStrategy caseListAttribute(final ArrayType<?> openType) {
- Preconditions.checkState(getLastAttribute() instanceof ListAttribute);
- AttributeIfc innerAttribute = ((ListAttribute) getLastAttribute()).getInnerAttribute();
-
- AttributeWritingStrategy innerStrategy = prepareWritingStrategy(key, innerAttribute, document);
- return new ArrayAttributeWritingStrategy(innerStrategy);
- }
-
- @Override
- protected AttributeWritingStrategy caseListDependeciesAttribute(final ArrayType<?> openType) {
- Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute);
- AttributeWritingStrategy innerStrategy = caseDependencyAttribute(SimpleType.OBJECTNAME);
- return new ArrayAttributeWritingStrategy(innerStrategy);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import com.google.common.base.Optional;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class RuntimeBeanEntryWritingStrategy extends CompositeAttributeWritingStrategy {
-
- public RuntimeBeanEntryWritingStrategy(final Document document, final String key,
- final Map<String, AttributeWritingStrategy> innerStrats) {
- super(document, key, innerStrats);
- }
-
- @Override
- public void writeElement(final Element parentElement, final String namespace, final Object value) {
- Util.checkType(value, Map.class);
-
- Element innerNode = XmlUtil.createElement(getDocument(), getKey(), Optional.<String>absent());
-
- Map<?, ?> map = (Map<?, ?>) value;
-
- for (Entry<?, ?> runtimeBeanInstanceMappingEntry : map.entrySet()) {
-
- // wrap runtime attributes with number assigned to current runtime
- // bean
- Util.checkType(runtimeBeanInstanceMappingEntry.getValue(), Map.class);
- Map<?, ?> innerMap = (Map<?, ?>) runtimeBeanInstanceMappingEntry.getValue();
- Element runtimeInstanceNode = XmlUtil.createElement(getDocument(), "_"
- + runtimeBeanInstanceMappingEntry.getKey(), Optional.<String>absent());
- innerNode.appendChild(runtimeInstanceNode);
-
- for (Entry<?, ?> innerObjectEntry : innerMap.entrySet()) {
-
- Util.checkType(innerObjectEntry.getKey(), String.class);
-
- String innerKey = (String) innerObjectEntry.getKey();
- Object innerValue = innerObjectEntry.getValue();
-
- getInnerStrats().get(innerKey).writeElement(runtimeInstanceNode, namespace, innerValue);
- }
- }
- parentElement.appendChild(innerNode);
-
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class SimpleAttributeWritingStrategy implements AttributeWritingStrategy {
-
- private final Document document;
- private final String key;
-
- public SimpleAttributeWritingStrategy(final Document document, final String key) {
- this.document = document;
- this.key = key;
- }
-
- @Override
- public void writeElement(final Element parentElement, final String namespace, Object value) {
- value = preprocess(value);
- Util.checkType(value, String.class);
- Element innerNode = createElement(document, key, (String) value, Optional.of(namespace));
- parentElement.appendChild(innerNode);
- }
-
- @SuppressWarnings("checkstyle:hiddenField")
- protected Element createElement(final Document document, final String key, final String value,
- final Optional<String> namespace) {
- Element typeElement = XmlUtil.createElement(document, key, namespace);
-
- typeElement.appendChild(document.createTextNode(value));
- return typeElement;
- }
-
- protected Object preprocess(final Object value) {
- return value;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import com.google.common.base.Preconditions;
-import com.google.common.io.BaseEncoding;
-import java.util.List;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.w3c.dom.Document;
-
-public class SimpleBinaryAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
-
- public SimpleBinaryAttributeWritingStrategy(final Document document, final String key) {
- super(document, key);
- }
-
- @Override
- protected Object preprocess(final Object value) {
- Util.checkType(value, List.class);
- BaseEncoding en = BaseEncoding.base64();
-
- List<?> list = (List<?>) value;
- byte[] decoded = new byte[list.size()];
- int index = 0;
- for (Object basStr : list) {
- Preconditions.checkArgument(basStr instanceof String, "Unexpected inner value for %s, expected string",
- value);
- decoded[index++] = Byte.parseByte((String) basStr);
- }
- return en.encode(decoded);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import com.google.common.base.Preconditions;
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.w3c.dom.Document;
-
-public class SimpleCompositeAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
-
- public SimpleCompositeAttributeWritingStrategy(final Document document, final String key) {
- super(document, key);
- }
-
- @Override
- protected Object preprocess(final Object value) {
- Util.checkType(value, Map.class);
- Preconditions.checkArgument(((Map<?, ?>) value).size() == 1, "Unexpected number of values in %s, expected 1",
- value);
- return ((Map<?, ?>) value).values().iterator().next();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class SimpleIdentityRefAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
-
- private static final String PREFIX = "prefix";
-
- public SimpleIdentityRefAttributeWritingStrategy(final Document document, final String key) {
- super(document, key);
- }
-
- @Override
- protected Object preprocess(final Object value) {
- Util.checkType(value, Map.class);
- Preconditions.checkArgument(((Map<?, ?>) value).size() == 1, "Unexpected number of values in %s, expected 1",
- value);
- Object stringValue = ((Map<?, ?>) value).values().iterator().next();
- Util.checkType(stringValue, String.class);
-
- return stringValue;
- }
-
- @Override
- protected Element createElement(final Document doc, final String key, final String value,
- final Optional<String> namespace) {
- QName qualifiedName = QName.create(value);
- String identityValue = qualifiedName.getLocalName();
- String identityNamespace = qualifiedName.getNamespace().toString();
- return XmlUtil.createTextElementWithNamespacedContent(doc, key, PREFIX, identityNamespace, identityValue,
- namespace);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
-
-import com.google.common.base.Preconditions;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.util.Util;
-import org.w3c.dom.Document;
-
-public class SimpleUnionAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
-
- public SimpleUnionAttributeWritingStrategy(final Document document, final String key) {
- super(document, key);
- }
-
- @Override
- protected Object preprocess(final Object value) {
- Util.checkType(value, Map.class);
- Preconditions.checkArgument(((Map<?, ?>) value).size() == 1, "Unexpected number of values in %s, expected 1",
- value);
- Object listOfStrings = ((Map<?, ?>) value).values().iterator().next();
- Util.checkType(listOfStrings, List.class);
-
- StringBuilder builder = new StringBuilder();
- for (Object character : (List<?>) listOfStrings) {
- Util.checkType(character, String.class);
- builder.append(character);
- }
- return builder.toString();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.config;
-
-import static com.google.common.base.Preconditions.checkState;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Multimap;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class Config {
-
- private final Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */,
- ModuleConfig>> moduleConfigs;
-
- private final Map<String, Map<Optional<Revision>, IdentityMapping>> identityMap;
-
- private final EnumResolver enumResolver;
-
- public Config(final Map<String, Map<String, ModuleConfig>> moduleConfigs, final EnumResolver enumResolver) {
- this(moduleConfigs, Collections.<String, Map<Optional<Revision>, IdentityMapping>>emptyMap(), enumResolver);
- }
-
- public Config(final Map<String, Map<String, ModuleConfig>> moduleConfigs,
- final Map<String, Map<Optional<Revision>, IdentityMapping>> identityMap, final EnumResolver enumResolver) {
- this.moduleConfigs = moduleConfigs;
- this.identityMap = identityMap;
- this.enumResolver = enumResolver;
- }
-
- public static Map<String, Map<String, Collection<ObjectName>>> getMappedInstances(
- final Set<ObjectName> instancesToMap, final Map<String, Map<String, ModuleConfig>> configs) {
- Multimap<String, ObjectName> moduleToInstances = mapInstancesToModules(instancesToMap);
-
- Map<String, Map<String, Collection<ObjectName>>> retVal = Maps.newLinkedHashMap();
-
- for (Entry<String, Map<String, ModuleConfig>> namespaceToModuleToConfigEntry : configs.entrySet()) {
-
- Map<String, Collection<ObjectName>> innerRetVal = Maps.newHashMap();
-
- for (Entry<String, ModuleConfig> mbeEntry : namespaceToModuleToConfigEntry.getValue().entrySet()) {
-
- String moduleName = mbeEntry.getKey();
- Collection<ObjectName> instances = moduleToInstances.get(moduleName);
-
- // TODO, this code does not support same module names from different namespaces
- // Namespace should be present in ObjectName
-
- if (instances == null) {
- continue;
- }
-
- innerRetVal.put(moduleName, instances);
-
- }
- retVal.put(namespaceToModuleToConfigEntry.getKey(), innerRetVal);
- }
- return retVal;
- }
-
- private static Multimap<String, ObjectName> mapInstancesToModules(final Set<ObjectName> instancesToMap) {
- Multimap<String, ObjectName> retVal = HashMultimap.create();
-
- for (ObjectName objectName : instancesToMap) {
- String factoryName = ObjectNameUtil.getFactoryName(objectName);
- retVal.put(factoryName, objectName);
- }
- return retVal;
- }
-
- public Element toXml(final Set<ObjectName> instancesToMap, final Optional<String> maybeNamespace,
- final Document document, final Element dataElement, final ServiceRegistryWrapper serviceTracker) {
-
- Map<String, Map<String, Collection<ObjectName>>> moduleToInstances = getMappedInstances(instancesToMap,
- moduleConfigs);
-
- if (maybeNamespace.isPresent()) {
- dataElement.setAttributeNS(maybeNamespace.get(), dataElement.getNodeName(), "xmlns");
- }
-
- Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY,
- Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
- dataElement.appendChild(modulesElement);
- for (Entry<String, Map<String, Collection<ObjectName>>> moduleToInstanceEntry : moduleToInstances.entrySet()) {
- for (Entry<String, Collection<ObjectName>> moduleMappingEntry : moduleToInstanceEntry.getValue()
- .entrySet()) {
-
- ModuleConfig mapping = moduleConfigs.get(moduleToInstanceEntry.getKey())
- .get(moduleMappingEntry.getKey());
-
- if (moduleMappingEntry.getValue().isEmpty()) {
- continue;
- }
-
- for (ObjectName objectName : moduleMappingEntry.getValue()) {
- modulesElement.appendChild(
- mapping.toXml(objectName, document, moduleToInstanceEntry.getKey(), enumResolver));
- }
-
- }
- }
-
- dataElement.appendChild(Services.toXml(serviceTracker, document));
-
- return dataElement;
- }
-
- public Element moduleToXml(final String moduleNamespace, final String factoryName, final String instanceName,
- final ObjectName instanceON, final Document document) {
- ModuleConfig moduleConfig = getModuleMapping(moduleNamespace, instanceName, factoryName);
- return moduleConfig.toXml(instanceON, document, moduleNamespace, enumResolver);
- }
-
- // TODO refactor, replace string representing namespace with namespace class
- // TODO refactor, replace Map->Multimap with e.g. ConfigElementResolved
- // class
-
- public Map<String, Multimap<String, ModuleElementResolved>> fromXmlModulesResolved(final XmlElement xml,
- final EditStrategyType defaultEditStrategyType, final ServiceRegistryWrapper serviceTracker)
- throws DocumentedException {
- Optional<XmlElement> modulesElement = getModulesElement(xml);
- List<XmlElement> moduleElements = getModulesElementList(modulesElement);
-
- Map<String, Multimap<String, ModuleElementResolved>> retVal = Maps.newHashMap();
-
- ResolvingStrategy<ModuleElementResolved> resolvingStrategy = (moduleMapping, moduleElement, serviceTracker1,
- instanceName, moduleNamespace, defaultStrategy) -> moduleMapping.fromXml(moduleElement, serviceTracker1,
- instanceName, moduleNamespace, defaultStrategy, identityMap, enumResolver);
-
- for (XmlElement moduleElement : moduleElements) {
- resolveModule(retVal, serviceTracker, moduleElement, defaultEditStrategyType, resolvingStrategy);
- }
-
- return retVal;
- }
-
- /**
- * return a map containing namespace -> moduleName -> instanceName map.
- * Attribute parsing is omitted.
- */
- public Map<String, Multimap<String, ModuleElementDefinition>> fromXmlModulesMap(final XmlElement xml,
- final EditStrategyType defaultEditStrategyType, final ServiceRegistryWrapper serviceTracker)
- throws DocumentedException {
- Optional<XmlElement> modulesElement = getModulesElement(xml);
- List<XmlElement> moduleElements = getModulesElementList(modulesElement);
-
- Map<String, Multimap<String, ModuleElementDefinition>> retVal = Maps.newHashMap();
-
- ResolvingStrategy<ModuleElementDefinition> resolvingStrategy = (moduleMapping, moduleElement, serviceTracker1,
- instanceName, moduleNamespace, defaultStrategy) -> {
- // TODO: add check for conflicts between global and local edit
- // strategy
- String perInstanceEditStrategy = moduleElement.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
- XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- return new ModuleElementDefinition(instanceName, perInstanceEditStrategy, defaultStrategy);
- };
-
- for (XmlElement moduleElement : moduleElements) {
- resolveModule(retVal, serviceTracker, moduleElement, defaultEditStrategyType, resolvingStrategy);
- }
-
- return retVal;
- }
-
- private static Optional<XmlElement> getModulesElement(final XmlElement xml) {
- return xml.getOnlyChildElementOptionally(XmlMappingConstants.MODULES_KEY,
- XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
- }
-
- private List<XmlElement> getModulesElementList(final Optional<XmlElement> modulesElement)
- throws DocumentedException {
- List<XmlElement> moduleElements;
-
- if (modulesElement.isPresent()) {
- moduleElements = modulesElement.get().getChildElementsWithSameNamespace(XmlMappingConstants.MODULE_KEY);
- modulesElement.get().checkUnrecognisedElements(moduleElements);
- } else {
- moduleElements = Lists.newArrayList();
- }
- return moduleElements;
- }
-
- private <T> void resolveModule(final Map<String, Multimap<String, T>> retVal,
- final ServiceRegistryWrapper serviceTracker, final XmlElement moduleElement,
- final EditStrategyType defaultStrategy, final ResolvingStrategy<T> resolvingStrategy)
- throws DocumentedException {
- XmlElement typeElement = null;
- typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY);
- Entry<String, String> prefixToNamespace = typeElement.findNamespaceOfTextContent();
- String moduleNamespace = prefixToNamespace.getValue();
- XmlElement nameElement = null;
- nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.NAME_KEY);
- String instanceName = nameElement.getTextContent();
- String factoryNameWithPrefix = typeElement.getTextContent();
- String prefixOrEmptyString = prefixToNamespace.getKey();
- String factoryName = getFactoryName(factoryNameWithPrefix, prefixOrEmptyString);
-
- ModuleConfig moduleMapping = getModuleMapping(moduleNamespace, instanceName, factoryName);
-
- Multimap<String, T> innerMap = retVal.computeIfAbsent(moduleNamespace, k -> HashMultimap.create());
-
- T resolvedElement = resolvingStrategy.resolveElement(moduleMapping, moduleElement, serviceTracker, instanceName,
- moduleNamespace, defaultStrategy);
-
- innerMap.put(factoryName, resolvedElement);
- }
-
- public Services fromXmlServices(final XmlElement xml) throws DocumentedException {
- Optional<XmlElement> servicesElement = getServicesElement(xml);
-
- Services services;
- if (servicesElement.isPresent()) {
- services = Services.fromXml(servicesElement.get());
- } else {
- services = new Services();
- }
-
- return services;
- }
-
- private static Optional<XmlElement> getServicesElement(final XmlElement xml) {
- return xml.getOnlyChildElementOptionally(XmlMappingConstants.SERVICES_KEY,
- XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
- }
-
- public static void checkUnrecognisedChildren(final XmlElement parent) throws DocumentedException {
- Optional<XmlElement> servicesOpt = getServicesElement(parent);
- Optional<XmlElement> modulesOpt = getModulesElement(parent);
-
- List<XmlElement> recognised = Lists.newArrayList();
- if (servicesOpt.isPresent()) {
- recognised.add(servicesOpt.get());
- }
- if (modulesOpt.isPresent()) {
- recognised.add(modulesOpt.get());
- }
-
- parent.checkUnrecognisedElements(recognised);
- }
-
- private String getFactoryName(final String factoryNameWithPrefix, final String prefixOrEmptyString) {
- checkState(factoryNameWithPrefix.startsWith(prefixOrEmptyString),
- String.format("Internal error: text " + "content '%s' of type node does not start with prefix '%s'",
- factoryNameWithPrefix, prefixOrEmptyString));
-
- int factoryNameAfterPrefixIndex;
- if (prefixOrEmptyString.isEmpty()) {
- factoryNameAfterPrefixIndex = 0;
- } else {
- factoryNameAfterPrefixIndex = prefixOrEmptyString.length() + 1;
- }
- return factoryNameWithPrefix.substring(factoryNameAfterPrefixIndex);
- }
-
- private ModuleConfig getModuleMapping(final String moduleNamespace, final String instanceName,
- final String factoryName) {
- Map<String, ModuleConfig> mappingsFromNamespace = moduleConfigs.get(moduleNamespace);
-
- Preconditions.checkNotNull(mappingsFromNamespace,
- "Namespace %s, defined in: module %s of type %s not found, available namespaces: %s", moduleNamespace,
- instanceName, factoryName, moduleConfigs.keySet());
-
- ModuleConfig moduleMapping = mappingsFromNamespace.get(factoryName);
- checkState(moduleMapping != null, "Cannot find mapping for module type " + factoryName);
- return moduleMapping;
- }
-
- private interface ResolvingStrategy<T> {
- T resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker,
- String instanceName, String moduleNamespace, EditStrategyType defaultStrategy)
- throws DocumentedException;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.config;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import javax.management.ObjectName;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeReadingStrategy;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.ObjectXmlReader;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.AttributeMappingStrategy;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.ObjectMapper;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving.AttributeResolvingStrategy;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving.ObjectResolver;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml.AttributeWritingStrategy;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml.ObjectXmlWriter;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.util.BeanReader;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public final class InstanceConfig {
- private static final Logger LOG = LoggerFactory.getLogger(InstanceConfig.class);
-
- private final Map<String, AttributeIfc> yangToAttrConfig;
- private final String nullableDummyContainerName;
- private final Map<String, AttributeIfc> jmxToAttrConfig;
- private final BeanReader configRegistryClient;
-
- public InstanceConfig(final BeanReader configRegistryClient, final Map<String, AttributeIfc> yangNamesToAttributes,
- final String nullableDummyContainerName) {
-
- this.yangToAttrConfig = yangNamesToAttributes;
- this.nullableDummyContainerName = nullableDummyContainerName;
- this.jmxToAttrConfig = reverseMap(yangNamesToAttributes);
- this.configRegistryClient = configRegistryClient;
- }
-
- @SuppressWarnings("IllegalCatch")
- private Map<String, Object> getMappedConfiguration(final ObjectName on, final EnumResolver enumResolver) {
-
- // TODO make field, mappingStrategies can be instantiated only once
- Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> mappingStrategies = new ObjectMapper()
- .prepareMapping(jmxToAttrConfig, enumResolver);
-
- Map<String, Object> toXml = Maps.newHashMap();
-
- for (Entry<String, AttributeIfc> configDefEntry : jmxToAttrConfig.entrySet()) {
- // Skip children runtime beans as they are mapped by InstanceRuntime
- if (configDefEntry.getValue() instanceof RuntimeBeanEntry) {
- continue;
- }
- Object value = configRegistryClient.getAttributeCurrentValue(on, configDefEntry.getKey());
- try {
- AttributeMappingStrategy<?, ? extends OpenType<?>> attributeMappingStrategy = mappingStrategies
- .get(configDefEntry.getKey());
- Optional<?> attribute = attributeMappingStrategy.mapAttribute(value);
- if (!attribute.isPresent()) {
- continue;
- }
- toXml.put(configDefEntry.getValue().getAttributeYangName(), attribute.get());
- } catch (final RuntimeException e) {
- throw new IllegalStateException("Unable to map value " + value + " to attribute "
- + configDefEntry.getKey(), e);
- }
- }
- return toXml;
- }
-
- @SuppressWarnings("IllegalCatch")
- public Element toXml(final ObjectName on, final String namespace, final Document document,
- final Element rootElement, final EnumResolver enumResolver) {
- Map<String, AttributeWritingStrategy> strats = new ObjectXmlWriter().prepareWriting(yangToAttrConfig, document);
- Map<String, Object> mappedConfig = getMappedConfiguration(on, enumResolver);
- Element parentElement;
- if (nullableDummyContainerName != null) {
- Element dummyElement = XmlUtil.createElement(document, nullableDummyContainerName, Optional.of(namespace));
- rootElement.appendChild(dummyElement);
- parentElement = dummyElement;
- } else {
- parentElement = rootElement;
- }
- for (Entry<String, ?> mappingEntry : mappedConfig.entrySet()) {
- try {
- strats.get(mappingEntry.getKey()).writeElement(parentElement, namespace, mappingEntry.getValue());
- } catch (final RuntimeException e) {
- throw new IllegalStateException("Unable to write value " + mappingEntry.getValue() + " for attribute "
- + mappingEntry.getValue(), e);
- }
- }
- return rootElement;
- }
-
- private void resolveConfiguration(final InstanceConfigElementResolved mappedConfig,
- final ServiceRegistryWrapper depTracker, final EnumResolver enumResolver) {
-
- // TODO make field, resolvingStrategies can be instantiated only once
- Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> resolvingStrategies = new ObjectResolver(
- depTracker).prepareResolving(yangToAttrConfig, enumResolver);
-
- for (Entry<String, AttributeConfigElement> configDefEntry : mappedConfig.getConfiguration().entrySet()) {
- AttributeConfigElement value = configDefEntry.getValue();
- String attributeName = configDefEntry.getKey();
- try {
- AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy = resolvingStrategies
- .get(attributeName);
- LOG.trace("Trying to set value {} of attribute {} with {}", value, attributeName,
- attributeResolvingStrategy);
-
- value.resolveValue(attributeResolvingStrategy, attributeName);
- value.setJmxName(yangToAttrConfig.get(attributeName).getUpperCaseCammelCase());
- } catch (final DocumentedException e) {
- throw new IllegalStateException("Unable to resolve value " + value + " to attribute " + attributeName,
- e);
- }
- }
- }
-
- public InstanceConfigElementResolved fromXml(XmlElement moduleElement, final ServiceRegistryWrapper services,
- final String moduleNamespace, final EditStrategyType defaultStrategy,
- final Map<String, Map<Optional<Revision>, IdentityMapping>> identityMap,
- final EnumResolver enumResolver)
- throws DocumentedException {
- Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
-
- Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig,
- identityMap);
- List<XmlElement> recognisedChildren = Lists.newArrayList();
-
- XmlElement typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY);
- XmlElement nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.NAME_KEY);
- List<XmlElement> typeAndNameElements = Lists.newArrayList(typeElement, nameElement);
-
- // if dummy container was defined in yang, set moduleElement to its content
- if (nullableDummyContainerName != null) {
- int size = moduleElement.getChildElements().size();
- int expectedChildNodes = 1 + typeAndNameElements.size();
- if (size > expectedChildNodes) {
- throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : "
- + nameElement.getTextContent() + " - Expected " + expectedChildNodes + " child nodes, "
- + "one of them with name " + nullableDummyContainerName + ", got " + size + " elements.");
- }
- if (size == expectedChildNodes) {
- try {
- moduleElement = moduleElement.getOnlyChildElement(nullableDummyContainerName, moduleNamespace);
- } catch (final DocumentedException e) {
- throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : "
- + nameElement.getTextContent() + " - Expected child node with name "
- + nullableDummyContainerName + "." + e.getMessage(), e);
- }
- } // else 2 elements, no need to descend
- }
-
- for (Entry<String, AttributeReadingStrategy> readStratEntry : strats.entrySet()) {
- List<XmlElement> configNodes = getConfigNodes(moduleElement, moduleNamespace, readStratEntry.getKey(),
- recognisedChildren, typeAndNameElements);
- AttributeConfigElement readElement = readStratEntry.getValue().readElement(configNodes);
- retVal.put(readStratEntry.getKey(), readElement);
- }
-
- recognisedChildren.addAll(typeAndNameElements);
- try {
- moduleElement.checkUnrecognisedElements(recognisedChildren);
- } catch (final DocumentedException e) {
- throw new DocumentedException(
- "Error reading module " + typeElement.getTextContent() + " : " + nameElement.getTextContent()
- + " - " + e.getMessage(), e,
- e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
- }
- // TODO: add check for conflicts between global and local edit strategy
- String perInstanceEditStrategy = moduleElement.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
- XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
-
- InstanceConfigElementResolved instanceConfigElementResolved = perInstanceEditStrategy.equals("")
- ? new InstanceConfigElementResolved(retVal, defaultStrategy)
- : new InstanceConfigElementResolved(perInstanceEditStrategy, retVal, defaultStrategy);
-
- resolveConfiguration(instanceConfigElementResolved, services, enumResolver);
- return instanceConfigElementResolved;
- }
-
- private List<XmlElement> getConfigNodes(final XmlElement moduleElement, final String moduleNamespace,
- final String name, final List<XmlElement> recognisedChildren,
- final List<XmlElement> typeAndName)
- throws DocumentedException {
- List<XmlElement> foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name, moduleNamespace);
- if (foundConfigNodes.isEmpty()) {
- LOG.debug("No config nodes {}:{} found in {}", moduleNamespace, name, moduleElement);
- LOG.debug("Trying lookup of config nodes without specified namespace");
- foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name,
- XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
- // In case module type or name element is not present in config it
- // would be matched with config type or name
- // We need to remove config type and name from available module
- // config elements
- foundConfigNodes.removeAll(typeAndName);
- LOG.debug("Found {} config nodes {} without specified namespace in {}", foundConfigNodes.size(), name,
- moduleElement);
- } else {
- List<XmlElement> foundWithoutNamespaceNodes = moduleElement.getChildElementsWithinNamespace(name,
- XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
- foundWithoutNamespaceNodes.removeAll(typeAndName);
- if (!foundWithoutNamespaceNodes.isEmpty()) {
- throw new DocumentedException(
- String.format("Element %s present multiple times with different namespaces: %s, %s", name,
- foundConfigNodes, foundWithoutNamespaceNodes),
- DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.INVALID_VALUE,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
- recognisedChildren.addAll(foundConfigNodes);
- return foundConfigNodes;
- }
-
- private static Map<String, AttributeIfc> reverseMap(final Map<String, AttributeIfc> yangNameToAttr) {
- Map<String, AttributeIfc> reversednameToAtr = Maps.newHashMap();
-
- for (Entry<String, AttributeIfc> entry : yangNameToAttr.entrySet()) {
- reversednameToAtr.put(entry.getValue().getUpperCaseCammelCase(), entry.getValue());
- }
- return reversednameToAtr;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.config;
-
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.exception.OperationNotPermittedException;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.strategy.EditConfigStrategy;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-
-/**
- * Parsed xml element containing whole configuration for an instance of some
- * module. Contains preferred edit strategy type.
- */
-public class InstanceConfigElementResolved {
-
- private final EditStrategyType editStrategy;
- private final Map<String, AttributeConfigElement> configuration;
-
- public InstanceConfigElementResolved(final String currentStrategy,
- final Map<String, AttributeConfigElement> configuration, final EditStrategyType defaultStrategy)
- throws DocumentedException {
- this.editStrategy = parseStrategy(currentStrategy, defaultStrategy);
- this.configuration = configuration;
- }
-
- public InstanceConfigElementResolved(final Map<String, AttributeConfigElement> configuration,
- final EditStrategyType defaultStrategy) {
- editStrategy = defaultStrategy;
- this.configuration = configuration;
- }
-
- static EditStrategyType parseStrategy(final String currentStrategy, final EditStrategyType defaultStrategy)
- throws OperationNotPermittedException {
- EditStrategyType parsedStrategy = EditStrategyType.valueOf(currentStrategy);
- EditStrategyType.compareParsedStrategyToDefaultEnforcing(parsedStrategy, defaultStrategy);
- return parsedStrategy;
- }
-
- public EditConfigStrategy getEditStrategy() {
- return editStrategy.getFittingStrategy();
- }
-
- public Map<String, AttributeConfigElement> getConfiguration() {
- return configuration;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.config;
-
-import com.google.common.base.Optional;
-import java.util.Map;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class ModuleConfig {
-
- private final String moduleName;
- private final InstanceConfig instanceConfig;
-
- public ModuleConfig(final String moduleName, final InstanceConfig mbeanMapping) {
- this.moduleName = moduleName;
- this.instanceConfig = mbeanMapping;
- }
-
- public Element toXml(final ObjectName instanceON, final Document document, final String namespace,
- final EnumResolver enumResolver) {
- final Optional<String> configNs = Optional
- .of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
- Element root = XmlUtil.createElement(document, XmlMappingConstants.MODULE_KEY, configNs);
-
- // type belongs to config.yang namespace, but needs to be <type
- // prefix:moduleNS>prefix:moduleName</type>
-
- Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlMappingConstants.TYPE_KEY,
- XmlMappingConstants.PREFIX, namespace, moduleName, configNs);
-
- root.appendChild(typeElement);
- // name belongs to config.yang namespace
- String instanceName = ObjectNameUtil.getInstanceName(instanceON);
- Element nameElement = XmlUtil.createTextElement(document, XmlMappingConstants.NAME_KEY, instanceName, configNs);
-
- root.appendChild(nameElement);
-
- root = instanceConfig.toXml(instanceON, namespace, document, root, enumResolver);
-
- return root;
- }
-
- public ModuleElementResolved fromXml(final XmlElement moduleElement, final ServiceRegistryWrapper depTracker,
- final String instanceName, final String moduleNamespace, final EditStrategyType defaultStrategy,
- final Map<String, Map<Optional<Revision>, IdentityMapping>> identityMap, final EnumResolver enumResolver)
- throws DocumentedException {
-
- InstanceConfigElementResolved ice = instanceConfig.fromXml(moduleElement, depTracker, moduleNamespace,
- defaultStrategy, identityMap, enumResolver);
- return new ModuleElementResolved(instanceName, ice);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.config;
-
-import org.opendaylight.controller.config.facade.xml.exception.OperationNotPermittedException;
-import org.opendaylight.controller.config.facade.xml.strategy.EditConfigStrategy;
-import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
-import org.opendaylight.controller.config.facade.xml.strategy.MissingInstanceHandlingStrategy;
-import org.opendaylight.controller.config.facade.xml.strategy.NoneEditConfigStrategy;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ModuleElementDefinition {
-
- public static final NoneEditConfigStrategy NONE_EDIT_CONFIG_STRATEGY = new NoneEditConfigStrategy();
- public static final MissingInstanceHandlingStrategy MISSING_INSTANCE_HANDLING_STRATEGY =
- new MissingInstanceHandlingStrategy();
-
- private final String instanceName;
- private final EditStrategyType editStrategy;
- private static final Logger LOG = LoggerFactory.getLogger(ModuleElementDefinition.class);
-
- public ModuleElementDefinition(final String instanceName, final String currentStrategy,
- final EditStrategyType defaultStrategy) {
- this.instanceName = instanceName;
- if (currentStrategy == null || currentStrategy.isEmpty()) {
- this.editStrategy = defaultStrategy;
- } else {
- EditStrategyType edStrategy = null;
- try {
- edStrategy = InstanceConfigElementResolved.parseStrategy(currentStrategy, defaultStrategy);
- } catch (final OperationNotPermittedException e) {
- edStrategy = defaultStrategy;
- LOG.warn(
- "Operation not permitted on current strategy {} while default strategy "
- + "is {}. Element definition strategy set to default.",
- currentStrategy, defaultStrategy, e);
- }
- this.editStrategy = edStrategy;
- }
-
- }
-
- public String getInstanceName() {
- return instanceName;
- }
-
- public EditConfigStrategy getEditStrategy() {
- switch (editStrategy) {
- case delete:
- case remove:
- case none:
- return NONE_EDIT_CONFIG_STRATEGY;
- default:
- return MISSING_INSTANCE_HANDLING_STRATEGY;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.config;
-
-public class ModuleElementResolved {
-
- private final String instanceName;
- private final InstanceConfigElementResolved instanceConfigElementResolved;
-
- public ModuleElementResolved(final String instanceName,
- final InstanceConfigElementResolved instanceConfigElementResolved) {
- this.instanceName = instanceName;
- this.instanceConfigElementResolved = instanceConfigElementResolved;
- }
-
- public String getInstanceName() {
- return instanceName;
- }
-
- public InstanceConfigElementResolved getInstanceConfigElementResolved() {
- return instanceConfigElementResolved;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.config;
-
-import com.google.common.base.Preconditions;
-import java.util.HashMap;
-import java.util.Map;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.yangtools.yang.common.QName;
-
-public class ServiceRegistryWrapper {
-
- private final ServiceReferenceReadableRegistry configServiceRefRegistry;
-
- public ServiceRegistryWrapper(final ServiceReferenceReadableRegistry configServiceRefRegistry) {
- this.configServiceRefRegistry = configServiceRefRegistry;
- }
-
- public ObjectName getByServiceAndRefName(final String namespace, final String serviceType, final String refName) {
- Map<String, Map<String, Map<String, String>>> mappedServices = getMappedServices();
- Map<String, Map<String, String>> serviceNameToRefNameToInstance = mappedServices.get(namespace);
-
- Preconditions.checkArgument(serviceNameToRefNameToInstance != null,
- "No service mapped to %s:%s:%s. Wrong namespace, available namespaces: %s", namespace, serviceType,
- refName, mappedServices.keySet());
-
- Map<String, String> refNameToInstance = serviceNameToRefNameToInstance.get(serviceType);
- Preconditions.checkArgument(refNameToInstance != null,
- "No service mapped to %s:%s:%s. Wrong service type, available service types: %s", namespace,
- serviceType, refName, serviceNameToRefNameToInstance.keySet());
-
- String instanceId = refNameToInstance.get(refName);
- Preconditions.checkArgument(instanceId != null,
- "No service mapped to %s:%s:%s. Wrong ref name, available ref names: %s", namespace, serviceType,
- refName, refNameToInstance.keySet());
-
- Services.ServiceInstance serviceInstance = Services.ServiceInstance.fromString(instanceId);
- Preconditions.checkArgument(serviceInstance != null,
- "No service mapped to %s:%s:%s. Wrong ref name, available ref names: %s", namespace, serviceType,
- refName, refNameToInstance.keySet());
-
- String serviceName = configServiceRefRegistry.getServiceInterfaceName(namespace, serviceType);
- try {
- /*
- * Remove transaction name as this is redundant - will be stripped in
- * DynamicWritableWrapper, and makes it hard to compare with service references
- * got from MXBean attributes
- */
- return ObjectNameUtil
- .withoutTransactionName(configServiceRefRegistry.getServiceReference(serviceName, refName));
- } catch (final InstanceNotFoundException e) {
- throw new IllegalArgumentException("No serviceInstance mapped to " + refName + " under service name "
- + serviceType + " , " + refNameToInstance.keySet(), e);
-
- }
- }
-
- public Map<String, Map<String, Map<String, String>>> getMappedServices() {
- Map<String, Map<String, Map<String, String>>> retVal = new HashMap<>();
-
- Map<String, Map<String, ObjectName>> serviceMapping = configServiceRefRegistry.getServiceMapping();
- for (Map.Entry<String, Map<String, ObjectName>> nameToRefEntry : serviceMapping.entrySet()) {
- for (String refName : nameToRefEntry.getValue().keySet()) {
-
- ObjectName on = nameToRefEntry.getValue().get(refName);
- Services.ServiceInstance si = Services.ServiceInstance.fromObjectName(on);
-
- QName qname = QName.create(nameToRefEntry.getKey());
- String namespace = qname.getNamespace().toString();
- Map<String, Map<String, String>> serviceToRefs = retVal.computeIfAbsent(namespace,
- k -> new HashMap<>());
-
- String localName = qname.getLocalName();
- Map<String, String> refsToSis = serviceToRefs.computeIfAbsent(localName, k -> new HashMap<>());
-
- Preconditions.checkState(!refsToSis.containsKey(refName),
- "Duplicate reference name %s for service %s:%s, now for instance %s", refName, namespace,
- localName, on);
- refsToSis.put(refName, si.toString());
- }
- }
-
- return retVal;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.config;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.ObjectNameAttributeReadingStrategy;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public final class Services {
-
- private static final String EMPTY_PROVIDER = "";
- private static final String PROVIDER_KEY = "provider";
- private static final String NAME_KEY = "name";
- public static final String TYPE_KEY = "type";
- public static final String SERVICE_KEY = "service";
-
- private final Map<String
- /* Namespace */,
- Map<String/* ServiceName */,
- Map<String/* refName */,
- ServiceInstance>>> namespaceToServiceNameToRefNameToInstance = new HashMap<>();
-
- public Map<String, Map<String, Map<String, ServiceInstance>>> getNamespaceToServiceNameToRefNameToInstance() {
- return namespaceToServiceNameToRefNameToInstance;
- }
-
- private static Services resolveServices(final Map<String, Map<String, Map<String, String>>> mappedServices) {
- Services tracker = new Services();
-
- for (Entry<String, Map<String, Map<String, String>>> namespaceEntry : mappedServices.entrySet()) {
- String namespace = namespaceEntry.getKey();
-
- for (Entry<String, Map<String, String>> serviceEntry : namespaceEntry.getValue().entrySet()) {
-
- String serviceName = serviceEntry.getKey();
- for (Entry<String, String> refEntry : serviceEntry.getValue().entrySet()) {
-
- Map<String, Map<String, ServiceInstance>> namespaceToServices =
- tracker.namespaceToServiceNameToRefNameToInstance
- .computeIfAbsent(namespace, k -> new HashMap<>());
-
- Map<String, ServiceInstance> refNameToInstance = namespaceToServices.computeIfAbsent(serviceName,
- k -> new HashMap<>());
-
- String refName = refEntry.getKey();
- // we want to compare reference not value of the provider
- refNameToInstance.put(refName, refEntry.getValue() == EMPTY_PROVIDER
- // provider name cannot be EMPTY_PROVIDER instance unless we are executing
- // delete
- ? ServiceInstance.EMPTY_SERVICE_INSTANCE
- : ServiceInstance.fromString(refEntry.getValue()));
-
- }
- }
- }
- return tracker;
- }
-
- // TODO support edit strategies on services
-
- public static Services fromXml(final XmlElement xml) throws DocumentedException {
- Map<String, Map<String, Map<String, String>>> retVal = new HashMap<>();
-
- List<XmlElement> services = xml.getChildElements(SERVICE_KEY);
- xml.checkUnrecognisedElements(services);
-
- for (XmlElement service : services) {
-
- XmlElement typeElement = service.getOnlyChildElement(TYPE_KEY);
- Entry<String, String> prefixNamespace = typeElement.findNamespaceOfTextContent();
-
- Preconditions.checkState(prefixNamespace.getKey() != null && !prefixNamespace.getKey().equals(""),
- "Type attribute was not prefixed");
-
- Map<String, Map<String, String>> namespaceToServices = retVal.computeIfAbsent(prefixNamespace.getValue(),
- k -> new HashMap<>());
-
- String serviceName = ObjectNameAttributeReadingStrategy.checkPrefixAndExtractServiceName(typeElement,
- prefixNamespace);
-
- Map<String, String> innerMap = namespaceToServices.computeIfAbsent(serviceName, k -> new HashMap<>());
-
- List<XmlElement> instances = service.getChildElements(XmlMappingConstants.INSTANCE_KEY);
- service.checkUnrecognisedElements(instances, typeElement);
-
- for (XmlElement instance : instances) {
- XmlElement nameElement = instance.getOnlyChildElement(NAME_KEY);
- String refName = nameElement.getTextContent();
-
- if (!ModifyAction.DELETE.toString().toLowerCase()
- .equals(instance.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
- XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0))) {
- XmlElement providerElement = instance.getOnlyChildElement(PROVIDER_KEY);
- String providerName = providerElement.getTextContent();
-
- instance.checkUnrecognisedElements(nameElement, providerElement);
-
- innerMap.put(refName, providerName);
- } else {
- // since this is a delete we dont have a provider name - we want empty service
- // instance
- innerMap.put(refName, EMPTY_PROVIDER);
- }
- }
- }
-
- return resolveServices(retVal);
- }
-
- public static Element toXml(final ServiceRegistryWrapper serviceRegistryWrapper, final Document document) {
- final Optional<String> configNs = Optional
- .of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
- Element root = XmlUtil.createElement(document, XmlMappingConstants.SERVICES_KEY, configNs);
-
- Map<String, Map<String, Map<String, String>>> mappedServices = serviceRegistryWrapper.getMappedServices();
- for (Entry<String, Map<String, Map<String, String>>> namespaceToRefEntry : mappedServices.entrySet()) {
-
- for (Entry<String, Map<String, String>> serviceEntry : namespaceToRefEntry.getValue().entrySet()) {
- // service belongs to config.yang namespace
- Element serviceElement = XmlUtil.createElement(document, SERVICE_KEY, configNs);
- root.appendChild(serviceElement);
-
- // type belongs to config.yang namespace
- String serviceType = serviceEntry.getKey();
- Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document,
- XmlMappingConstants.TYPE_KEY, XmlMappingConstants.PREFIX, namespaceToRefEntry.getKey(),
- serviceType, configNs);
-
- serviceElement.appendChild(typeElement);
-
- for (Entry<String, String> instanceEntry : serviceEntry.getValue().entrySet()) {
- Element instanceElement = XmlUtil.createElement(document, XmlMappingConstants.INSTANCE_KEY,
- configNs);
- serviceElement.appendChild(instanceElement);
-
- Element nameElement = XmlUtil.createTextElement(document, NAME_KEY, instanceEntry.getKey(),
- configNs);
- instanceElement.appendChild(nameElement);
-
- Element providerElement = XmlUtil.createTextElement(document, PROVIDER_KEY,
- instanceEntry.getValue(), configNs);
- instanceElement.appendChild(providerElement);
- }
- }
-
- }
- return root;
- }
-
- public static final class ServiceInstance {
- public static final ServiceInstance EMPTY_SERVICE_INSTANCE = new ServiceInstance("", "");
-
- public ServiceInstance(final String moduleName, final String instanceName) {
- this.moduleName = moduleName;
- this.instanceName = instanceName;
- }
-
- public static ServiceInstance fromString(String instanceId) {
- instanceId = instanceId.trim();
- Matcher matcher = PATTERN.matcher(instanceId);
- if (!matcher.matches()) {
- matcher = PATTERN_DEPRECATED.matcher(instanceId);
- }
-
- Preconditions.checkArgument(matcher.matches(),
- "Unexpected format for provider, expected " + PATTERN.toString()
- + " or " + PATTERN_DEPRECATED.toString() + " but was " + instanceId);
-
- String factoryName = matcher.group(1);
- String instanceName = matcher.group(2);
- return new ServiceInstance(factoryName, instanceName);
- }
-
- private final String moduleName;
- private final String instanceName;
-
- private String serviceName;
-
- public String getServiceName() {
- return serviceName;
- }
-
- public void setServiceName(final String serviceName) {
- this.serviceName = serviceName;
- }
-
- public String getModuleName() {
- return moduleName;
- }
-
- public String getInstanceName() {
- return instanceName;
- }
-
- private static final String BLUEPRINT = "/" + XmlMappingConstants.MODULES_KEY + "/"
- + XmlMappingConstants.MODULE_KEY + "[" + XmlMappingConstants.TYPE_KEY + "='%s']["
- + XmlMappingConstants.NAME_KEY + "='%s']";
-
- // TODO unify with xpath in RuntimeRpc
-
- // Previous version of xpath, needs to be supported for backwards compatibility
- // (persisted configs by config-persister)
- private static final String BLUEPRINTR_DEPRECATED = "/" + XmlMappingConstants.CONFIG_KEY + "/"
- + XmlMappingConstants.MODULES_KEY + "/" + XmlMappingConstants.MODULE_KEY + "\\["
- + XmlMappingConstants.NAME_KEY + "='%s'\\]/" + XmlMappingConstants.INSTANCE_KEY + "\\["
- + XmlMappingConstants.NAME_KEY + "='%s'\\]";
-
- private static final String BLUEPRINTR = "/" + XmlMappingConstants.MODULES_KEY + "/"
- + XmlMappingConstants.MODULE_KEY + "\\[" + XmlMappingConstants.TYPE_KEY + "='%s'\\]\\["
- + XmlMappingConstants.NAME_KEY + "='%s'\\]";
-
- private static final Pattern PATTERN_DEPRECATED =
- Pattern.compile(String.format(BLUEPRINTR_DEPRECATED, "(.+)", "(.+)"));
- private static final Pattern PATTERN = Pattern.compile(String.format(BLUEPRINTR, "(.+)", "(.+)"));
-
- @Override
- public String toString() {
- return String.format(BLUEPRINT, moduleName, instanceName);
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (instanceName == null ? 0 : instanceName.hashCode());
- result = prime * result + (moduleName == null ? 0 : moduleName.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- ServiceInstance other = (ServiceInstance) obj;
- if (instanceName == null) {
- if (other.instanceName != null) {
- return false;
- }
- } else if (!instanceName.equals(other.instanceName)) {
- return false;
- }
- if (moduleName == null) {
- if (other.moduleName != null) {
- return false;
- }
- } else if (!moduleName.equals(other.moduleName)) {
- return false;
- }
- return true;
- }
-
- public ObjectName getObjectName(final String transactionName) {
- return ObjectNameUtil.createTransactionModuleON(transactionName, moduleName, instanceName);
- }
-
- public static ServiceInstance fromObjectName(final ObjectName on) {
- return new ServiceInstance(ObjectNameUtil.getFactoryName(on), ObjectNameUtil.getInstanceName(on));
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.osgi;
-
-public interface EnumResolver {
-
- String fromYang(String enumType, String enumYangValue);
-
- String toYang(String enumType, String enumJavaValue);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.osgi;
-
-import com.google.common.base.Preconditions;
-import java.lang.management.ManagementFactory;
-import java.util.Hashtable;
-import java.util.concurrent.atomic.AtomicBoolean;
-import javax.management.MBeanServer;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
-import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
-import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
-import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.ServiceTracker;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Start yang store service and the XML config manager facade.
- */
-public class YangStoreActivator implements BundleActivator {
-
- private static final Logger LOG = LoggerFactory.getLogger(YangStoreActivator.class);
-
- private final MBeanServer configMBeanServer = ManagementFactory.getPlatformMBeanServer();
-
- private ServiceRegistration<YangStoreService> yangStoreServiceServiceRegistration;
- private ConfigRegistryLookupThread configRegistryLookup = null;
- private BundleContext context;
- private ServiceRegistration<ConfigSubsystemFacadeFactory> osgiRegistrayion;
-
- @Override
- @SuppressWarnings("checkstyle:hiddenField")
- public void start(final BundleContext context) throws Exception {
- LOG.debug("ConfigPersister starting");
- this.context = context;
-
- final ServiceTrackerCustomizer<SchemaContextProvider, YangStoreService> schemaServiceTrackerCustomizer =
- new ServiceTrackerCustomizer<SchemaContextProvider, YangStoreService>() {
-
- private final AtomicBoolean alreadyStarted = new AtomicBoolean(false);
-
- @Override
- public YangStoreService addingService(final ServiceReference<SchemaContextProvider> reference) {
- LOG.debug("Got addingService(SchemaContextProvider) event");
- if (reference.getProperty(SchemaSourceProvider.class.getName()) == null
- && reference.getProperty(BindingRuntimeContext.class.getName()) == null) {
- LOG.debug("SchemaContextProvider not from config-manager. Ignoring");
- return null;
- }
-
- // Yang store service should not be registered multiple times
- if (!this.alreadyStarted.compareAndSet(false, true)) {
- LOG.warn("Starting yang store service multiple times. Received new service {}", reference);
- throw new RuntimeException("Starting yang store service multiple times");
- }
- final SchemaContextProvider schemaContextProvider = reference.getBundle().getBundleContext()
- .getService(reference);
- final Object sourceProvider = Preconditions.checkNotNull(
- reference.getProperty(SchemaSourceProvider.class.getName()), "Source provider not found");
- Preconditions.checkArgument(sourceProvider instanceof SchemaSourceProvider);
-
- // TODO avoid cast
- final YangStoreService yangStoreService = new YangStoreService(schemaContextProvider,
- (SchemaSourceProvider<YangTextSchemaSource>) sourceProvider);
-
- final BindingRuntimeContext runtimeContext = (BindingRuntimeContext) reference
- .getProperty(BindingRuntimeContext.class.getName());
- LOG.debug("BindingRuntimeContext retrieved as {}", runtimeContext);
- if (runtimeContext != null) {
- yangStoreService.refresh(runtimeContext);
- }
-
- YangStoreActivator.this.yangStoreServiceServiceRegistration = context
- .registerService(YangStoreService.class, yangStoreService, new Hashtable<>());
- YangStoreActivator.this.configRegistryLookup = new ConfigRegistryLookupThread(yangStoreService);
- YangStoreActivator.this.configRegistryLookup.start();
- return yangStoreService;
- }
-
- @Override
- public void modifiedService(final ServiceReference<SchemaContextProvider> reference,
- final YangStoreService service) {
- if (service == null) {
- return;
- }
-
- LOG.debug("Got modifiedService(SchemaContextProvider) event");
- final BindingRuntimeContext runtimeContext = (BindingRuntimeContext) reference
- .getProperty(BindingRuntimeContext.class.getName());
- LOG.debug("BindingRuntimeContext retrieved as {}", runtimeContext);
- service.refresh(runtimeContext);
- }
-
- @Override
- public void removedService(final ServiceReference<SchemaContextProvider> reference,
- final YangStoreService service) {
- if (service == null) {
- return;
- }
-
- LOG.debug("Got removedService(SchemaContextProvider) event");
- this.alreadyStarted.set(false);
- YangStoreActivator.this.configRegistryLookup.interrupt();
- YangStoreActivator.this.yangStoreServiceServiceRegistration.unregister();
- YangStoreActivator.this.yangStoreServiceServiceRegistration = null;
- }
- };
-
- final ServiceTracker<SchemaContextProvider, YangStoreService> schemaContextProviderServiceTracker =
- new ServiceTracker<>(context, SchemaContextProvider.class, schemaServiceTrackerCustomizer);
- schemaContextProviderServiceTracker.open();
- }
-
- @Override
- @SuppressWarnings("checkstyle:hiddenField")
- public void stop(final BundleContext context) throws Exception {
- if (this.configRegistryLookup != null) {
- this.configRegistryLookup.interrupt();
- }
- if (this.osgiRegistrayion != null) {
- this.osgiRegistrayion.unregister();
- }
- if (this.yangStoreServiceServiceRegistration != null) {
- this.yangStoreServiceServiceRegistration.unregister();
- this.yangStoreServiceServiceRegistration = null;
- }
- }
-
- /**
- * Find ConfigRegistry from config manager in JMX.
- */
- private class ConfigRegistryLookupThread extends Thread {
- public static final int ATTEMPT_TIMEOUT_MS = 1000;
- private static final int SILENT_ATTEMPTS = 30;
-
- private final YangStoreService yangStoreService;
-
- ConfigRegistryLookupThread(final YangStoreService yangStoreService) {
- super("config-registry-lookup");
- this.yangStoreService = yangStoreService;
- }
-
- @Override
- public void run() {
-
- ConfigRegistryJMXClient configRegistryJMXClient;
- ConfigRegistryJMXClient configRegistryJMXClientNoNotifications;
- int index = 0;
- // Config registry might not be present yet, but will be eventually
- while (true) {
-
- try {
- configRegistryJMXClient = new ConfigRegistryJMXClient(YangStoreActivator.this.configMBeanServer);
- configRegistryJMXClientNoNotifications = ConfigRegistryJMXClient
- .createWithoutNotifications(YangStoreActivator.this.configMBeanServer);
- break;
- } catch (final IllegalStateException e) {
- ++index;
- if (index > SILENT_ATTEMPTS) {
- LOG.info("JMX client not created after {} attempts, still trying", index, e);
- } else {
- LOG.debug("JMX client could not be created, reattempting, try {}", index, e);
- }
- try {
- Thread.sleep(ATTEMPT_TIMEOUT_MS);
- } catch (final InterruptedException e1) {
- Thread.currentThread().interrupt();
- throw new IllegalStateException("Interrupted while reattempting connection", e1);
- }
- }
- }
-
- final ConfigRegistryJMXClient jmxClient = configRegistryJMXClient;
- final ConfigRegistryJMXClient jmxClientNoNotifications = configRegistryJMXClientNoNotifications;
- if (index > SILENT_ATTEMPTS) {
- LOG.info("Created JMX client after {} attempts", index);
- } else {
- LOG.debug("Created JMX client after {} attempts", index);
- }
-
- final ConfigSubsystemFacadeFactory configSubsystemFacade = new ConfigSubsystemFacadeFactory(jmxClient,
- jmxClientNoNotifications, this.yangStoreService);
- YangStoreActivator.this.osgiRegistrayion = YangStoreActivator.this.context
- .registerService(ConfigSubsystemFacadeFactory.class, configSubsystemFacade, new Hashtable<>());
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.facade.xml.osgi;
-
-import java.util.Map;
-import java.util.Set;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-
-public interface YangStoreContext {
-
- /**
- * Yang store context.
- *
- * @deprecated Use {@link #getQNamesToIdentitiesToModuleMXBeanEntries()}
- * instead. This method return only one module representation even
- * if multiple revisions are available.
- */
- @Deprecated
- Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */,
- ModuleMXBeanEntry>> getModuleMXBeanEntryMap();
-
- Map<QName, Map<String /* identity local name */, ModuleMXBeanEntry>> getQNamesToIdentitiesToModuleMXBeanEntries();
-
- /**
- * Get all modules discovered when this snapshot was created.
- *
- * @return all modules discovered. If one module exists with two different
- * revisions, return both.
- */
- Set<Module> getModules();
-
- String getModuleSource(SourceIdentifier moduleIdentifier);
-
- EnumResolver getEnumResolver();
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.osgi;
-
-import com.google.common.collect.Collections2;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Sets;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import javax.annotation.concurrent.GuardedBy;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.controller.config.util.capability.ModuleListener;
-import org.opendaylight.controller.config.util.capability.YangModuleCapability;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
-import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
-
-public class YangStoreService implements YangStoreContext {
-
- private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
- private final ExecutorService notificationExecutor = Executors.newSingleThreadExecutor(
- new ThreadFactoryBuilder().setDaemon(true).setNameFormat("yangstore-capability-notifications").build());
-
- /**
- * Guarded by explicit lock to allow for properly synchronizing the initial
- * notification and modification of the listener set.
- */
- @GuardedBy("listeners")
- private final Set<ModuleListener> listeners = new HashSet<>();
-
- /**
- * This is the latest snapshot. Some of its state is always initialized, but the
- * MXBean maps potentially cause recomputation. Accessing those two specific
- * methods needs to re-check whether the snapshot has changed asynchronously and
- * retry if it didi.
- */
- private volatile YangStoreSnapshot snap;
-
- public YangStoreService(final SchemaContextProvider schemaContextProvider,
- final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
- this.sourceProvider = sourceProvider;
- }
-
- public YangStoreContext getCurrentSnapshot() {
- return this.snap;
- }
-
- @Deprecated
- @Override
- public Map<String, Map<String, ModuleMXBeanEntry>> getModuleMXBeanEntryMap() {
- Map<String, Map<String, ModuleMXBeanEntry>> ret;
- YangStoreSnapshot snapshot;
-
- do {
- snapshot = this.snap;
- ret = snapshot.getModuleMXBeanEntryMap();
- } while (!snapshot.equals(this.snap));
-
- return ret;
- }
-
- @Override
- public Map<QName, Map<String, ModuleMXBeanEntry>> getQNamesToIdentitiesToModuleMXBeanEntries() {
- Map<QName, Map<String, ModuleMXBeanEntry>> ret;
- YangStoreSnapshot snapshot;
-
- do {
- snapshot = this.snap;
- ret = snapshot.getQNamesToIdentitiesToModuleMXBeanEntries();
- } while (!snapshot.equals(this.snap));
-
- return ret;
- }
-
- @Override
- public Set<Module> getModules() {
- return this.snap.getModules();
- }
-
- @Override
- public String getModuleSource(final SourceIdentifier moduleIdentifier) {
- return this.snap.getModuleSource(moduleIdentifier);
- }
-
- @Override
- public EnumResolver getEnumResolver() {
- return this.snap.getEnumResolver();
- }
-
- public void refresh(final BindingRuntimeContext runtimeContext) {
- final YangStoreSnapshot next = new YangStoreSnapshot(runtimeContext, this.sourceProvider);
- final YangStoreSnapshot previous = this.snap;
- this.snap = next;
- this.notificationExecutor.submit(() -> notifyListeners(previous, next));
- }
-
- public AutoCloseable registerModuleListener(final ModuleListener listener) {
- final YangStoreContext context = this.snap;
-
- synchronized (this.listeners) {
- if (context != null) {
- listener.onCapabilitiesChanged(toCapabilities(context.getModules(), context),
- Collections.<Capability>emptySet());
- }
- this.listeners.add(listener);
- }
-
- return () -> {
- synchronized (YangStoreService.this.listeners) {
- YangStoreService.this.listeners.remove(listener);
- }
- };
- }
-
- void notifyListeners(final YangStoreSnapshot previous, final YangStoreSnapshot current) {
- final Set<Module> prevModules = previous.getModules();
- final Set<Module> currModules = current.getModules();
- final Set<Module> removed = Sets.difference(prevModules, currModules);
- final Set<Module> added = Sets.difference(currModules, prevModules);
-
- final Set<Capability> addedCaps = toCapabilities(added, current);
- final Set<Capability> removedCaps = toCapabilities(removed, current);
-
- synchronized (this.listeners) {
- for (final ModuleListener listener : this.listeners) {
- listener.onCapabilitiesChanged(addedCaps, removedCaps);
- }
- }
- }
-
- private static Set<Capability> toCapabilities(final Set<Module> modules, final YangStoreContext current) {
- return ImmutableSet.copyOf(Collections2.transform(modules,
- input -> new YangModuleCapability(input, current.getModuleSource(
- RevisionSourceIdentifier.create(input.getName(), input.getRevision())))));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.osgi;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.BiMap;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import com.google.common.io.ByteStreams;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.ref.SoftReference;
-import java.nio.charset.StandardCharsets;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Objects;
-import java.util.Set;
-import java.util.concurrent.ExecutionException;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
-import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
-import org.opendaylight.mdsal.binding.yang.types.TypeProviderImpl;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
-import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class YangStoreSnapshot implements YangStoreContext, EnumResolver {
- private static final class MXBeans {
- private final Map<String /* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> moduleMXBeanEntryMap;
- private final Map<QName, Map<String, ModuleMXBeanEntry>> namesToIdentitiesToModuleMXBeanEntries;
-
- MXBeans(final SchemaContext schemaContext) {
- LOG.trace("Resolved modules:{}", schemaContext.getModules());
-
- // JMX generator
- final Map<String, String> namespaceToPackageMapping = Maps.newHashMap();
- final PackageTranslator packageTranslator = new PackageTranslator(namespaceToPackageMapping);
- final Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>();
- final Map<IdentitySchemaNode, ServiceInterfaceEntry> knownSEITracker = new HashMap<>();
- // create SIE structure qNamesToSIEs
- for (final Module module : schemaContext.getModules()) {
- final String packageName = packageTranslator.getPackageName(module);
- final Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry
- .create(module, packageName, knownSEITracker);
- for (final Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries.entrySet()) {
- // merge value into qNamesToSIEs
- if (!qNamesToSIEs.containsKey(sieEntry.getKey())) {
- qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
- } else {
- throw new IllegalStateException("Cannot add two SIE with same qname "
- + sieEntry.getValue());
- }
- }
- }
-
- final Map<String, Map<String, ModuleMXBeanEntry>> moduleMXBeanEntries = Maps.newHashMap();
-
- final Map<QName, Map<String /* identity local name */,
- ModuleMXBeanEntry>> qNamesToIdentitiesToModuleMXBeanEntries = new HashMap<>();
-
-
- for (final Module module : schemaContext.getModules()) {
- final String packageName = packageTranslator.getPackageName(module);
- final TypeProviderWrapper typeProviderWrapper = new TypeProviderWrapper(
- new TypeProviderImpl(schemaContext));
-
- final QName qName = QName.create(module.getNamespace(), module.getRevision(), module.getName());
-
- final Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs =
- Collections.unmodifiableMap(ModuleMXBeanEntry.create(module, qNamesToSIEs, schemaContext,
- typeProviderWrapper, packageName));
- moduleMXBeanEntries.put(module.getNamespace().toString(), namesToMBEs);
-
- qNamesToIdentitiesToModuleMXBeanEntries.put(qName, namesToMBEs);
- }
- this.moduleMXBeanEntryMap = Collections.unmodifiableMap(moduleMXBeanEntries);
- this.namesToIdentitiesToModuleMXBeanEntries =
- Collections.unmodifiableMap(qNamesToIdentitiesToModuleMXBeanEntries);
- }
- }
-
- private static final Logger LOG = LoggerFactory.getLogger(YangStoreSnapshot.class);
- private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
- private final BindingRuntimeContext bindingContextProvider;
-
- /**
- * We want to lazily compute the context of the MXBean class and have it only softly-attached to this instance,
- * so it can be garbage collected when the memory gets tight. If the schema context changes as we are computing
- * things, YangStoreService will detect that and retry, so we do not have to worry about that.
- */
- private volatile SoftReference<MXBeans> ref = new SoftReference<>(null);
-
- public YangStoreSnapshot(final BindingRuntimeContext bindingContextProvider,
- final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
- this.bindingContextProvider = Preconditions.checkNotNull(bindingContextProvider);
- this.sourceProvider = Preconditions.checkNotNull(sourceProvider);
- }
-
- private MXBeans getMXBeans() {
- MXBeans mxBean = this.ref.get();
-
- if (mxBean == null) {
- synchronized (this) {
- mxBean = this.ref.get();
- if (mxBean == null) {
- mxBean = new MXBeans(this.bindingContextProvider.getSchemaContext());
- this.ref = new SoftReference<>(mxBean);
- }
- }
- }
-
- return mxBean;
- }
-
- @Override
- public Map<String, Map<String, ModuleMXBeanEntry>> getModuleMXBeanEntryMap() {
- return getMXBeans().moduleMXBeanEntryMap;
- }
-
- @Override
- public Map<QName, Map<String, ModuleMXBeanEntry>> getQNamesToIdentitiesToModuleMXBeanEntries() {
- return getMXBeans().namesToIdentitiesToModuleMXBeanEntries;
- }
-
- @Override
- public Set<Module> getModules() {
- final Set<Module> modules = Sets.newHashSet(this.bindingContextProvider.getSchemaContext().getModules());
- for (final Module module : this.bindingContextProvider.getSchemaContext().getModules()) {
- modules.addAll(module.getSubmodules());
- }
- return modules;
- }
-
- @Override
- public String getModuleSource(final SourceIdentifier moduleIdentifier) {
- final ListenableFuture<? extends YangTextSchemaSource> source = this.sourceProvider.getSource(
- RevisionSourceIdentifier.create(moduleIdentifier.getName(), moduleIdentifier.getRevision()));
- try {
- final YangTextSchemaSource yangTextSchemaSource = source.get();
- try (InputStream inStream = yangTextSchemaSource.openStream()) {
- return new String(ByteStreams.toByteArray(inStream), StandardCharsets.UTF_8);
- }
- } catch (ExecutionException | InterruptedException | IOException e) {
- LOG.warn("Unable to provide source for {}", moduleIdentifier, e);
- throw new IllegalArgumentException("Unable to provide source for " + moduleIdentifier, e);
- }
- }
-
- @Override
- public EnumResolver getEnumResolver() {
- return this;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof YangStoreSnapshot)) {
- return false;
- }
-
- final YangStoreSnapshot other = (YangStoreSnapshot) obj;
- return Objects.equals(this.bindingContextProvider, other.bindingContextProvider);
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(this.bindingContextProvider);
- }
-
- @Override
- public String fromYang(final String enumClass, final String enumYangValue) {
- Preconditions.checkState(this.bindingContextProvider != null, "Binding context provider was not set yet");
- final BiMap<String, String> enumMapping = this.bindingContextProvider.getEnumMapping(enumClass);
- final String javaName = enumMapping.get(enumYangValue);
- return Preconditions.checkNotNull(javaName,
- "Unable to resolve enum value %s for enum class %s with assumed enum mapping: %s", enumYangValue,
- enumClass, enumMapping);
- }
-
- @Override
- public String toYang(final String enumClass, final String enumJavaValue) {
- Preconditions.checkState(this.bindingContextProvider != null, "Binding context provider was not set yet");
- final BiMap<String, String> enumMapping = this.bindingContextProvider.getEnumMapping(enumClass);
- final String javaName = enumMapping.inverse().get(enumJavaValue);
- return Preconditions.checkNotNull(javaName,
- "Unable to map enum value %s for enum class %s with assumed enum mapping: %s", enumJavaValue, enumClass,
- enumMapping.inverse());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.rpc;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Maps;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeReadingStrategy;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.ObjectXmlReader;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving.AttributeResolvingStrategy;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving.ObjectResolver;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry.Rpc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.yangtools.yang.common.Revision;
-
-public final class InstanceRuntimeRpc {
-
- private final Map<String, AttributeIfc> yangToAttrConfig;
- private final Rpc rpc;
- private final EnumResolver enumResolver;
-
- public InstanceRuntimeRpc(final Rpc rpc, final EnumResolver enumResolver) {
- this.enumResolver = enumResolver;
- this.yangToAttrConfig = map(rpc.getParameters());
- this.rpc = rpc;
- }
-
- private Map<String, AttributeIfc> map(final List<JavaAttribute> parameters) {
- Map<String, AttributeIfc> mapped = Maps.newHashMap();
- for (JavaAttribute javaAttribute : parameters) {
- mapped.put(javaAttribute.getAttributeYangName(), javaAttribute);
- }
- return mapped;
- }
-
- private void resolveConfiguration(final Map<String, AttributeConfigElement> mappedConfig) {
-
- // TODO make field, resolvingStrategies can be instantiated only once
- Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> resolvingStrategies = new ObjectResolver(null)
- .prepareResolving(yangToAttrConfig, enumResolver);
- // TODO make constructor for object resolver without service tracker
- for (Entry<String, AttributeConfigElement> configDefEntry : mappedConfig.entrySet()) {
- try {
-
- AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy = resolvingStrategies
- .get(configDefEntry.getKey());
-
- configDefEntry.getValue().resolveValue(attributeResolvingStrategy, configDefEntry.getKey());
- configDefEntry.getValue()
- .setJmxName(yangToAttrConfig.get(configDefEntry.getKey()).getUpperCaseCammelCase());
- } catch (final DocumentedException e) {
- throw new IllegalStateException("Unable to resolve value " + configDefEntry.getValue()
- + " to attribute " + configDefEntry.getKey(), e);
- }
- }
- }
-
- public Map<String, AttributeConfigElement> fromXml(final XmlElement configRootNode) throws DocumentedException {
- Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
-
- // FIXME add identity map to runtime data
- Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig,
- Collections.<String, Map<Optional<Revision>, IdentityMapping>>emptyMap());
-
- for (Entry<String, AttributeReadingStrategy> readStratEntry : strats.entrySet()) {
- List<XmlElement> configNodes = configRootNode.getChildElements(readStratEntry.getKey());
- AttributeConfigElement readElement = readStratEntry.getValue().readElement(configNodes);
- retVal.put(readStratEntry.getKey(), readElement);
- }
-
- resolveConfiguration(retVal);
- return retVal;
- }
-
- public String getName() {
- return rpc.getName();
- }
-
- public AttributeIfc getReturnType() {
- return rpc.getReturnType();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.rpc;
-
-import com.google.common.base.Preconditions;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry.Rpc;
-
-public final class ModuleRpcs {
-
- private final Map<String, String> yangToJavaNames = new HashMap<>();
- private final Map<String, Map<String, InstanceRuntimeRpc>> rpcMapping = new HashMap<>();
- private final EnumResolver enumResolver;
-
- public ModuleRpcs(final EnumResolver enumResolver) {
- this.enumResolver = enumResolver;
- }
-
- public void addNameMapping(RuntimeBeanEntry runtimeEntry) {
- String yangName = runtimeEntry.getYangName();
- Preconditions.checkState(!yangToJavaNames.containsKey(yangName),
- "RuntimeBean %s found twice in same namespace", yangName);
- yangToJavaNames.put(yangName, runtimeEntry.getJavaNamePrefix());
- }
-
- public void addRpc(RuntimeBeanEntry runtimeEntry, Rpc rpc) {
- String yangName = runtimeEntry.getYangName();
- Map<String, InstanceRuntimeRpc> map = rpcMapping.computeIfAbsent(yangName, k -> new HashMap<>());
-
- Preconditions.checkState(!map.containsKey(rpc.getYangName()), "Rpc %s for runtime bean %s added twice",
- rpc.getYangName(), yangName);
- map.put(rpc.getYangName(), new InstanceRuntimeRpc(rpc, enumResolver));
- }
-
- public String getRbeJavaName(String yangName) {
- String javaName = yangToJavaNames.get(yangName);
- Preconditions.checkState(javaName != null,
- "No runtime bean entry found under yang name %s, available yang names %s", yangName,
- yangToJavaNames.keySet());
- return javaName;
- }
-
- public InstanceRuntimeRpc getRpc(String rbeName, String rpcName) {
- Map<String, InstanceRuntimeRpc> rpcs = rpcMapping.get(rbeName);
- Preconditions.checkState(rpcs != null, "No rpcs found for runtime bean %s", rbeName);
- InstanceRuntimeRpc rpc = rpcs.get(rpcName);
- Preconditions.checkState(rpc != null, "No rpc found for runtime bean %s with name %s", rbeName, rpcName);
- return rpc;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.rpc;
-
-import com.google.common.base.Preconditions;
-import java.util.Map;
-
-public class Rpcs {
- private final Map<String, Map<String, ModuleRpcs>> mappedRpcs;
-
- public Rpcs(Map<String, Map<String, ModuleRpcs>> mappedRpcs) {
- this.mappedRpcs = mappedRpcs;
- }
-
- public ModuleRpcs getRpcMapping(RuntimeRpcElementResolved id) {
- Map<String, ModuleRpcs> modules = mappedRpcs.get(id.getNamespace());
- Preconditions.checkState(modules != null, "No modules found for namespace %s", id.getNamespace());
- String moduleName = id.getModuleName();
- ModuleRpcs rpcMapping = modules.get(moduleName);
- Preconditions.checkState(rpcMapping != null, "No module %s found for namespace %s", moduleName,
- id.getNamespace());
-
- return rpcMapping;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.rpc;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.common.collect.Maps;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.Modules;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.modules.Module;
-
-/**
- * Represents parsed xpath to runtime bean instance.
- */
-public final class RuntimeRpcElementResolved {
- private final String moduleName;
- private final String instanceName;
- private final String namespace;
- private final String runtimeBeanName;
- private final Map<String, String> additionalAttributes;
-
- private RuntimeRpcElementResolved(String namespace, String moduleName, String instanceName, String runtimeBeanName,
- Map<String, String> additionalAttributes) {
- this.moduleName = Preconditions.checkNotNull(moduleName, "Module name");
- this.instanceName = Preconditions.checkNotNull(instanceName, "Instance name");
- this.additionalAttributes = additionalAttributes;
- this.namespace = Preconditions.checkNotNull(namespace, "Namespace");
- this.runtimeBeanName = Preconditions.checkNotNull(runtimeBeanName, "Runtime bean name");
- }
-
- public String getModuleName() {
- return moduleName;
- }
-
- @VisibleForTesting
- Map<String, String> getAdditionalAttributes() {
- return additionalAttributes;
- }
-
- public String getInstanceName() {
- return instanceName;
- }
-
- public String getNamespace() {
- return namespace;
- }
-
- public String getRuntimeBeanName() {
- return runtimeBeanName;
- }
-
- public ObjectName getObjectName(ModuleRpcs rpcMapping) {
- Map<String, String> additionalAttributesJavaNames = Maps
- .newHashMapWithExpectedSize(additionalAttributes.size());
- for (String attributeYangName : additionalAttributes.keySet()) {
- String attributeJavaName = rpcMapping.getRbeJavaName(attributeYangName);
- Preconditions.checkState(attributeJavaName != null,
- "Cannot find java name for runtime bean wtih yang name %s", attributeYangName);
- additionalAttributesJavaNames.put(attributeJavaName, additionalAttributes.get(attributeYangName));
- }
- return ObjectNameUtil.createRuntimeBeanName(moduleName, instanceName, additionalAttributesJavaNames);
- }
-
- /**
- * Pattern for an absolute instance identifier xpath pointing to a runtime bean.
- * For instance e.g:
- *
- * <pre>
- * /modules/module[name=instanceName][type=moduleType]
- * </pre>
- *
- *<p>
- * or
- *
- * <pre>
- * /a:modules/a:module[a:name=instanceName][a:type=moduleType]
- * </pre>
- */
- private static final String XPATH_PATTERN_BLUEPRINT = "/" + getRegExForPrefixedName(Modules.QNAME.getLocalName())
- + "/" + getRegExForPrefixedName(Module.QNAME.getLocalName())
-
- + "\\[" + "(?<key1>" + getRegExForPrefixedName(XmlMappingConstants.TYPE_KEY) + "|"
- + getRegExForPrefixedName(XmlMappingConstants.NAME_KEY) + ")" + "=('|\")?(?<value1>[^'\"\\]]+)('|\")?"
- + "( and |\\]\\[)" + "(?<key2>" + getRegExForPrefixedName(XmlMappingConstants.TYPE_KEY) + "|"
- + getRegExForPrefixedName(XmlMappingConstants.NAME_KEY) + ")" + "=('|\")?(?<value2>[^'\"\\]]+)('|\")?"
- + "\\]"
-
- + "(?<additional>.*)";
-
- /**
- * Return reg ex that matches either the name with or without a prefix.
- */
- private static String getRegExForPrefixedName(final String name) {
- return "([^:]+:)?" + name;
- }
-
- private static final Pattern XPATH_PATTERN = Pattern.compile(XPATH_PATTERN_BLUEPRINT);
-
- /**
- * Pattern for additional path elements inside xpath for instance identifier
- * pointing to an inner runtime bean. E.g:
- *
- * <pre>
- * /modules/module[name=instanceName and type=moduleType]/inner[key=b]
- * </pre>
- */
- private static final String ADDITIONAL_PATTERN_BLUEPRINT = getRegExForPrefixedName("(?<additionalKey>.+)")
- + "\\[(?<prefixedKey>" + getRegExForPrefixedName("(.+)")
- + ")=('|\")?(?<additionalValue>[^'\"\\]]+)('|\")?\\]";
- private static final Pattern ADDITIONAL_PATTERN = Pattern.compile(ADDITIONAL_PATTERN_BLUEPRINT);
-
- public static RuntimeRpcElementResolved fromXpath(String xpath, String elementName, String namespace) {
- Matcher matcher = XPATH_PATTERN.matcher(xpath);
- Preconditions.checkState(matcher.matches(),
- "Node %s with value '%s' not in required form on rpc element %s, required format is %s",
- // TODO refactor this string, and/or unify with RPR.CONTEXT_INSTANCE from
- // netconf
- "context-instance", xpath, elementName, XPATH_PATTERN_BLUEPRINT);
-
- PatternGroupResolver groups = new PatternGroupResolver(matcher.group("key1"), matcher.group("value1"),
- matcher.group("value2"), matcher.group("additional"));
-
- String moduleName = groups.getModuleName();
- String instanceName = groups.getInstanceName();
-
- Map<String, String> additionalAttributes = groups.getAdditionalKeys(elementName, moduleName);
-
- return new RuntimeRpcElementResolved(namespace, moduleName, instanceName, groups.getRuntimeBeanYangName(),
- additionalAttributes);
- }
-
- private static final class PatternGroupResolver {
-
- private final String key1;
- private final String value1;
- private final String value2;
- private final String additional;
- private String runtimeBeanYangName;
-
- PatternGroupResolver(String key1, String value1, String value2, String additional) {
- this.key1 = Preconditions.checkNotNull(key1);
- this.value1 = Preconditions.checkNotNull(value1);
- this.value2 = Preconditions.checkNotNull(value2);
- this.additional = Preconditions.checkNotNull(additional);
- }
-
- String getModuleName() {
- return key1.contains(XmlMappingConstants.TYPE_KEY) ? value1 : value2;
- }
-
- String getInstanceName() {
- return key1.contains(XmlMappingConstants.NAME_KEY) ? value1 : value2;
- }
-
- Map<String, String> getAdditionalKeys(String elementName, String moduleName) {
- HashMap<String, String> additionalAttributes = Maps.newHashMap();
-
- runtimeBeanYangName = moduleName;
- for (String additionalKeyValue : additional.split("/")) {
- if (Strings.isNullOrEmpty(additionalKeyValue)) {
- continue;
- }
- Matcher matcher = ADDITIONAL_PATTERN.matcher(additionalKeyValue);
- Preconditions.checkState(matcher.matches(),
- "Attribute %s not in required form on rpc element %s,"
- + " required format for additional attributes is: %s",
- additionalKeyValue, elementName, ADDITIONAL_PATTERN_BLUEPRINT);
- String name = matcher.group("additionalKey");
- runtimeBeanYangName = name;
- additionalAttributes.put(name, matcher.group("additionalValue"));
- }
- return additionalAttributes;
- }
-
- private String getRuntimeBeanYangName() {
- Preconditions.checkState(runtimeBeanYangName != null);
- return runtimeBeanYangName;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.runtime;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Sets;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfig;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class InstanceRuntime {
-
- private static final String KEY_ATTRIBUTE_KEY = "key";
-
- private final InstanceConfig instanceMapping;
- private final Map<String, InstanceRuntime> childrenMappings;
- private final Map<String, String> jmxToYangChildRbeMapping;
-
- public InstanceRuntime(InstanceConfig instanceMapping, Map<String, InstanceRuntime> childrenMappings,
- Map<String, String> jmxToYangChildRbeMapping) {
- this.instanceMapping = instanceMapping;
- this.childrenMappings = childrenMappings;
- this.jmxToYangChildRbeMapping = jmxToYangChildRbeMapping;
- }
-
- /**
- * Finds all children runtime beans, same properties and values as current root
- * + any number of additional properties.
- */
- private Set<ObjectName> findChildren(ObjectName innerRootBean, Set<ObjectName> childRbeOns) {
- final Map<String, String> wantedProperties = innerRootBean.getKeyPropertyList();
-
- return Sets.newHashSet(Collections2.filter(childRbeOns, on -> {
- Map<String, String> localProperties = on.getKeyPropertyList();
- for (Entry<String, String> propertyEntry : wantedProperties.entrySet()) {
- if (!localProperties.containsKey(propertyEntry.getKey())) {
- return false;
- }
- if (!localProperties.get(propertyEntry.getKey()).equals(propertyEntry.getValue())) {
- return false;
- }
- if (localProperties.size() <= wantedProperties.size()) {
- return false;
- }
- }
- return true;
- }));
- }
-
- /**
- * Finds next level root runtime beans, beans that have the same properties as
- * current root + one additional.
- */
- private Set<ObjectName> getRootBeans(Set<ObjectName> childRbeOns, final String string, final int keyListSize) {
- return Sets.newHashSet(Collections2.filter(childRbeOns, on -> {
- if (on.getKeyPropertyList().size() != keyListSize + 1) {
- return false;
- }
- return on.getKeyPropertyList().containsKey(string);
- }));
- }
-
- public Element toXml(ObjectName rootOn, Set<ObjectName> childRbeOns, Document document, Element parentElement,
- String namespace, final EnumResolver enumResolver) {
- return toXml(rootOn, childRbeOns, document, null, parentElement, namespace, enumResolver);
- }
-
- public Element toXml(ObjectName rootOn, Set<ObjectName> childRbeOns, Document document, String instanceIndex,
- Element parentElement, String namespace, final EnumResolver enumResolver) {
- Element xml = instanceMapping.toXml(rootOn, namespace, document, parentElement, enumResolver);
-
- if (instanceIndex != null) {
- xml.setAttribute(KEY_ATTRIBUTE_KEY, instanceIndex);
- }
-
- for (Entry<String, InstanceRuntime> childMappingEntry : childrenMappings.entrySet()) {
- Set<ObjectName> innerRootBeans = getRootBeans(childRbeOns, childMappingEntry.getKey(),
- rootOn.getKeyPropertyList().size());
-
- for (ObjectName objectName : innerRootBeans) {
- Set<ObjectName> innerChildRbeOns = findChildren(objectName, childRbeOns);
- String runtimeInstanceIndex = objectName.getKeyProperty(childMappingEntry.getKey());
-
- String elementName = jmxToYangChildRbeMapping.get(childMappingEntry.getKey());
-
- Element innerXml = XmlUtil.createElement(document, elementName, Optional.of(namespace));
- childMappingEntry.getValue().toXml(objectName, innerChildRbeOns, document, runtimeInstanceIndex,
- innerXml, namespace, enumResolver);
- xml.appendChild(innerXml);
- }
- }
- return xml;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.runtime;
-
-import com.google.common.collect.Sets;
-import java.util.Collection;
-import java.util.Set;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleConfig;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class ModuleRuntime {
-
- private final InstanceRuntime instanceRuntime;
-
- public ModuleRuntime(InstanceRuntime instanceRuntime) {
- this.instanceRuntime = instanceRuntime;
- }
-
- private ObjectName findRoot(Collection<ObjectName> runtimeBeanOns) {
- for (ObjectName objectName : runtimeBeanOns) {
- if (objectName.getKeyPropertyList().size() == 3) {
- return objectName;
- }
- }
- throw new IllegalStateException("Root runtime bean not found among " + runtimeBeanOns);
- }
-
- public Element toXml(String namespace, Collection<ObjectName> runtimeBeanOns, Document document,
- ModuleConfig moduleConfig, ObjectName configBeanON, final EnumResolver enumResolver) {
-
- Element moduleElement = moduleConfig.toXml(configBeanON, document, namespace, enumResolver);
-
- ObjectName rootName = findRoot(runtimeBeanOns);
-
- Set<ObjectName> childrenRuntimeBeans = Sets.newHashSet(runtimeBeanOns);
- childrenRuntimeBeans.remove(rootName);
-
- // FIXME: why is this called and not used?
- instanceRuntime.toXml(rootName, childrenRuntimeBeans, document, moduleElement, namespace, enumResolver);
-
- return moduleElement;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.runtime;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Multimap;
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleConfig;
-import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
-import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class Runtime {
-
- private final Map<String, Map<String, ModuleRuntime>> moduleRuntimes;
- private final Map<String, Map<String, ModuleConfig>> moduleConfigs;
-
- public Runtime(Map<String, Map<String, ModuleRuntime>> moduleRuntimes,
- Map<String, Map<String, ModuleConfig>> moduleConfigs) {
- this.moduleRuntimes = moduleRuntimes;
- this.moduleConfigs = moduleConfigs;
- }
-
- private Map<String, Multimap<String, ObjectName>> mapInstancesToModules(Set<ObjectName> instancesToMap) {
- Map<String, Multimap<String, ObjectName>> retVal = Maps.newHashMap();
-
- // TODO map to namepsace, prevent module name conflicts
- // this code does not support same module names from different namespaces
- // Namespace should be present in ObjectName
-
- for (ObjectName objectName : instancesToMap) {
- String moduleName = ObjectNameUtil.getFactoryName(objectName);
-
- Multimap<String, ObjectName> multimap = retVal.computeIfAbsent(moduleName, k -> HashMultimap.create());
-
- String instanceName = ObjectNameUtil.getInstanceName(objectName);
-
- multimap.put(instanceName, objectName);
- }
- return retVal;
- }
-
- public Element toXml(Set<ObjectName> instancesToMap, Set<ObjectName> configBeans, Document document,
- final EnumResolver enumResolver) {
- Element root = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.<String>absent());
-
- Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY,
- Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
- root.appendChild(modulesElement);
-
- Map<String, Multimap<String, ObjectName>> moduleToRuntimeInstance = mapInstancesToModules(instancesToMap);
- Map<String, Map<String, Collection<ObjectName>>> moduleToConfigInstance = Config.getMappedInstances(configBeans,
- moduleConfigs);
-
- for (String localNamespace : moduleConfigs.keySet()) {
-
- Map<String, Collection<ObjectName>> instanceToMbe = moduleToConfigInstance.get(localNamespace);
-
- for (String moduleName : moduleConfigs.get(localNamespace).keySet()) {
- Multimap<String, ObjectName> instanceToRbe = moduleToRuntimeInstance.get(moduleName);
-
- for (ObjectName instanceON : instanceToMbe.get(moduleName)) {
- String instanceName = ObjectNameUtil.getInstanceName(instanceON);
-
- Element runtimeXml;
- ModuleConfig moduleConfig = moduleConfigs.get(localNamespace).get(moduleName);
- if (instanceToRbe == null || !instanceToRbe.containsKey(instanceName)) {
- runtimeXml = moduleConfig.toXml(instanceON, document, localNamespace, enumResolver);
- } else {
- ModuleRuntime moduleRuntime = moduleRuntimes.get(localNamespace).get(moduleName);
- runtimeXml = moduleRuntime.toXml(localNamespace, instanceToRbe.get(instanceName), document,
- moduleConfig, instanceON, enumResolver);
- }
- modulesElement.appendChild(runtimeXml);
- }
-
- }
- }
- return root;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.strategy;
-
-import java.util.Map;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class AbstractEditConfigStrategy implements EditConfigStrategy {
-
- private static final Logger LOG = LoggerFactory.getLogger(AbstractEditConfigStrategy.class);
-
- @Override
- public void executeConfiguration(String module, String instance, Map<String, AttributeConfigElement> configuration,
- ConfigTransactionClient ta, ServiceRegistryWrapper services) throws
- ConfigHandlingException {
-
- try {
- ObjectName on = ta.lookupConfigBean(module, instance);
- LOG.debug("ServiceInstance for {} {} located successfully under {}", module, instance, on);
- executeStrategy(configuration, ta, on, services);
- } catch (InstanceNotFoundException e) {
- handleMissingInstance(configuration, ta, module, instance, services);
- }
-
- }
-
- // TODO split missing instances handling strategies from edit config strategies in this hierarchy = REFACTOR
- // edit configs should not handle missing
-
- abstract void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws
- ConfigHandlingException;
-
- abstract void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- ObjectName objectName, ServiceRegistryWrapper services) throws
- ConfigHandlingException;
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.strategy;
-
-import java.util.Map;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class DeleteEditConfigStrategy extends AbstractEditConfigStrategy {
-
- private static final Logger LOG = LoggerFactory.getLogger(DeleteEditConfigStrategy.class);
-
- @Override
- void handleMissingInstance(final Map<String, AttributeConfigElement> configuration,
- final ConfigTransactionClient ta, final String module, final String instance,
- final ServiceRegistryWrapper services)
- throws ConfigHandlingException {
- throw new ConfigHandlingException(
- String.format("Unable to delete %s : %s , ServiceInstance not found", module, instance),
- DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
-
- @Override
- void executeStrategy(final Map<String, AttributeConfigElement> configuration, final ConfigTransactionClient ta,
- final ObjectName on, final ServiceRegistryWrapper services) throws ConfigHandlingException {
- try {
- ta.destroyModule(on);
- LOG.debug("ServiceInstance {} deleted successfully", on);
- } catch (InstanceNotFoundException e) {
- throw new ConfigHandlingException(
- String.format("Unable to delete %s because of exception %s" + on, e.getMessage()), e,
- DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.strategy;
-
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-
-public interface EditConfigStrategy {
-
- void executeConfiguration(String module, String instance, Map<String, AttributeConfigElement> configuration,
- ConfigTransactionClient ta, ServiceRegistryWrapper services) throws
- ConfigHandlingException;
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.strategy;
-
-import java.util.EnumSet;
-import java.util.Set;
-import org.opendaylight.controller.config.facade.xml.exception.OperationNotPermittedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-
-public enum EditStrategyType {
- // can be default
- merge, replace, none,
- // additional per element
- delete, remove, recreate;
-
- private static final Set<EditStrategyType> DEFAULT_STRATS = EnumSet.of(merge, replace, none);
-
- public static EditStrategyType getDefaultStrategy() {
- return merge;
- }
-
- public boolean isEnforcing() {
- switch (this) {
- case merge:
- case none:
- case remove:
- case delete:
- case recreate:
- return false;
- case replace:
- return true;
-
- default:
- throw new IllegalStateException(
- "Default edit strategy can be only of value " + DEFAULT_STRATS + " but was " + this);
- }
- }
-
- public static void compareParsedStrategyToDefaultEnforcing(EditStrategyType parsedStrategy,
- EditStrategyType defaultStrategy) throws OperationNotPermittedException {
- if (defaultStrategy.isEnforcing()) {
- if (parsedStrategy != defaultStrategy) {
- throw new OperationNotPermittedException("With " + defaultStrategy
- + " as default-operation operations on module elements are not permitted since the default "
- + "option is restrictive",
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
- }
-
- public EditConfigStrategy getFittingStrategy() {
- switch (this) {
- case merge:
- return new MergeEditConfigStrategy();
- case replace:
- return new ReplaceEditConfigStrategy();
- case delete:
- return new DeleteEditConfigStrategy();
- case remove:
- return new RemoveEditConfigStrategy();
- case recreate:
- return new ReCreateEditConfigStrategy();
- case none:
- return new NoneEditConfigStrategy();
- default:
- throw new UnsupportedOperationException("Unimplemented edit config strategy" + this);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.strategy;
-
-import static java.util.Arrays.asList;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import javax.management.Attribute;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MergeEditConfigStrategy extends AbstractEditConfigStrategy {
-
- private static final Logger LOG = LoggerFactory.getLogger(MergeEditConfigStrategy.class);
-
- public MergeEditConfigStrategy() {
- }
-
- @Override
- void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws ConfigHandlingException {
- throw new ConfigHandlingException(String.format(
- "Unable to handle missing instance, no missing instances should "
- + "appear at this point, missing: %s : %s ",
- module, instance), DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorSeverity.ERROR);
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on,
- ServiceRegistryWrapper services) throws ConfigHandlingException {
-
- for (Entry<String, AttributeConfigElement> configAttributeEntry : configuration.entrySet()) {
- try {
- AttributeConfigElement ace = configAttributeEntry.getValue();
-
- if (!ace.getResolvedValue().isPresent()) {
- LOG.debug("Skipping attribute {} for {}", configAttributeEntry.getKey(), on);
- continue;
- }
-
- Object toBeMergedIn = ace.getResolvedValue().get();
- // Get the existing values so we can merge the new values with them.
- Attribute currentAttribute = ta.getAttribute(on, ace.getJmxName());
- Object oldValue = currentAttribute != null ? currentAttribute.getValue() : null;
- // Merge value with currentValue
- toBeMergedIn = merge(oldValue, toBeMergedIn);
- ta.setAttribute(on, ace.getJmxName(), new Attribute(ace.getJmxName(), toBeMergedIn));
- LOG.debug("Attribute {} set to {} for {}", configAttributeEntry.getKey(), toBeMergedIn, on);
- } catch (RuntimeException e) {
- LOG.error("Error while merging object names of {}", on, e);
- throw new ConfigHandlingException(String.format("Unable to set attributes for %s, "
- + "Error with attribute %s : %s ",
- on,
- configAttributeEntry.getKey(),
- configAttributeEntry.getValue()), e,
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
- }
-
- /**
- * Merge value into current value Currently, this is only implemented for arrays
- * of ObjectNames, but that is the most common case for which it is needed.
- */
- protected Object merge(Object oldValue, Object toBeMergedIn) {
- if (oldValue instanceof ObjectName[] && toBeMergedIn instanceof ObjectName[]) {
- toBeMergedIn = mergeObjectNameArrays((ObjectName[]) oldValue, (ObjectName[]) toBeMergedIn);
- }
- return toBeMergedIn;
- }
-
- /**
- * Merge value into current values This implements for arrays of ObjectNames,
- * but that is the most common case for which it is needed.
- *
- * @param oldValue
- * - the new values to be merged into existing values
- * @param toBeMergedIn
- * - the existing values
- *
- * @return an ObjectName[] consisting the elements of currentValue with an
- * elements from values not already present in currentValue added
- *
- */
- protected ObjectName[] mergeObjectNameArrays(ObjectName[] oldValue, ObjectName[] toBeMergedIn) {
- List<ObjectName> newValueList = new ArrayList<>();
- newValueList.addAll(asList(oldValue));
- /*
- * It is guaranteed that old values do not contain transaction name. Since
- * toBeMergedIn is filled using service references translated by
- * ServiceRegistryWrapper, it is also guaranteed that this list will not contain
- * transaction names. Run through the list of values to be merged. If we don't
- * have them already, add them to the list.
- */
- for (ObjectName objName : toBeMergedIn) {
- if (!newValueList.contains(objName)) {
- newValueList.add(objName);
- }
- }
- return newValueList.toArray(new ObjectName[newValueList.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.config.facade.xml.strategy;
-
-import java.util.Map;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MissingInstanceHandlingStrategy extends AbstractEditConfigStrategy {
-
- private static final Logger LOG = LoggerFactory.getLogger(MissingInstanceHandlingStrategy.class);
-
- @Override
- void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws ConfigHandlingException {
- try {
- ObjectName on = ta.createModule(module, instance);
- LOG.trace("New instance for {} {} created under name {}", module, instance, on);
- } catch (InstanceAlreadyExistsException e1) {
- throw new ConfigHandlingException(String.format("Unable to create instance for %s : %s.", module, instance),
- e1, DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
-
- @Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- ObjectName objectName, ServiceRegistryWrapper services) {
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.strategy;
-
-import java.util.Collections;
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NoneEditConfigStrategy implements EditConfigStrategy {
-
- private static final Logger LOG = LoggerFactory.getLogger(NoneEditConfigStrategy.class);
-
- @Override
- public void executeConfiguration(String module, String instance, Map<String, AttributeConfigElement> configuration,
- ConfigTransactionClient ta, ServiceRegistryWrapper services) throws ConfigHandlingException {
- if (configuration != null && !configuration.isEmpty()) {
- for (Map.Entry<String, AttributeConfigElement> attrEntry : configuration.entrySet()) {
- if (attrEntry.getValue().getEditStrategy().isPresent()) {
- final Map<String, AttributeConfigElement> partialConfig = Collections
- .singletonMap(attrEntry.getKey(), attrEntry.getValue());
- attrEntry.getValue().getEditStrategy().get().getFittingStrategy().executeConfiguration(module,
- instance, partialConfig, ta, services);
- } else {
- LOG.debug("Skipping configuration element for {}:{}:{}", module, instance, attrEntry.getKey());
- }
- }
- } else {
- LOG.debug("Skipping configuration element for {}:{}", module, instance);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016, 2017 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.facade.xml.strategy;
-
-import java.util.Map;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-
-/**
- * Edit strategy that forces re-creation of a module instance even if the config
- * didn't change.
- *
- * @author Thomas Pantelis
- */
-public class ReCreateEditConfigStrategy extends AbstractEditConfigStrategy {
-
- @Override
- void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws ConfigHandlingException {
- throw new ConfigHandlingException(
- String.format("Unable to recreate %s : %s, Existing module instance not found", module, instance),
- DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
-
- @Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- ObjectName objectName, ServiceRegistryWrapper services) throws ConfigHandlingException {
- try {
- ta.reCreateModule(objectName);
- } catch (InstanceNotFoundException e) {
- throw new ConfigHandlingException(String.format("Unable to recreate instance for %s", objectName),
- e, DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.strategy;
-
-import java.util.Map;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class RemoveEditConfigStrategy extends DeleteEditConfigStrategy {
-
- private static final Logger LOG = LoggerFactory.getLogger(RemoveEditConfigStrategy.class);
-
- @Override
- void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) {
- LOG.warn("Unable to delete {}:{}, ServiceInstance not found", module, instance);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.strategy;
-
-import java.util.Map;
-import java.util.Map.Entry;
-import javax.management.Attribute;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
-import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ReplaceEditConfigStrategy extends AbstractEditConfigStrategy {
-
- private static final Logger LOG = LoggerFactory.getLogger(ReplaceEditConfigStrategy.class);
-
- @Override
- void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws ConfigHandlingException {
- throw new ConfigHandlingException(String.format(
- "Unable to handle missing instance, no missing instances should appear"
- + " at this point, missing: %s : %s ",
- module, instance), DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorSeverity.ERROR);
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on,
- ServiceRegistryWrapper services) throws ConfigHandlingException {
- for (Entry<String, AttributeConfigElement> configAttributeEntry : configuration.entrySet()) {
- try {
- AttributeConfigElement ace = configAttributeEntry.getValue();
-
- if (!ace.getResolvedValue().isPresent()) {
- Object value = ace.getResolvedDefaultValue();
- ta.setAttribute(on, ace.getJmxName(), new Attribute(ace.getJmxName(), value));
- LOG.debug("Attribute {} set to default value {} for {}", configAttributeEntry.getKey(), value, on);
- } else {
- Object value = ace.getResolvedValue().get();
- ta.setAttribute(on, ace.getJmxName(), new Attribute(ace.getJmxName(), value));
- LOG.debug("Attribute {} set to value {} for {}", configAttributeEntry.getKey(), value, on);
- }
- } catch (RuntimeException e) {
- throw new IllegalStateException("Unable to set attributes for " + on + ", Error with attribute "
- + configAttributeEntry.getKey() + ":" + configAttributeEntry.getValue(), e);
- }
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.transactions;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class TransactionProvider implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(TransactionProvider.class);
-
- private final ConfigRegistryClient configRegistryClient;
-
- private final String sessionIdForReporting;
- private ObjectName candidateTx;
- private ObjectName readTx;
- private final List<ObjectName> allOpenedTransactions = new ArrayList<>();
- private static final String NO_TRANSACTION_FOUND_FOR_SESSION = "No transaction found for session ";
-
- public TransactionProvider(final ConfigRegistryClient configRegistryClient, final String sessionIdForReporting) {
- this.configRegistryClient = configRegistryClient;
- this.sessionIdForReporting = sessionIdForReporting;
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- public synchronized void close() {
- for (ObjectName tx : allOpenedTransactions) {
- try {
- if (isStillOpenTransaction(tx)) {
- configRegistryClient.getConfigTransactionClient(tx).abortConfig();
- }
- } catch (final RuntimeException e) {
- LOG.debug("Ignoring exception while closing transaction {}", tx, e);
- }
- }
- allOpenedTransactions.clear();
- }
-
- public synchronized Optional<ObjectName> getTransaction() {
-
- if (candidateTx == null) {
- return Optional.absent();
- }
-
- // Transaction was already closed somehow
- if (!isStillOpenTransaction(candidateTx)) {
- LOG.warn("Fixing illegal state: transaction {} was closed in {}", candidateTx, sessionIdForReporting);
- candidateTx = null;
- return Optional.absent();
- }
- return Optional.of(candidateTx);
- }
-
- public synchronized Optional<ObjectName> getReadTransaction() {
-
- if (readTx == null) {
- return Optional.absent();
- }
-
- // Transaction was already closed somehow
- if (!isStillOpenTransaction(readTx)) {
- LOG.warn("Fixing illegal state: transaction {} was closed in {}", readTx, sessionIdForReporting);
- readTx = null;
- return Optional.absent();
- }
- return Optional.of(readTx);
- }
-
- private boolean isStillOpenTransaction(final ObjectName transaction) {
- return configRegistryClient.getOpenConfigs().contains(transaction);
- }
-
- public synchronized ObjectName getOrCreateTransaction() {
- Optional<ObjectName> ta = getTransaction();
-
- if (ta.isPresent()) {
- return ta.get();
- }
- candidateTx = configRegistryClient.beginConfig();
- allOpenedTransactions.add(candidateTx);
- return candidateTx;
- }
-
- public synchronized ObjectName getOrCreateReadTransaction() {
- Optional<ObjectName> ta = getReadTransaction();
-
- if (ta.isPresent()) {
- return ta.get();
- }
- readTx = configRegistryClient.beginConfig();
- allOpenedTransactions.add(readTx);
- return readTx;
- }
-
- /**
- * Used for editConfig test option.
- */
- public synchronized ObjectName getTestTransaction() {
- ObjectName testTx = configRegistryClient.beginConfig();
- allOpenedTransactions.add(testTx);
- return testTx;
- }
-
- /**
- * Commit and notification send must be atomic.
- */
- public CommitStatus commitTransaction() throws ValidationException, ConflictingVersionException {
- return commitTransaction(configRegistryClient);
- }
-
- /**
- * Commit and notification send must be atomic.
- */
- public synchronized CommitStatus commitTransaction(final ConfigRegistryClient client)
- throws ValidationException, ConflictingVersionException {
- if (!getTransaction().isPresent()) {
- // making empty commit without prior opened transaction, just return commit
- // status with empty lists
- LOG.debug("Making commit without open candidate transaction for session {}", sessionIdForReporting);
- return new CommitStatus(Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
- }
- final Optional<ObjectName> maybeTaON = getTransaction();
- ObjectName taON = maybeTaON.get();
- try {
- CommitStatus status = client.commitConfig(taON);
- // clean up
- allOpenedTransactions.remove(candidateTx);
- candidateTx = null;
- return status;
- } catch (final ValidationException validationException) {
- // no clean up: user can reconfigure and recover this transaction
- LOG.warn("Transaction {} failed on {}", taON, validationException.toString());
- throw validationException;
- } catch (final ConflictingVersionException e) {
- LOG.debug("Exception while commit of {}, aborting transaction", taON, e);
- // clean up
- abortTransaction();
- throw e;
- }
- }
-
- public synchronized void abortTransaction() {
- LOG.debug("Aborting current transaction");
- Optional<ObjectName> taON = getTransaction();
- Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + sessionIdForReporting);
-
- ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON.get());
- transactionClient.abortConfig();
- allOpenedTransactions.remove(candidateTx);
- candidateTx = null;
- }
-
- public synchronized void closeReadTransaction() {
- LOG.debug("Closing read transaction");
- Optional<ObjectName> taON = getReadTransaction();
- Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + sessionIdForReporting);
-
- ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON.get());
- transactionClient.abortConfig();
- allOpenedTransactions.remove(readTx);
- readTx = null;
- }
-
- public synchronized void abortTestTransaction(final ObjectName testTx) {
- LOG.debug("Aborting transaction {}", testTx);
- ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(testTx);
- allOpenedTransactions.remove(testTx);
- transactionClient.abortConfig();
- }
-
- public void validateTransaction() throws ValidationException {
- Optional<ObjectName> taON = getTransaction();
- Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + sessionIdForReporting);
-
- ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON.get());
- transactionClient.validateConfig();
- }
-
- public void validateTestTransaction(final ObjectName taON) throws ValidationException {
- ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON);
- transactionClient.validateConfig();
- }
-
- public void wipeTestTransaction(final ObjectName taON) {
- wipeInternal(taON, true);
- }
-
- /**
- * Wiping means removing all module instances keeping the transaction open +
- * service references.
- */
- synchronized void wipeInternal(final ObjectName taON, final boolean isTest) {
- ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON);
-
- Set<ObjectName> lookupConfigBeans = transactionClient.lookupConfigBeans();
- int index = lookupConfigBeans.size();
- for (ObjectName instance : lookupConfigBeans) {
- try {
- transactionClient.destroyModule(instance);
- } catch (final InstanceNotFoundException e) {
- if (isTest) {
- LOG.debug("Unable to clean configuration in transactiom {}", taON, e);
- } else {
- LOG.warn("Unable to clean configuration in transactiom {}", taON, e);
- }
-
- throw new IllegalStateException("Unable to clean configuration in transactiom " + taON, e);
- }
- }
- LOG.debug("Transaction {} wiped clean of {} config beans", taON, index);
-
- transactionClient.removeAllServiceReferences();
- LOG.debug("Transaction {} wiped clean of all service references", taON);
- }
-
- public void wipeTransaction() {
- Optional<ObjectName> taON = getTransaction();
- Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + sessionIdForReporting);
- wipeInternal(taON.get(), false);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.util;
-
-import com.google.common.base.Preconditions;
-
-public final class Util {
-
- private Util() {
- }
-
- public static void checkType(final Object value, final Class<?> clazz) {
- Preconditions.checkArgument(clazz.isAssignableFrom(value.getClass()),
- "Unexpected type " + value.getClass() + " should be " + clazz + " of " + value);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
-
-import static org.junit.Assert.assertEquals;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Maps;
-import java.net.URI;
-import java.util.Collections;
-import java.util.Map;
-import org.junit.Test;
-import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.Revision;
-
-public class SimpleIdentityRefAttributeReadingStrategyTest {
-
- @Test
- public void testReadIdRef() throws Exception {
- final Map<String, Map<Optional<Revision>, IdentityMapping>> identityMapping = Maps.newHashMap();
- final IdentityMapping value = new IdentityMapping();
- final Optional<Revision> rev = Optional.of(Revision.of("2017-10-10"));
- identityMapping.put("namespace", Collections.singletonMap(rev, value));
- identityMapping.put("inner", Collections.singletonMap(rev, value));
- final SimpleIdentityRefAttributeReadingStrategy key = new SimpleIdentityRefAttributeReadingStrategy(null, "key",
- identityMapping);
-
- String read = key.readElementContent(XmlElement.fromString("<el xmlns=\"namespace\">local</el>"));
- assertEquals(QName.create(URI.create("namespace"), rev.toJavaUtil(), "local").toString(), read);
-
- read = key.readElementContent(XmlElement.fromString("<el xmlns:a=\"inner\" xmlns=\"namespace\">a:local</el>"));
- assertEquals(QName.create(URI.create("inner"), rev.toJavaUtil(), "local").toString(), read);
-
- read = key.readElementContent(
- XmlElement.fromString("<top xmlns=\"namespace\"><el>local</el></top>").getOnlyChildElement());
- assertEquals(QName.create(URI.create("namespace"), rev.toJavaUtil(), "local").toString(), read);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.facade.xml.rpc;
-
-import static org.junit.Assert.assertEquals;
-
-import com.google.common.collect.ImmutableMap;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
-@RunWith(Parameterized.class)
-public class RuntimeRpcElementResolvedTest {
-
- private static final String MODULE_TYPE = "moduleType";
- private static final String INSTANCE_NAME = "instanceName";
- @Parameterized.Parameter(0)
- public String xpath;
- @Parameterized.Parameter(1)
- public Map<String, String> additional;
-
- @Parameterized.Parameters(name = "{index}: parsed({0}) contains moduleName:{1} and instanceName:{2}")
- @SuppressWarnings("linelength")
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][] {
- // With namespaces
- { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']/b:listener-state[b:peer-id='127.0.0.1']",
- new HashMap<>(ImmutableMap.of("listener-state", "127.0.0.1")) },
- { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']", null },
-
- // Without namespaces
- { "/modules/module[name=instanceName][type=moduleType]", null },
- { "/modules/module[type=moduleType][name='instanceName']", null },
- { "/modules/module[name=\'instanceName\'][type=\"moduleType\"]", null },
- { "/modules/module[type=moduleType and name=instanceName]", null },
- { "/modules/module[name=\"instanceName\" and type=moduleType]", null },
- { "/modules/module[type=\"moduleType\" and name=instanceName]", null },
- { "/modules/module[name=\'instanceName\' and type=\"moduleType\"]", null },
-
- // With inner beans
- { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key=b]",
- Collections.singletonMap("inner", "b") },
- { "/modules/module[name=instanceName and type=moduleType]/inner[key=b]",
- Collections.singletonMap("inner", "b") },
- { "/modules/module[name=instanceName and type=moduleType]/inner[key=\'b\']",
- Collections.singletonMap("inner", "b") },
- { "/modules/module[name=instanceName and type=moduleType]/inner[key=\"b\"]",
- Collections.singletonMap("inner", "b") },
-
- { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key2=a]/inner2[key=b]",
- new HashMap<>(ImmutableMap.of("inner", "a", "inner2", "b")) }, });
- }
-
- @Test
- public void testFromXpath() throws Exception {
- final RuntimeRpcElementResolved resolved = RuntimeRpcElementResolved.fromXpath(xpath, "element", "namespace");
- assertEquals(MODULE_TYPE, resolved.getModuleName());
- assertEquals(INSTANCE_NAME, resolved.getInstanceName());
- if (additional != null) {
- assertEquals(additional, resolved.getAdditionalAttributes());
- }
- }
-}
+++ /dev/null
-<?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>config-subsystem</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>config-manager</artifactId>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
-
- <dependencies>
- <!-- compile dependencies -->
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-api</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
-
- <!--Dependencies regarding RuntimeGeneratedMappingService-->
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-binding-generator-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>concepts</artifactId>
- </dependency>
-
- <!-- test dependencies -->
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <!--End-->
-
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-util</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-util</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-Activator>org.opendaylight.controller.config.manager.impl.osgi.ConfigManagerActivator</Bundle-Activator>
- <Private-Package>org.opendaylight.controller.config.manager.*</Private-Package>
- <Export-Package></Export-Package>
- </instructions>
- </configuration>
- </plugin>
- <!-- test jar -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- <phase>package</phase>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
-
-/**
- * Interface exposing some internal state on top of ServiceReferenceReadableRegistry. This will
- * not be exposed via JMX.
- */
-public interface CloseableServiceReferenceReadableRegistry extends AutoCloseable, ServiceReferenceReadableRegistry {
-
- @Override
- void close();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import javax.annotation.concurrent.Immutable;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.manager.impl.dependencyresolver.DestroyedModule;
-import org.opendaylight.controller.config.manager.impl.dependencyresolver.ModuleInternalTransactionalInfo;
-
-/**
- * Structure obtained during first phase commit, contains destroyed modules from
- * previous transactions that need to be closed and all committed modules with
- * meta data.
- */
-@Immutable
-public class CommitInfo {
- private final List<DestroyedModule> destroyedFromPreviousTransactions;
- private final Map<ModuleIdentifier, ModuleInternalTransactionalInfo> commitMap;
-
- public CommitInfo(final List<DestroyedModule> destroyedFromPreviousTransactions,
- final Map<ModuleIdentifier, ModuleInternalTransactionalInfo> commitMap) {
- this.destroyedFromPreviousTransactions = Collections.unmodifiableList(destroyedFromPreviousTransactions);
- this.commitMap = Collections.unmodifiableMap(commitMap);
- }
-
- /**
- * Get ordered list of modules that can be closed in the same order, i.e. first
- * element will be a leaf on which no other module depends, n-th element can
- * only have dependencies with index smaller than n.
- *
- * @return list of destroyed modules
- */
- public List<DestroyedModule> getDestroyedFromPreviousTransactions() {
- return destroyedFromPreviousTransactions;
- }
-
- public Map<ModuleIdentifier, ModuleInternalTransactionalInfo> getCommitted() {
- return commitMap;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import com.google.common.collect.Maps;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-import javax.annotation.concurrent.GuardedBy;
-import javax.annotation.concurrent.ThreadSafe;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.RuntimeBeanRegistratorAwareModule;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.ConfigTransactionLookupRegistry.TransactionJMXRegistratorFactory;
-import org.opendaylight.controller.config.manager.impl.dependencyresolver.DestroyedModule;
-import org.opendaylight.controller.config.manager.impl.dependencyresolver.ModuleInternalTransactionalInfo;
-import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HierarchicalConfigMBeanFactoriesHolder;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.ModuleJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
-import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager;
-import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager.OsgiRegistration;
-import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
-import org.opendaylight.controller.config.manager.impl.util.LookupBeansUtil;
-import org.opendaylight.controller.config.manager.impl.util.ModuleQNameUtil;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Singleton that is responsible for creating and committing Config
- * Transactions. It is registered in Platform MBean Server.
- */
-@ThreadSafe
-public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBean {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigRegistryImpl.class);
- private static final ObjectName NOOP_TX_NAME = ObjectNameUtil.createTransactionControllerON("noop");
-
- private final ModuleFactoriesResolver resolver;
- private final MBeanServer configMBeanServer;
- private final BindingContextProvider bindingContextProvider;
-
- private volatile long version = 0;
- private volatile long versionCounter = 0;
-
- /**
- * Contains current configuration in form of {moduleName:{instanceName,read only
- * module}} for copying state to new transaction. Each running module is present
- * just once, no matter how many interfaces it exposes.
- */
- private final ConfigHolder currentConfig = new ConfigHolder();
-
- /**
- * Will return true unless there was a transaction that succeeded during
- * validation but failed in second phase of commit. In this case the server is
- * unstable and its state is undefined.
- */
- private volatile boolean isHealthy = true;
-
- /**
- * Holds the map of transactions and purges it each time its content is
- * requested.
- */
- private final TransactionsHolder transactionsHolder = new TransactionsHolder();
-
- private final BaseJMXRegistrator baseJMXRegistrator;
-
- private final BeanToOsgiServiceManager beanToOsgiServiceManager;
-
- // internal jmx server for read only beans
- private final MBeanServer registryMBeanServer;
- // internal jmx server shared by all transactions
- private final MBeanServer transactionsMBeanServer;
-
- private final AtomicBoolean closed = new AtomicBoolean();
-
- private final Object readableSRRegistryLock = new Object();
-
- private final Lock configTransactionLock = new ReentrantLock();
-
- // Used for finding new factory instances for default module functionality
- @GuardedBy("configTransactionLock")
- private List<ModuleFactory> lastListOfFactories = Collections.emptyList();
-
- // switched in every 2ndPC
- @GuardedBy("readableSRRegistryLock")
- private CloseableServiceReferenceReadableRegistry readableSRRegistry = ServiceReferenceRegistryImpl
- .createInitialSRLookupRegistry();
-
- // constructor
- public ConfigRegistryImpl(final ModuleFactoriesResolver resolver, final MBeanServer configMBeanServer,
- final BindingContextProvider bindingContextProvider) {
- this(resolver, configMBeanServer, new BaseJMXRegistrator(configMBeanServer), bindingContextProvider);
- }
-
- // constructor
- public ConfigRegistryImpl(final ModuleFactoriesResolver resolver, final MBeanServer configMBeanServer,
- final BaseJMXRegistrator baseJMXRegistrator, final BindingContextProvider bindingContextProvider) {
- this.resolver = resolver;
- this.beanToOsgiServiceManager = new BeanToOsgiServiceManager();
- this.configMBeanServer = configMBeanServer;
- this.baseJMXRegistrator = baseJMXRegistrator;
- this.bindingContextProvider = bindingContextProvider;
- this.registryMBeanServer = MBeanServerFactory
- .createMBeanServer("ConfigRegistry" + configMBeanServer.getDefaultDomain());
- this.transactionsMBeanServer = MBeanServerFactory
- .createMBeanServer("ConfigTransactions" + configMBeanServer.getDefaultDomain());
- }
-
- /**
- * Create new {@link ConfigTransactionControllerImpl }.
- */
- @Override
- public ObjectName beginConfig() {
- return beginConfig(false);
- }
-
- /**
- * It returns true if this transaction is created automatically by
- * org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker.
- *
- * @param blankTransaction
- * true if this transaction is created automatically by
- * org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker
- *
- * @return object name
- */
- public ObjectName beginConfig(final boolean blankTransaction) {
- // If we're closed or in the process of closing then all modules are destroyed
- // or being destroyed
- // so there's no point in trying to acquire the lock and beginning an actual
- // transaction. Also we want
- // to avoid trying to lock as it may block the shutdown process if there is an
- // outstanding transaction
- // attempting to be committed.
- //
- // We could throw an exception here to indicate this but that's not part of the
- // original API contract
- // and callers may not be expecting an unchecked exception. Therefore we return
- // a special transaction
- // handle that signifies a "no-op".
- if (closed.get()) {
- return NOOP_TX_NAME;
- }
-
- if (blankTransaction) {
- try {
- // For a "blank" transaction, we'll try to obtain the config lock but "blank"
- // transactions
- // are initiated via OSGi events so we don't want to block indefinitely or for a
- // long period
- // of time.
- if (!configTransactionLock.tryLock(5, TimeUnit.SECONDS)) {
- LOG.debug("Timed out trying to obtain configTransactionLock");
- return NOOP_TX_NAME;
- }
- } catch (final InterruptedException e) {
- LOG.debug("Interrupted trying to obtain configTransactionLock", e);
- Thread.currentThread().interrupt();
- return NOOP_TX_NAME;
- }
- } else {
- configTransactionLock.lock();
- }
-
- try {
- return beginConfigSafe(blankTransaction).getControllerObjectName();
- } finally {
- configTransactionLock.unlock();
- }
- }
-
- @GuardedBy("configTransactionLock")
- private ConfigTransactionControllerInternal beginConfigSafe(final boolean blankTransaction) {
- versionCounter++;
- final String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
-
- TransactionJMXRegistratorFactory factory = () -> baseJMXRegistrator
- .createTransactionJMXRegistrator(transactionName);
-
- Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = new HashMap<>(
- resolver.getAllFactories());
-
- // add all factories that disappeared from SR but are still committed
- for (ModuleInternalInfo moduleInternalInfo : currentConfig.getEntries()) {
- String name = moduleInternalInfo.getModuleFactory().getImplementationName();
- if (!allCurrentFactories.containsKey(name)) {
- LOG.trace("Factory {} not found in SR, using reference from previous commit", name);
- allCurrentFactories.put(name, Maps.immutableEntry(moduleInternalInfo.getModuleFactory(),
- moduleInternalInfo.getBundleContext()));
- }
- }
- allCurrentFactories = Collections.unmodifiableMap(allCurrentFactories);
-
- // closed by transaction controller
- ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(
- new TransactionIdentifier(transactionName), factory, allCurrentFactories);
- SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl
- .createSRWritableRegistry(readableSRRegistry, txLookupRegistry, allCurrentFactories);
-
- ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
- txLookupRegistry, version, bindingContextProvider, versionCounter, allCurrentFactories,
- transactionsMBeanServer, configMBeanServer, blankTransaction, writableRegistry);
- try {
- txLookupRegistry.registerMBean(transactionController, transactionController.getControllerObjectName());
- } catch (final InstanceAlreadyExistsException e) {
- throw new IllegalStateException(e);
- }
- transactionController.copyExistingModulesAndProcessFactoryDiff(currentConfig.getEntries(), lastListOfFactories);
- transactionsHolder.add(transactionName, transactionController, txLookupRegistry);
- return transactionController;
- }
-
- @Override
- public CommitStatus commitConfig(final ObjectName transactionControllerON)
- throws ValidationException, ConflictingVersionException {
- if (NOOP_TX_NAME.equals(transactionControllerON) || closed.get()) {
- return new CommitStatus(Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
- }
-
- configTransactionLock.lock();
- try {
- return commitConfigSafe(transactionControllerON);
- } finally {
- configTransactionLock.unlock();
- }
- }
-
- @GuardedBy("configTransactionLock")
- private CommitStatus commitConfigSafe(final ObjectName transactionControllerON)
- throws ConflictingVersionException, ValidationException {
- final String transactionName = ObjectNameUtil.getTransactionName(transactionControllerON);
- LOG.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version,
- versionCounter);
-
- // find ConfigTransactionController
- Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions =
- transactionsHolder.getCurrentTransactions();
- Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry =
- transactions.get(transactionName);
- if (configTransactionControllerEntry == null) {
- throw new IllegalArgumentException(String.format("Transaction with name '%s' not found", transactionName));
- }
- ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
- // check optimistic lock
- if (version != configTransactionController.getParentVersion()) {
- throw new ConflictingVersionException(
- String.format("Optimistic lock failed. Expected parent version %d, was %d", version,
- configTransactionController.getParentVersion()));
- }
- // optimistic lock ok
-
- CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
- lastListOfFactories = Collections
- .unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
- return secondPhaseCommit(configTransactionController, commitInfo, configTransactionControllerEntry.getValue());
- }
-
- @GuardedBy("configTransactionLock")
- private CommitStatus secondPhaseCommit(final ConfigTransactionControllerInternal configTransactionController,
- final CommitInfo commitInfo, final ConfigTransactionLookupRegistry txLookupRegistry) {
-
- // close instances which were destroyed by the user, including
- // (hopefully) runtime beans
- for (DestroyedModule toBeDestroyed : commitInfo.getDestroyedFromPreviousTransactions()) {
- // closes instance (which should close
- // runtime jmx registrator),
- // also closes osgi registration and ModuleJMXRegistrator
- // registration
- toBeDestroyed.close();
- currentConfig.remove(toBeDestroyed.getIdentifier());
- }
-
- // set RuntimeBeanRegistrators on beans implementing
- // RuntimeBeanRegistratorAwareModule
- Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
- for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted().values()) {
- // set runtime jmx registrator if required
- Module module = entry.getProxiedModule();
- RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = null;
-
- if (module instanceof RuntimeBeanRegistratorAwareModule) {
-
- if (entry.hasOldModule()) {
-
- if (module.canReuse(entry.getOldInternalInfo().getReadableModule().getModule())) {
- runtimeBeanRegistrator = entry.getOldInternalInfo().getRuntimeBeanRegistrator();
- ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
- } else {
- runtimeBeanRegistrator = baseJMXRegistrator.createRuntimeBeanRegistrator(entry.getIdentifier());
- entry.getOldInternalInfo().getRuntimeBeanRegistrator().close();
- ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
- }
- } else {
- runtimeBeanRegistrator = baseJMXRegistrator.createRuntimeBeanRegistrator(entry.getIdentifier());
- ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
- }
- }
- // save it to info so it is accessible afterwards
- if (runtimeBeanRegistrator != null) {
- runtimeRegistrators.put(entry.getIdentifier(), runtimeBeanRegistrator);
- }
- }
-
- // can register runtime beans
- List<ModuleIdentifier> orderedModuleIdentifiers = configTransactionController.secondPhaseCommit();
- txLookupRegistry.close();
- configTransactionController.close();
-
- // copy configuration to read only mode
- List<ObjectName> newInstances = new LinkedList<>();
- List<ObjectName> reusedInstances = new LinkedList<>();
- List<ObjectName> recreatedInstances = new LinkedList<>();
-
- Map<Module, ModuleInternalInfo> newConfigEntries = new HashMap<>();
-
- int orderingIdx = 0;
- for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
- LOG.trace("Registering {}", moduleIdentifier);
- ModuleInternalTransactionalInfo entry = commitInfo.getCommitted().get(moduleIdentifier);
- if (entry == null) {
- throw new NullPointerException("Module not found " + moduleIdentifier);
- }
-
- ObjectName primaryReadOnlyON = ObjectNameUtil.createReadOnlyModuleON(moduleIdentifier);
-
- // determine if current instance was recreated or reused or is new
-
- // rules for closing resources:
- // osgi registration - will be reused if possible.
- // module jmx registration - will be (re)created every time, needs
- // to be closed here
- // runtime jmx registration - should be taken care of by module
- // itself
- // instance - is closed only if it was destroyed
- ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator.createModuleJMXRegistrator();
-
- OsgiRegistration osgiRegistration = null;
- AutoCloseable instance = entry.getProxiedModule().getInstance();
- if (entry.hasOldModule()) {
- ModuleInternalInfo oldInternalInfo = entry.getOldInternalInfo();
- DynamicReadableWrapper oldReadableConfigBean = oldInternalInfo.getReadableModule();
- currentConfig.remove(entry.getIdentifier());
-
- // test if old instance == new instance
- if (oldReadableConfigBean.getInstance().equals(instance)) {
- // reused old instance:
- // wrap in readable dynamic mbean
- reusedInstances.add(primaryReadOnlyON);
- osgiRegistration = oldInternalInfo.getOsgiRegistration();
- } else {
- // recreated instance:
- // it is responsibility of module to call the old instance -
- // we just need to unregister configbean
- recreatedInstances.add(primaryReadOnlyON);
-
- // close old osgi registration
- oldInternalInfo.getOsgiRegistration().close();
- }
-
- // close old module jmx registrator
- oldInternalInfo.getModuleJMXRegistrator().close();
-
- // We no longer need old internal info. Clear it out, so we do not create a
- // serial leak evidenced
- // by BUG-4514. The reason is that modules retain their resolver, which retains
- // modules. If we retain
- // the old module, we would have the complete reconfiguration history held in
- // heap for no good reason.
- entry.clearOldInternalInfo();
- } else {
- // new instance:
- // wrap in readable dynamic mbean
- newInstances.add(primaryReadOnlyON);
- }
- Module realModule = entry.getRealModule();
-
- DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(realModule, instance,
- moduleIdentifier, registryMBeanServer, configMBeanServer);
-
- // register to JMX
- try {
- newModuleJMXRegistrator.registerMBean(newReadableConfigBean, primaryReadOnlyON);
- } catch (final InstanceAlreadyExistsException e) {
- throw new IllegalStateException("Possible code error, already registered:" + primaryReadOnlyON, e);
- }
-
- // register services to OSGi
- Map<ServiceInterfaceAnnotation, String> annotationMapping = configTransactionController
- .getWritableRegistry().findServiceInterfaces(moduleIdentifier);
- BundleContext bc = configTransactionController
- .getModuleFactoryBundleContext(entry.getModuleFactory().getImplementationName());
- if (osgiRegistration == null) {
- osgiRegistration = beanToOsgiServiceManager.registerToOsgi(newReadableConfigBean.getInstance(),
- moduleIdentifier, bc, annotationMapping);
- } else {
- osgiRegistration.updateRegistrations(annotationMapping, bc, instance);
- }
-
- RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators.get(entry.getIdentifier());
- ModuleInternalInfo newInfo = new ModuleInternalInfo(entry.getIdentifier(), newReadableConfigBean,
- osgiRegistration, runtimeBeanRegistrator, newModuleJMXRegistrator, orderingIdx,
- entry.isDefaultBean(), entry.getModuleFactory(), entry.getBundleContext());
-
- newConfigEntries.put(realModule, newInfo);
- orderingIdx++;
- }
- currentConfig.addAll(newConfigEntries.values());
-
- // update version
- version = configTransactionController.getVersion();
-
- // switch readable Service Reference Registry
- synchronized (readableSRRegistryLock) {
- readableSRRegistry.close();
- readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(
- configTransactionController.getWritableRegistry(), this, baseJMXRegistrator);
- }
-
- return new CommitStatus(newInstances, reusedInstances, recreatedInstances);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public List<ObjectName> getOpenConfigs() {
- Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions =
- transactionsHolder.getCurrentTransactions();
- List<ObjectName> result = new ArrayList<>(transactions.size());
- for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>
- configTransactionControllerEntry : transactions.values()) {
- result.add(configTransactionControllerEntry.getKey().getControllerObjectName());
- }
- return result;
- }
-
- /**
- * Abort open transactions and unregister read only modules. Since this class is
- * not responsible for registering itself under
- * {@link org.opendaylight.controller.config.api.ConfigRegistry#OBJECT_NAME}, it
- * will not unregister itself here.
- */
- @Override
- public void close() {
- if (!closed.compareAndSet(false, true)) {
- return;
- }
-
- // abort transactions
- Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions =
- transactionsHolder.getCurrentTransactions();
- for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>
- configTransactionControllerEntry : transactions.values()) {
- ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
- configTransactionControllerEntry.getValue().close();
- configTransactionController.abortConfig();
- }
-
- // destroy all live objects one after another in order of the dependency
- // hierarchy, from top to bottom
- List<DestroyedModule> destroyedModules = currentConfig.getModulesToBeDestroyed();
-
- LOG.info("ConfigRegistry closing - destroying {} modules", destroyedModules.size());
-
- for (DestroyedModule destroyedModule : destroyedModules) {
- destroyedModule.close();
- }
- // unregister MBeans that failed to unregister properly
- baseJMXRegistrator.close();
- // remove jmx servers
- MBeanServerFactory.releaseMBeanServer(registryMBeanServer);
- MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
-
- LOG.info("ConfigRegistry closed");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public long getVersion() {
- return version;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<String> getAvailableModuleNames() {
- return new HierarchicalConfigMBeanFactoriesHolder(resolver.getAllFactories()).getModuleNames();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean isHealthy() {
- return isHealthy;
- }
-
- // filtering methods
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupConfigBeans() {
- return lookupConfigBeans("*", "*");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName) {
- return lookupConfigBeans(moduleName, "*");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
- ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName, instanceName);
- return baseJMXRegistrator.queryNames(namePattern, null);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupRuntimeBeans() {
- return lookupRuntimeBeans("*", "*");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
- String finalModuleName = moduleName == null ? "*" : moduleName;
- String finalInstanceName = instanceName == null ? "*" : instanceName;
- ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(finalModuleName, finalInstanceName);
- return baseJMXRegistrator.queryNames(namePattern, null);
- }
-
- @Override
- public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
- ObjectNameUtil.checkDomain(objectName);
- ObjectNameUtil.checkType(objectName, ObjectNameUtil.TYPE_MODULE);
- String transactionName = ObjectNameUtil.getTransactionName(objectName);
- if (transactionName != null) {
- throw new IllegalArgumentException(
- "Transaction attribute not supported in registry, wrong ObjectName: " + objectName);
- }
- // make sure exactly one match is found:
- LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName),
- ObjectNameUtil.getInstanceName(objectName));
- }
-
- // service reference functionality:
- @Override
- public ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
- synchronized (readableSRRegistryLock) {
- return readableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
- }
- }
-
- @Override
- public Map<String, Map<String, ObjectName>> getServiceMapping() {
- synchronized (readableSRRegistryLock) {
- return readableSRRegistry.getServiceMapping();
- }
- }
-
- @Override
- public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
- synchronized (readableSRRegistryLock) {
- return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
- }
- }
-
- @Override
- public Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
- synchronized (readableSRRegistryLock) {
- return readableSRRegistry.lookupServiceInterfaceNames(objectName);
- }
- }
-
- @Override
- public String getServiceInterfaceName(final String namespace, final String localName) {
- synchronized (readableSRRegistryLock) {
- return readableSRRegistry.getServiceInterfaceName(namespace, localName);
- }
- }
-
- @Override
- public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
- synchronized (readableSRRegistryLock) {
- readableSRRegistry.checkServiceReferenceExists(objectName);
- }
- }
-
- @Override
- public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName)
- throws InstanceNotFoundException {
- synchronized (readableSRRegistryLock) {
- return readableSRRegistry.getServiceReference(serviceInterfaceQName, refName);
- }
- }
-
- @Override
- public Set<String> getAvailableModuleFactoryQNames() {
- return ModuleQNameUtil.getQNames(resolver.getAllFactories());
- }
-
- @Override
- public String toString() {
- return "ConfigRegistryImpl{" + "versionCounter=" + versionCounter + ", version=" + version + '}';
- }
-
- /**
- * Inner class holding transactions and purges it each time its content is
- * requested.
- */
- class TransactionsHolder {
- /**
- * This map keeps transaction names and
- * {@link ConfigTransactionControllerInternal} instances, because platform
- * MBeanServer transforms mbeans into another representation. Map is cleaned
- * every time current transactions are requested.
- */
- private final ConcurrentMap<String /* transactionName */,
- Entry<ConfigTransactionControllerInternal,
- ConfigTransactionLookupRegistry>> transactions = new ConcurrentHashMap<>();
-
- public void add(final String transactionName, final ConfigTransactionControllerInternal transactionController,
- final ConfigTransactionLookupRegistry txLookupRegistry) {
- Object oldValue = transactions.putIfAbsent(transactionName,
- Maps.immutableEntry(transactionController, txLookupRegistry));
- if (oldValue != null) {
- throw new IllegalStateException("Error: two transactions with same name");
- }
- }
-
- /**
- * Purges closed transactions from transactions map. Calling this method more
- * than once within the method can modify the resulting map that was obtained in
- * previous calls.
- *
- * @return current view on transactions map.
- */
- public Map<String, Entry<ConfigTransactionControllerInternal,
- ConfigTransactionLookupRegistry>> getCurrentTransactions() {
- // first, remove closed transaction
- for (Iterator<Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>>>
- it = transactions.entrySet().iterator(); it.hasNext();) {
- Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> entry = it
- .next();
- if (entry.getValue().getKey().isClosed()) {
- it.remove();
- }
- }
- return Collections.unmodifiableMap(transactions);
- }
- }
-
- /**
- * Inner class that holds currently running modules.
- */
- class ConfigHolder {
- private final ConcurrentMap<ModuleIdentifier, ModuleInternalInfo> currentConfig = new ConcurrentHashMap<>();
-
- /**
- * Add all modules to the internal map. Also add service instance to OSGi
- * Service Registry.
- */
- public void addAll(final Collection<ModuleInternalInfo> configInfos) {
- if (!currentConfig.isEmpty()) {
- throw new IllegalStateException("Error - some config entries were not removed: " + currentConfig);
- }
- for (ModuleInternalInfo configInfo : configInfos) {
- add(configInfo);
- }
- }
-
- private void add(final ModuleInternalInfo configInfo) {
- ModuleInternalInfo oldValue = currentConfig.putIfAbsent(configInfo.getIdentifier(), configInfo);
- if (oldValue != null) {
- throw new IllegalStateException(
- "Cannot overwrite module with same name:" + configInfo.getIdentifier() + ":" + configInfo);
- }
- }
-
- /**
- * Remove entry from current config.
- */
- public void remove(final ModuleIdentifier name) {
- ModuleInternalInfo removed = currentConfig.remove(name);
- if (removed == null) {
- throw new IllegalStateException("Cannot remove from ConfigHolder - name not found:" + name);
- }
- }
-
- public Collection<ModuleInternalInfo> getEntries() {
- return currentConfig.values();
- }
-
- public List<DestroyedModule> getModulesToBeDestroyed() {
- List<DestroyedModule> result = new ArrayList<>();
- for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
- result.add(moduleInternalInfo.toDestroyedModule());
- }
- Collections.sort(result);
- return result;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import org.opendaylight.controller.config.api.ConfigRegistry;
-
-/**
- * Exposes version of config registry.
- */
-public interface ConfigRegistryImplMXBean extends ConfigRegistry {
- /**
- * Get the version of last committed transaction that is now used as base
- * version. Transactions can only be committed if their parent
- * version matches this value, that means, transaction must be
- * started after last one has been committed.
- * @return version
- */
- long getVersion();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-import javax.annotation.Nullable;
-import javax.annotation.concurrent.GuardedBy;
-import javax.management.DynamicMBean;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.ModuleFactoryNotFoundException;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.dependencyresolver.DependencyResolverManager;
-import org.opendaylight.controller.config.manager.impl.dependencyresolver.ModuleInternalTransactionalInfo;
-import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicWritableWrapper;
-import org.opendaylight.controller.config.manager.impl.dynamicmbean.ReadOnlyAtomicBoolean;
-import org.opendaylight.controller.config.manager.impl.dynamicmbean.ReadOnlyAtomicBoolean.ReadOnlyAtomicBooleanImpl;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HierarchicalConfigMBeanFactoriesHolder;
-import org.opendaylight.controller.config.manager.impl.jmx.TransactionModuleJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.TransactionModuleJMXRegistrator.TransactionModuleJMXRegistration;
-import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
-import org.opendaylight.controller.config.manager.impl.util.InterfacesHelper;
-import org.opendaylight.controller.config.spi.AbstractModule;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.osgi.framework.BundleContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This is a JMX bean representing current transaction. It contains transaction
- * identifier, unique version and parent version for optimistic locking.
- */
-public class ConfigTransactionControllerImpl implements ConfigTransactionControllerInternal,
- ConfigTransactionControllerImplMXBean, Identifiable<TransactionIdentifier> {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigTransactionControllerImpl.class);
-
- private final ConfigTransactionLookupRegistry txLookupRegistry;
- private final ObjectName controllerON;
-
- private final long parentVersion;
- private final long currentVersion;
- private final HierarchicalConfigMBeanFactoriesHolder factoriesHolder;
- private final DependencyResolverManager dependencyResolverManager;
- private final TransactionStatus transactionStatus;
- private final MBeanServer transactionsMBeanServer;
- private final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories;
-
- /**
- * Disables ability of {@link DynamicWritableWrapper} to change attributes
- * during validation.
- */
- @GuardedBy("this")
- private final AtomicBoolean configBeanModificationDisabled = new AtomicBoolean(false);
- private final ReadOnlyAtomicBoolean readOnlyAtomicBoolean = new ReadOnlyAtomicBooleanImpl(
- configBeanModificationDisabled);
- private final MBeanServer configMBeanServer;
-
- private final boolean blankTransaction;
-
- @GuardedBy("this")
- private final SearchableServiceReferenceWritableRegistry writableSRRegistry;
-
- public ConfigTransactionControllerImpl(final ConfigTransactionLookupRegistry txLookupRegistry,
- final long parentVersion, final BindingContextProvider bindingContextProvider, final long currentVersion,
- final Map<String, Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories,
- final MBeanServer transactionsMBeanServer, final MBeanServer configMBeanServer,
- final boolean blankTransaction, final SearchableServiceReferenceWritableRegistry writableSRRegistry) {
- this.txLookupRegistry = txLookupRegistry;
- String transactionName = txLookupRegistry.getTransactionIdentifier().getName();
- this.controllerON = ObjectNameUtil.createTransactionControllerON(transactionName);
- this.parentVersion = parentVersion;
- this.currentVersion = currentVersion;
- this.currentlyRegisteredFactories = currentlyRegisteredFactories;
- this.factoriesHolder = new HierarchicalConfigMBeanFactoriesHolder(currentlyRegisteredFactories);
- this.transactionStatus = new TransactionStatus();
- this.dependencyResolverManager = new DependencyResolverManager(txLookupRegistry.getTransactionIdentifier(),
- transactionStatus, writableSRRegistry, bindingContextProvider, transactionsMBeanServer);
- this.transactionsMBeanServer = transactionsMBeanServer;
- this.configMBeanServer = configMBeanServer;
- this.blankTransaction = blankTransaction;
- this.writableSRRegistry = writableSRRegistry;
- }
-
- @Override
- public void copyExistingModulesAndProcessFactoryDiff(final Collection<ModuleInternalInfo> existingModules,
- final List<ModuleFactory> lastListOfFactories) {
- // copy old configuration to this server
- for (ModuleInternalInfo oldConfigInfo : existingModules) {
- try {
- copyExistingModule(oldConfigInfo);
- } catch (final InstanceAlreadyExistsException e) {
- throw new IllegalStateException("Error while copying " + oldConfigInfo, e);
- }
- }
- processDefaultBeans(lastListOfFactories);
- }
-
- private synchronized void processDefaultBeans(final List<ModuleFactory> lastListOfFactories) {
- transactionStatus.checkNotCommitStarted();
- transactionStatus.checkNotAborted();
-
- Set<ModuleFactory> oldSet = new HashSet<>(lastListOfFactories);
- Set<ModuleFactory> newSet = new HashSet<>(factoriesHolder.getModuleFactories());
-
- List<ModuleFactory> toBeAdded = new ArrayList<>();
- List<ModuleFactory> toBeRemoved = new ArrayList<>();
- for (ModuleFactory moduleFactory : factoriesHolder.getModuleFactories()) {
- if (!oldSet.contains(moduleFactory)) {
- toBeAdded.add(moduleFactory);
- }
- }
- for (ModuleFactory moduleFactory : lastListOfFactories) {
- if (!newSet.contains(moduleFactory)) {
- toBeRemoved.add(moduleFactory);
- }
- }
- // add default modules
- for (ModuleFactory moduleFactory : toBeAdded) {
- BundleContext bundleContext = getModuleFactoryBundleContext(moduleFactory.getImplementationName());
- Set<? extends Module> defaultModules = moduleFactory.getDefaultModules(dependencyResolverManager,
- bundleContext);
- for (Module module : defaultModules) {
- // ensure default module to be registered to jmx even if its module factory does
- // not use dependencyResolverFactory
- DependencyResolver dependencyResolver = dependencyResolverManager.getOrCreate(module.getIdentifier());
- final ObjectName objectName;
- try {
- boolean defaultBean = true;
- objectName = putConfigBeanToJMXAndInternalMaps(module.getIdentifier(), module, moduleFactory, null,
- dependencyResolver, defaultBean, bundleContext);
- } catch (final InstanceAlreadyExistsException e) {
- throw new IllegalStateException(e);
- }
- // register default module as every possible service
- final Set<ServiceInterfaceAnnotation> serviceInterfaceAnnotations = InterfacesHelper
- .getServiceInterfaceAnnotations(moduleFactory);
- for (String qname : InterfacesHelper.getQNames(serviceInterfaceAnnotations)) {
- try {
- saveServiceReference(qname, module.getIdentifier().getInstanceName(), objectName);
- } catch (final InstanceNotFoundException e) {
- throw new IllegalStateException(
- "Unable to register default module instance " + module + " as a service of " + qname,
- e);
- }
- }
- }
- }
-
- // remove modules belonging to removed factories
- for (ModuleFactory removedFactory : toBeRemoved) {
- List<ModuleIdentifier> modulesOfRemovedFactory = dependencyResolverManager.findAllByFactory(removedFactory);
- for (ModuleIdentifier name : modulesOfRemovedFactory) {
- // remove service refs
- final ModuleFactory moduleFactory = dependencyResolverManager.findModuleInternalTransactionalInfo(name)
- .getModuleFactory();
- final Set<ServiceInterfaceAnnotation> serviceInterfaceAnnotations = InterfacesHelper
- .getServiceInterfaceAnnotations(moduleFactory);
- for (String qname : InterfacesHelper.getQNames(serviceInterfaceAnnotations)) {
- try {
- removeServiceReference(qname, name.getInstanceName());
- } catch (final InstanceNotFoundException e) {
- throw new IllegalStateException(
- "Unable to UNregister default module instance " + name + " as a service of " + qname,
- e);
- }
- }
- // close module
- destroyModule(name);
- }
- }
- }
-
- @SuppressWarnings("IllegalCatch")
- private synchronized void copyExistingModule(final ModuleInternalInfo oldConfigBeanInfo)
- throws InstanceAlreadyExistsException {
-
- transactionStatus.checkNotCommitStarted();
- transactionStatus.checkNotAborted();
- ModuleIdentifier moduleIdentifier = oldConfigBeanInfo.getIdentifier();
- dependencyResolverManager.assertNotExists(moduleIdentifier);
-
- ModuleFactory moduleFactory;
- BundleContext bc;
- try {
- moduleFactory = factoriesHolder.findByModuleName(moduleIdentifier.getFactoryName());
- bc = getModuleFactoryBundleContext(moduleFactory.getImplementationName());
- } catch (final ModuleFactoryNotFoundException e) {
- throw new IllegalStateException(e);
- }
-
- Module module;
- DependencyResolver dependencyResolver = dependencyResolverManager.getOrCreate(moduleIdentifier);
- try {
-
- module = moduleFactory.createModule(moduleIdentifier.getInstanceName(), dependencyResolver,
- oldConfigBeanInfo.getReadableModule(), bc);
- } catch (final Exception e) {
- throw new IllegalStateException(String.format("Error while copying old configuration from %s to %s",
- oldConfigBeanInfo, moduleFactory), e);
- }
- putConfigBeanToJMXAndInternalMaps(moduleIdentifier, module, moduleFactory, oldConfigBeanInfo,
- dependencyResolver, oldConfigBeanInfo.isDefaultBean(), bc);
- }
-
- @Override
- public synchronized ObjectName createModule(final String factoryName, final String instanceName)
- throws InstanceAlreadyExistsException {
-
- transactionStatus.checkNotCommitStarted();
- transactionStatus.checkNotAborted();
- ModuleIdentifier moduleIdentifier = new ModuleIdentifier(factoryName, instanceName);
- dependencyResolverManager.assertNotExists(moduleIdentifier);
-
- // find factory
- ModuleFactory moduleFactory = factoriesHolder.findByModuleName(factoryName);
-
- DependencyResolver dependencyResolver = dependencyResolverManager.getOrCreate(moduleIdentifier);
- BundleContext bundleContext = getModuleFactoryBundleContext(moduleFactory.getImplementationName());
- Module module = moduleFactory.createModule(instanceName, dependencyResolver, bundleContext);
- boolean defaultBean = false;
- return putConfigBeanToJMXAndInternalMaps(moduleIdentifier, module, moduleFactory, null, dependencyResolver,
- defaultBean, bundleContext);
- }
-
- @Override
- public synchronized void reCreateModule(final ObjectName objectName) throws InstanceNotFoundException {
- transactionStatus.checkNotCommitStarted();
- transactionStatus.checkNotAborted();
- checkTransactionName(objectName);
- ObjectNameUtil.checkDomain(objectName);
- ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(objectName, ObjectNameUtil.TYPE_MODULE);
-
- ModuleInternalTransactionalInfo txInfo = dependencyResolverManager
- .findModuleInternalTransactionalInfo(moduleIdentifier);
- Module realModule = txInfo.getRealModule();
- if (realModule instanceof AbstractModule) {
- ((AbstractModule<?>) realModule).setCanReuseInstance(false);
- }
- }
-
- private synchronized ObjectName putConfigBeanToJMXAndInternalMaps(final ModuleIdentifier moduleIdentifier,
- final Module module, final ModuleFactory moduleFactory,
- @Nullable final ModuleInternalInfo maybeOldConfigBeanInfo, final DependencyResolver dependencyResolver,
- final boolean isDefaultBean, final BundleContext bundleContext) throws InstanceAlreadyExistsException {
-
- LOG.debug("Adding module {} to transaction {}", moduleIdentifier, this);
- if (!moduleIdentifier.equals(module.getIdentifier())) {
- throw new IllegalStateException("Incorrect name reported by module. Expected " + moduleIdentifier + ", got "
- + module.getIdentifier());
- }
- if (!dependencyResolver.getIdentifier().equals(moduleIdentifier)) {
- throw new IllegalStateException("Incorrect name reported by dependency resolver. Expected "
- + moduleIdentifier + ", got " + dependencyResolver.getIdentifier());
- }
- DynamicMBean writableDynamicWrapper = new DynamicWritableWrapper(module, moduleIdentifier,
- getTransactionIdentifier().getName(), readOnlyAtomicBoolean, transactionsMBeanServer,
- configMBeanServer);
-
- ObjectName writableON = ObjectNameUtil.createTransactionModuleON(getTransactionIdentifier().getName(),
- moduleIdentifier);
- // put wrapper to jmx
- TransactionModuleJMXRegistration transactionModuleJMXRegistration = getTxModuleJMXRegistrator()
- .registerMBean(writableDynamicWrapper, writableON);
-
- dependencyResolverManager.put(moduleIdentifier, module, moduleFactory, maybeOldConfigBeanInfo,
- transactionModuleJMXRegistration, isDefaultBean, bundleContext);
- return writableON;
- }
-
- @Override
- public synchronized void destroyModule(final ObjectName objectName) throws InstanceNotFoundException {
- checkTransactionName(objectName);
- ObjectNameUtil.checkDomain(objectName);
- ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(objectName, ObjectNameUtil.TYPE_MODULE);
- destroyModule(moduleIdentifier);
- }
-
- private synchronized void destroyModule(final ModuleIdentifier moduleIdentifier) {
- LOG.debug("Destroying module {} in transaction {}", moduleIdentifier, this);
- transactionStatus.checkNotAborted();
-
- ModuleInternalTransactionalInfo found = dependencyResolverManager
- .findModuleInternalTransactionalInfo(moduleIdentifier);
- if (!blankTransaction && found.isDefaultBean()) {
- LOG.warn("Warning: removing default bean. This will be forbidden in next version of config-subsystem");
- }
- // first remove refNames, it checks for objectname existence
-
- try {
- writableSRRegistry.removeServiceReferences(
- ObjectNameUtil.createTransactionModuleON(getTransactionName(), moduleIdentifier));
- } catch (final InstanceNotFoundException e) {
- LOG.error("Possible code error: cannot find {} in {}", moduleIdentifier, writableSRRegistry);
- throw new IllegalStateException("Possible code error: cannot find " + moduleIdentifier, e);
- }
-
- ModuleInternalTransactionalInfo removedTInfo = dependencyResolverManager.destroyModule(moduleIdentifier);
- // remove from jmx
- removedTInfo.getTransactionModuleJMXRegistration().close();
- }
-
- private void checkTransactionName(final ObjectName objectName) {
- String foundTransactionName = ObjectNameUtil.getTransactionName(objectName);
- if (!getTransactionIdentifier().getName().equals(foundTransactionName)) {
- throw new IllegalArgumentException("Wrong transaction name " + objectName);
- }
- }
-
- @Override
- public long getParentVersion() {
- return parentVersion;
- }
-
- @Override
- public long getVersion() {
- return currentVersion;
- }
-
- @Override
- public synchronized void validateConfig() throws ValidationException {
- if (configBeanModificationDisabled.get()) {
- throw new IllegalStateException("Cannot start validation");
- }
- configBeanModificationDisabled.set(true);
- try {
- validateNoLocks();
- } finally {
- configBeanModificationDisabled.set(false);
- }
- }
-
- @SuppressWarnings("IllegalCatch")
- private void validateNoLocks() throws ValidationException {
- transactionStatus.checkNotAborted();
- LOG.trace("Validating transaction {}", getTransactionIdentifier());
- // call validate()
- List<ValidationException> collectedExceptions = new ArrayList<>();
- for (Entry<ModuleIdentifier, Module> entry : dependencyResolverManager.getAllModules().entrySet()) {
- ModuleIdentifier name = entry.getKey();
- Module module = entry.getValue();
- try {
- module.validate();
- } catch (final Exception e) {
- LOG.warn("Validation exception in {}", getTransactionName(), e);
- collectedExceptions.add(ValidationException.createForSingleException(name, e));
- }
- }
- if (!collectedExceptions.isEmpty()) {
- throw ValidationException.createFromCollectedValidationExceptions(collectedExceptions);
- }
- LOG.trace("Validated transaction {}", getTransactionIdentifier());
- }
-
- /**
- * If this method passes validation, it will grab
- * {@link TransactionStatus#secondPhaseCommitStarted} lock. This lock will
- * prevent calling @{link #validateBeforeCommitAndLockTransaction}, effectively
- * only allowing to call {@link #secondPhaseCommit} after successful return of
- * this method.
- */
- @Override
- public synchronized CommitInfo validateBeforeCommitAndLockTransaction() throws ValidationException {
- transactionStatus.checkNotAborted();
- transactionStatus.checkNotCommitStarted();
- configBeanModificationDisabled.set(true);
- try {
- validateNoLocks();
- } catch (final ValidationException e) {
- LOG.trace("Commit failed on validation");
- // recoverable error
- configBeanModificationDisabled.set(false);
- throw e;
- }
- // errors in this state are not recoverable. modules are not mutable
- // anymore.
- transactionStatus.setSecondPhaseCommitStarted();
- return dependencyResolverManager.toCommitInfo();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public synchronized List<ModuleIdentifier> secondPhaseCommit() {
- transactionStatus.checkNotAborted();
- transactionStatus.checkCommitStarted();
- if (!configBeanModificationDisabled.get()) {
- throw new IllegalStateException(
- "Internal error - validateBeforeCommitAndLockTransaction should be called " + "to obtain a lock");
- }
-
- LOG.trace("Committing transaction {}", getTransactionIdentifier());
-
- Map<ModuleIdentifier, Module> allModules = dependencyResolverManager.getAllModules();
-
- // call getInstance() on all Modules from top to bottom (from source to target
- // of the dependency relation)
- // The source of a dependency closes itself and calls getInstance recursively on
- // the dependencies (in case of reconfiguration)
- // This makes close() calls from top to bottom while createInstance() calls are
- // performed bottom to top
- List<ModuleIdentifier> sortedModuleIdentifiers = Lists
- .reverse(dependencyResolverManager.getSortedModuleIdentifiers());
- for (ModuleIdentifier moduleIdentifier : sortedModuleIdentifiers) {
- Module module = allModules.get(moduleIdentifier);
-
- LOG.debug("About to commit {} in transaction {}", moduleIdentifier, getTransactionIdentifier());
- AutoCloseable instance = module.getInstance();
- Preconditions.checkNotNull(instance, "Instance is null:%s in transaction %s", moduleIdentifier,
- getTransactionIdentifier());
- }
-
- LOG.trace("Committed configuration {}", getTransactionIdentifier());
- transactionStatus.setCommitted();
-
- return sortedModuleIdentifiers;
- }
-
- @Override
- public void abortConfig() {
- transactionStatus.checkNotCommitStarted();
- transactionStatus.checkNotAborted();
- internalAbort();
- }
-
- private void internalAbort() {
- LOG.trace("Aborting {}", this);
- transactionStatus.setAborted();
- close();
- }
-
- @Override
- public void close() {
- dependencyResolverManager.close();
- txLookupRegistry.close();
- }
-
- @Override
- public ObjectName getControllerObjectName() {
- return controllerON;
- }
-
- @Override
- public String getTransactionName() {
- return getTransactionIdentifier().getName();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupConfigBeans() {
- return txLookupRegistry.lookupConfigBeans();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName) {
- return txLookupRegistry.lookupConfigBeans(moduleName);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
- return txLookupRegistry.lookupConfigBeans(moduleName, instanceName);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- return txLookupRegistry.lookupConfigBean(moduleName, instanceName);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
- txLookupRegistry.checkConfigBeanExists(objectName);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupRuntimeBeans() {
- return txLookupRegistry.lookupRuntimeBeans();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
- return txLookupRegistry.lookupRuntimeBeans(moduleName, instanceName);
- }
-
- // --
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<String> getAvailableModuleNames() {
- return factoriesHolder.getModuleNames();
- }
-
- @Override
- public boolean isClosed() {
- return transactionStatus.isAbortedOrCommitted();
- }
-
- @Override
- public String toString() {
- return "transactionName=" + getTransactionName();
- }
-
- // @VisibleForTesting
-
- TransactionModuleJMXRegistrator getTxModuleJMXRegistrator() {
- return txLookupRegistry.getTxModuleJMXRegistrator();
- }
-
- public TransactionIdentifier getName() {
- return getTransactionIdentifier();
- }
-
- @Override
- public List<ModuleFactory> getCurrentlyRegisteredFactories() {
- return new ArrayList<>(factoriesHolder.getModuleFactories());
- }
-
- @Override
- public TransactionIdentifier getIdentifier() {
- return getTransactionIdentifier();
- }
-
- @Override
- public BundleContext getModuleFactoryBundleContext(final String factoryName) {
- Map.Entry<ModuleFactory, BundleContext> factoryBundleContextEntry = this.currentlyRegisteredFactories
- .get(factoryName);
- if (factoryBundleContextEntry == null || factoryBundleContextEntry.getValue() == null) {
- throw new NullPointerException("Bundle context of " + factoryName + " ModuleFactory not found.");
- }
- return factoryBundleContextEntry.getValue();
- }
-
- // service reference functionality:
-
- @Override
- public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName,
- final String refName) {
- return writableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
- }
-
- @Override
- public synchronized Map<String, Map<String, ObjectName>> getServiceMapping() {
- return writableSRRegistry.getServiceMapping();
- }
-
- @Override
- public synchronized Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(
- final String serviceInterfaceQName) {
- return writableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
- }
-
- @Override
- public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName)
- throws InstanceNotFoundException {
- return writableSRRegistry.lookupServiceInterfaceNames(objectName);
- }
-
- @Override
- public synchronized String getServiceInterfaceName(final String namespace, final String localName) {
- return writableSRRegistry.getServiceInterfaceName(namespace, localName);
- }
-
- @Override
- public synchronized ObjectName saveServiceReference(final String serviceInterfaceName, final String refName,
- final ObjectName moduleON) throws InstanceNotFoundException {
- return writableSRRegistry.saveServiceReference(serviceInterfaceName, refName, moduleON);
- }
-
- @Override
- public synchronized void removeServiceReference(final String serviceInterfaceName, final String refName)
- throws InstanceNotFoundException {
- writableSRRegistry.removeServiceReference(serviceInterfaceName, refName);
- }
-
- @Override
- public synchronized void removeAllServiceReferences() {
- writableSRRegistry.removeAllServiceReferences();
- }
-
- @Override
- public boolean removeServiceReferences(final ObjectName objectName) throws InstanceNotFoundException {
- return writableSRRegistry.removeServiceReferences(objectName);
- }
-
- @Override
- public SearchableServiceReferenceWritableRegistry getWritableRegistry() {
- return writableSRRegistry;
- }
-
- @Override
- public TransactionIdentifier getTransactionIdentifier() {
- return txLookupRegistry.getTransactionIdentifier();
- }
-
- @Override
- public Set<String> getAvailableModuleFactoryQNames() {
- return txLookupRegistry.getAvailableModuleFactoryQNames();
- }
-
- @Override
- public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
- writableSRRegistry.checkServiceReferenceExists(objectName);
- }
-
- @Override
- public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName)
- throws InstanceNotFoundException {
- return writableSRRegistry.getServiceReference(serviceInterfaceQName, refName);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import org.opendaylight.controller.config.api.ConfigTransactionController;
-
-/**
- * Exposes optimistic locking details about transaction.
- */
-public interface ConfigTransactionControllerImplMXBean extends ConfigTransactionController {
-
- /**
- * Get version of config registry when this transaction was created.
- *
- * @return parent version
- */
- long getParentVersion();
-
- /**
- * Get version of current transaction.
- *
- * @return version
- */
- long getVersion();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import java.util.Collection;
-import java.util.List;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-/**
- * Defines contract between {@link ConfigTransactionControllerImpl} (producer)
- * and {@link ConfigRegistryImpl} (consumer).
- */
-interface ConfigTransactionControllerInternal extends ConfigTransactionControllerImplMXBean, AutoCloseable {
-
- /**
- * 1, Copy already committed modules to current transaction. 2, Diff: compute
- * added and removed factories from last run, then create new modules using
- * {@link org.opendaylight.controller.config.spi
- * .ModuleFactory#getDefaultModules(org.opendaylight.controller
- * .config .api.DependencyResolverFactory, BundleContext)}
- * and remove modules belonging to removed factories.
- *
- * @param entries
- * entries
- * @param lastListOfFactories
- * list of factories
- */
- void copyExistingModulesAndProcessFactoryDiff(Collection<ModuleInternalInfo> entries,
- List<ModuleFactory> lastListOfFactories);
-
- /**
- * Call {@link org.opendaylight.controller.config.spi.Module#validate()} on all
- * beans in transaction. Lock transaction after successful validation. This
- * method can be called multiple times if validation fails, but cannot be called
- * after it did not throw exception.
- *
- * @return CommitInfo commit info
- */
- CommitInfo validateBeforeCommitAndLockTransaction() throws ValidationException;
-
- /**
- * Call {@link org.opendaylight.controller.config.spi.Module#getInstance()} on
- * all beans in transaction. This method can be only called once.
- *
- * @return ordered list of module identifiers that respects dependency order
- */
- List<ModuleIdentifier> secondPhaseCommit();
-
- /**
- * Gets the objectName of this transaction controller.
- *
- * @return ObjectName
- */
- ObjectName getControllerObjectName();
-
- /**
- * Check if the transaction was committed or aborted.
- *
- * @return result of transaction
- */
- boolean isClosed();
-
- List<ModuleFactory> getCurrentlyRegisteredFactories();
-
- BundleContext getModuleFactoryBundleContext(String factoryName);
-
- SearchableServiceReferenceWritableRegistry getWritableRegistry();
-
- TransactionIdentifier getTransactionIdentifier();
-
- @Override
- void close();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import java.io.Closeable;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.LookupRegistry;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.jmx.TransactionJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.TransactionModuleJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.util.LookupBeansUtil;
-import org.opendaylight.controller.config.manager.impl.util.ModuleQNameUtil;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-/**
- * Responsible for creating TransactionJMXRegistrator, registering transaction
- * and all its beans, lookup of beans, closing of TransactionJMXRegistrator.
- */
-class ConfigTransactionLookupRegistry implements LookupRegistry, Closeable {
- private final TransactionJMXRegistrator transactionJMXRegistrator;
- private final TransactionIdentifier transactionIdentifier;
- private final TransactionModuleJMXRegistrator txModuleJMXRegistrator;
- private final Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories;
-
- interface TransactionJMXRegistratorFactory {
- TransactionJMXRegistrator create();
- }
-
- ConfigTransactionLookupRegistry(final TransactionIdentifier transactionIdentifier,
- final TransactionJMXRegistratorFactory factory,
- final Map<String, Entry<ModuleFactory, BundleContext>> allCurrentFactories) {
- this.transactionIdentifier = transactionIdentifier;
- this.transactionJMXRegistrator = factory.create();
- this.txModuleJMXRegistrator = transactionJMXRegistrator.createTransactionModuleJMXRegistrator();
- this.allCurrentFactories = allCurrentFactories;
- }
-
- private void checkTransactionName(final ObjectName objectName) {
- String foundTransactionName = ObjectNameUtil.getTransactionName(objectName);
- if (!transactionIdentifier.getName().equals(foundTransactionName)) {
- throw new IllegalArgumentException("Wrong transaction name " + objectName);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupConfigBeans() {
- return lookupConfigBeans("*", "*");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName) {
- return lookupConfigBeans(moduleName, "*");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
- ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName, instanceName,
- transactionIdentifier.getName());
- return txModuleJMXRegistrator.queryNames(namePattern, null);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
- }
-
- @Override
- public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
- ObjectNameUtil.checkDomain(objectName);
- ObjectNameUtil.checkType(objectName, ObjectNameUtil.TYPE_MODULE);
- checkTransactionName(objectName);
- // make sure exactly one match is found:
- LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName),
- ObjectNameUtil.getInstanceName(objectName));
- }
-
- TransactionIdentifier getTransactionIdentifier() {
- return transactionIdentifier;
- }
-
- TransactionModuleJMXRegistrator getTxModuleJMXRegistrator() {
- return txModuleJMXRegistrator;
- }
-
- @Override
- public void close() {
- transactionJMXRegistrator.close();
- }
-
- public void registerMBean(final ConfigTransactionControllerInternal transactionController,
- final ObjectName controllerObjectName) throws InstanceAlreadyExistsException {
- transactionJMXRegistrator.registerMBean(transactionController, controllerObjectName);
- }
-
- @Override
- public Set<String> getAvailableModuleFactoryQNames() {
- return ModuleQNameUtil.getQNames(allCurrentFactories);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupRuntimeBeans() {
- return lookupRuntimeBeans("*", "*");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
- String finalModuleName = moduleName == null ? "*" : moduleName;
- String finalInstanceName = instanceName == null ? "*" : instanceName;
- ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(finalModuleName, finalInstanceName);
- return transactionJMXRegistrator.queryNames(namePattern, null);
- }
-
- @Override
- public String toString() {
- return "ConfigTransactionLookupRegistry{" + "transactionIdentifier=" + transactionIdentifier + '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.impl;
-
-import java.util.Deque;
-import java.util.LinkedList;
-import java.util.concurrent.TimeUnit;
-import javax.annotation.Nullable;
-import javax.annotation.concurrent.GuardedBy;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class DeadlockMonitor implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(DeadlockMonitor.class);
-
- private static final long WARN_AFTER_MILLIS = 5000;
-
- private final TransactionIdentifier transactionIdentifier;
- private final DeadlockMonitorRunnable thread;
- @GuardedBy("this")
- private final Deque<ModuleIdentifierWithNanos> moduleIdentifierWithNanosStack = new LinkedList<>();
- @GuardedBy("this")
- private ModuleIdentifierWithNanos top = ModuleIdentifierWithNanos.empty;
-
- public DeadlockMonitor(final TransactionIdentifier transactionIdentifier) {
- this.transactionIdentifier = transactionIdentifier;
- thread = new DeadlockMonitorRunnable();
- thread.start();
- }
-
- public synchronized void setCurrentlyInstantiatedModule(final ModuleIdentifier currentlyInstantiatedModule) {
-
- boolean popping = currentlyInstantiatedModule == null;
- if (popping) {
- moduleIdentifierWithNanosStack.pop();
- if (moduleIdentifierWithNanosStack.isEmpty()) {
- top = ModuleIdentifierWithNanos.empty;
- } else {
- top = moduleIdentifierWithNanosStack.peekLast();
- }
- } else {
- ModuleIdentifierWithNanos current = new ModuleIdentifierWithNanos(currentlyInstantiatedModule);
- moduleIdentifierWithNanosStack.push(current);
- top = current;
- }
- LOG.trace("setCurrentlyInstantiatedModule {}, top {}", currentlyInstantiatedModule, top);
- }
-
- public boolean isAlive() {
- return thread.isAlive();
- }
-
- @Override
- public void close() {
- thread.interrupt();
- }
-
- @Override
- public String toString() {
- return "DeadlockMonitor{" + transactionIdentifier + '}';
- }
-
- private final class DeadlockMonitorRunnable extends Thread {
-
- DeadlockMonitorRunnable() {
- super(DeadlockMonitor.this.toString());
- }
-
- @Override
- public void run() {
- // null moduleId
- ModuleIdentifierWithNanos old = new ModuleIdentifierWithNanos();
- while (!this.isInterrupted()) {
- ModuleIdentifierWithNanos copy;
- synchronized (this) {
- copy = new ModuleIdentifierWithNanos(DeadlockMonitor.this.top);
- }
-
- if (old.moduleIdentifier == null || !old.equals(copy)) {
- // started
- old = copy;
- } else {
- // is the getInstance() running longer than WARN_AFTER_MILLIS ?
- long runningTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - copy.nanoTime);
- if (runningTime > WARN_AFTER_MILLIS) {
- LOG.warn("{} did not finish after {} ms", copy.moduleIdentifier, runningTime);
- }
- }
- try {
- sleep(WARN_AFTER_MILLIS);
- } catch (final InterruptedException e) {
- interrupt();
- }
- }
- LOG.trace("Exiting {}", this);
- }
-
- @Override
- public String toString() {
- return "DeadLockMonitorRunnable{" + transactionIdentifier + "}";
- }
- }
-
- private static final class ModuleIdentifierWithNanos {
- private static ModuleIdentifierWithNanos empty = new ModuleIdentifierWithNanos();
- @Nullable
- private final ModuleIdentifier moduleIdentifier;
-
- private final long nanoTime;
-
- ModuleIdentifierWithNanos() {
- this((ModuleIdentifier) null);
- }
-
- ModuleIdentifierWithNanos(final ModuleIdentifier moduleIdentifier) {
- this.moduleIdentifier = moduleIdentifier;
- nanoTime = System.nanoTime();
- }
-
- ModuleIdentifierWithNanos(final ModuleIdentifierWithNanos copy) {
- moduleIdentifier = copy.moduleIdentifier;
- nanoTime = copy.nanoTime;
- }
-
- @Override
- public boolean equals(final Object object) {
- if (this == object) {
- return true;
- }
- if (object == null || getClass() != object.getClass()) {
- return false;
- }
-
- ModuleIdentifierWithNanos that = (ModuleIdentifierWithNanos) object;
-
- if (nanoTime != that.nanoTime) {
- return false;
- }
- if (moduleIdentifier != null ? !moduleIdentifier.equals(that.moduleIdentifier)
- : that.moduleIdentifier != null) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = moduleIdentifier != null ? moduleIdentifier.hashCode() : 0;
- result = 31 * result + (int) (nanoTime ^ nanoTime >>> 32);
- return result;
- }
-
- @Override
- public String toString() {
- return "ModuleIdentifierWithNanos{" + moduleIdentifier + '}';
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import javax.annotation.Nullable;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.manager.impl.dependencyresolver.DestroyedModule;
-import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
-import org.opendaylight.controller.config.manager.impl.jmx.ModuleJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
-import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager.OsgiRegistration;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.osgi.framework.BundleContext;
-
-/**
- * Provides metadata about Module from controller to registry.
- */
-public class ModuleInternalInfo implements Comparable<ModuleInternalInfo>, Identifiable<ModuleIdentifier> {
-
- private final ModuleIdentifier name;
- // this registrator is passed to runtime bean registrator and config
- // registry to register read only module.
- // writable modules are registered using TransactionJMXRegistrator
- @Nullable
- private final DynamicReadableWrapper readableModule;
-
- private final RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator;
- // added when bean instance is registered to Osgi
- // can be unregistered using this registration
- private final OsgiRegistration osgiRegistration;
- private final ModuleJMXRegistrator moduleJMXRegistrator;
- private final int orderingIdx;
- private final boolean isDefaultBean;
- private final ModuleFactory moduleFactory;
- private final BundleContext bundleContext;
-
- public ModuleInternalInfo(final ModuleIdentifier name, @Nullable final DynamicReadableWrapper readableModule,
- final OsgiRegistration osgiRegistration,
- @Nullable final RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator,
- final ModuleJMXRegistrator moduleJMXRegistrator, final int orderingIdx, final boolean isDefaultBean,
- final ModuleFactory moduleFactory, final BundleContext bundleContext) {
-
- if (osgiRegistration == null) {
- throw new IllegalArgumentException("Parameter 'osgiRegistration' is missing");
- }
- this.readableModule = readableModule;
- this.osgiRegistration = osgiRegistration;
- this.runtimeBeanRegistrator = runtimeBeanRegistrator;
- this.name = name;
- this.moduleJMXRegistrator = moduleJMXRegistrator;
- this.orderingIdx = orderingIdx;
- this.isDefaultBean = isDefaultBean;
- this.moduleFactory = moduleFactory;
- this.bundleContext = bundleContext;
- }
-
- public DynamicReadableWrapper getReadableModule() {
- return readableModule;
- }
-
- public ModuleJMXRegistrator getModuleJMXRegistrator() {
- return moduleJMXRegistrator;
- }
-
- /**
- * Tells if a running instance exists in the system.
- *
- * @return is there any running instance in the system.
- */
- public boolean hasReadableModule() {
- return readableModule != null;
- }
-
- @Override
- public String toString() {
- return "ModuleInternalInfo [name=" + name + "]";
- }
-
- public RootRuntimeBeanRegistratorImpl getRuntimeBeanRegistrator() {
- return runtimeBeanRegistrator;
- }
-
- public OsgiRegistration getOsgiRegistration() {
- return osgiRegistration;
- }
-
- /**
- * Get index representing dependency ordering within a transaction.
- *
- * @return index
- */
- public int getOrderingIdx() {
- return orderingIdx;
- }
-
- @Override
- public int compareTo(final ModuleInternalInfo moduleInternalInfo) {
- return Integer.compare(orderingIdx, moduleInternalInfo.orderingIdx);
- }
-
- public DestroyedModule toDestroyedModule() {
- return new DestroyedModule(getIdentifier(), getReadableModule().getInstance(), getModuleJMXRegistrator(),
- getOsgiRegistration(), getOrderingIdx(), runtimeBeanRegistrator);
- }
-
- @Override
- public ModuleIdentifier getIdentifier() {
- return name;
- }
-
- public boolean isDefaultBean() {
- return isDefaultBean;
- }
-
- public ModuleFactory getModuleFactory() {
- return moduleFactory;
- }
-
- public BundleContext getBundleContext() {
- return bundleContext;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.impl;
-
-import java.util.Map;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.ServiceReferenceWritableRegistry;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-
-public interface SearchableServiceReferenceWritableRegistry extends ServiceReferenceWritableRegistry {
- /**
- * Return mapping between service ref names and service interface annotation for
- * given module.
- *
- * @param moduleIdentifier module id
- * @return map
- * @throws java.lang.IllegalArgumentException
- * if any of service qNames is not found
- * @throws java.lang.NullPointerException
- * if parameter is null
- */
- Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(
- ModuleIdentifier moduleIdentifier);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import java.util.AbstractMap.SimpleImmutableEntry;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.LookupRegistry;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
-import org.opendaylight.controller.config.api.ServiceReferenceWritableRegistry;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.ServiceReference;
-import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceMXBeanImpl;
-import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceRegistrator.ServiceReferenceJMXRegistration;
-import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceRegistrator.ServiceReferenceTransactionRegistratorFactory;
-import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceRegistrator.ServiceReferenceTransactionRegistratorFactoryImpl;
-import org.opendaylight.controller.config.manager.impl.util.InterfacesHelper;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class ServiceReferenceRegistryImpl
- implements CloseableServiceReferenceReadableRegistry, SearchableServiceReferenceWritableRegistry {
- private static final Logger LOG = LoggerFactory.getLogger(ServiceReferenceRegistryImpl.class);
-
- private final Map<String, ModuleFactory> factories;
- private final Map<String, Set<String>> factoryNamesToQNames;
- // validator of incoming ObjectNames - throws InstanceNotFoundException if not
- // found either in registry or transaction
- private final LookupRegistry lookupRegistry;
- private final ServiceReferenceRegistrator serviceReferenceRegistrator;
- // helper method for getting QName of SI from namespace + local name
- private final Map<String /* namespace */, Map<String /* local name */, ServiceInterfaceAnnotation>>
- namespacesToAnnotations;
- private final Map<String /* service qName */, ServiceInterfaceAnnotation> serviceQNamesToAnnotations;
- // all Service Interface qNames for sanity checking
- private final Set<String /* qName */> allQNames;
- Map<ModuleIdentifier, Map<ServiceInterfaceAnnotation, String /* service ref name */>> modulesToServiceRef =
- new HashMap<>();
-
- // actual reference database
- private final Map<ServiceReference, ModuleIdentifier> refNames = new HashMap<>();
- private final boolean writable;
- private final Map<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>>
- managementBeans = new HashMap<>();
-
- private ServiceReferenceRegistryImpl(final Map<String, ModuleFactory> factories,
- final LookupRegistry lookupRegistry,
- final ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory,
- final boolean writable) {
- this.factories = factories;
- this.writable = writable;
- this.lookupRegistry = lookupRegistry;
-
- this.serviceReferenceRegistrator = serviceReferenceRegistratorFactory.create();
-
- Map<String, Set<String /* QName */>> modifiableFactoryNamesToQNames = new HashMap<>();
- Set<ServiceInterfaceAnnotation> allAnnotations = new HashSet<>();
- Set<String /* qName */> allQNameSet = new HashSet<>();
-
- for (Entry<String, ModuleFactory> entry : factories.entrySet()) {
- if (!entry.getKey().equals(entry.getValue().getImplementationName())) {
- LOG.error("Possible error in code: Mismatch between supplied and actual name of {}", entry);
- throw new IllegalArgumentException(
- "Possible error in code: Mismatch between supplied and actual name of " + entry);
- }
- Set<ServiceInterfaceAnnotation> siAnnotations = InterfacesHelper
- .getServiceInterfaceAnnotations(entry.getValue());
- Set<String> names = InterfacesHelper.getQNames(siAnnotations);
- allAnnotations.addAll(siAnnotations);
- allQNameSet.addAll(names);
- modifiableFactoryNamesToQNames.put(entry.getKey(), names);
- }
- this.factoryNamesToQNames = ImmutableMap.copyOf(modifiableFactoryNamesToQNames);
- this.allQNames = ImmutableSet.copyOf(allQNameSet);
- // fill namespacesToAnnotations
- Map<String /* namespace */, Map<String /* localName */, ServiceInterfaceAnnotation>>
- modifiableNamespacesToAnnotations = new HashMap<>();
- Map<String /* service qName */, ServiceInterfaceAnnotation>
- modifiableServiceQNamesToAnnotations = new HashMap<>();
- for (ServiceInterfaceAnnotation sia : allAnnotations) {
- Map<String, ServiceInterfaceAnnotation> ofNamespace = modifiableNamespacesToAnnotations
- .computeIfAbsent(sia.namespace(), k -> new HashMap<>());
- if (ofNamespace.containsKey(sia.localName())) {
- LOG.error(
- "Cannot construct namespacesToAnnotations map, conflict between local names in {},"
- + " offending local name: {}, map so far {}",
- sia.namespace(), sia.localName(), modifiableNamespacesToAnnotations);
- throw new IllegalArgumentException(
- "Conflict between local names in " + sia.namespace() + " : " + sia.localName());
- }
- ofNamespace.put(sia.localName(), sia);
- modifiableServiceQNamesToAnnotations.put(sia.value(), sia);
- }
- this.namespacesToAnnotations = ImmutableMap.copyOf(modifiableNamespacesToAnnotations);
- this.serviceQNamesToAnnotations = ImmutableMap.copyOf(modifiableServiceQNamesToAnnotations);
- LOG.trace("factoryNamesToQNames:{}", this.factoryNamesToQNames);
- }
-
- /**
- * Static constructor for config registry. Since only transaction can write to
- * this registry, it will return blank state.
- *
- * @return service reference registry
- */
- public static CloseableServiceReferenceReadableRegistry createInitialSRLookupRegistry() {
- // since this is initial state, just throw exception:
- LookupRegistry lookupRegistry = new LookupRegistry() {
- @Override
- public Set<ObjectName> lookupConfigBeans() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
- throw new InstanceNotFoundException("Cannot find " + objectName + " - Tried to use mocking registry");
- }
-
- @Override
- public Set<String> getAvailableModuleFactoryQNames() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String toString() {
- return "initial";
- }
- };
-
- ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory =
- () -> new ServiceReferenceRegistrator() {
- @Override
- public String getNullableTransactionName() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public ServiceReferenceJMXRegistration registerMBean(final ServiceReferenceMXBeanImpl object,
- final ObjectName on) throws InstanceAlreadyExistsException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void close() {
- }
- };
- return new ServiceReferenceRegistryImpl(Collections.<String, ModuleFactory>emptyMap(), lookupRegistry,
- serviceReferenceRegistratorFactory, false);
- }
-
- public static SearchableServiceReferenceWritableRegistry createSRWritableRegistry(
- final ServiceReferenceReadableRegistry oldReadableRegistry,
- final ConfigTransactionLookupRegistry txLookupRegistry,
- final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
-
- if (txLookupRegistry == null) {
- throw new IllegalArgumentException("txLookupRegistry is null");
- }
- ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldReadableRegistry;
- Map<String, ModuleFactory> factories = extractFactoriesMap(currentlyRegisteredFactories);
- ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory =
- new ServiceReferenceTransactionRegistratorFactoryImpl(txLookupRegistry.getTxModuleJMXRegistrator(),
- txLookupRegistry.getTxModuleJMXRegistrator().getTransactionName());
- ServiceReferenceRegistryImpl newRegistry = new ServiceReferenceRegistryImpl(factories, txLookupRegistry,
- serviceReferenceRegistratorFactory, true);
- copy(old, newRegistry, txLookupRegistry.getTransactionIdentifier().getName());
- return newRegistry;
- }
-
- /**
- * Copy back state to config registry after commit.
- *
- * @param oldWritableRegistry
- * old registry
- * @param lookupRegistry
- * lookup registry
- * @param baseJMXRegistrator
- * JMX registrator
- * @return service reference
- */
- public static CloseableServiceReferenceReadableRegistry createSRReadableRegistry(
- final ServiceReferenceWritableRegistry oldWritableRegistry, final LookupRegistry lookupRegistry,
- final BaseJMXRegistrator baseJMXRegistrator) {
- ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldWritableRegistry;
-
- // even if factories do change, nothing in the mapping can change between
- // transactions
- ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory =
- new ServiceReferenceTransactionRegistratorFactoryImpl(baseJMXRegistrator);
- ServiceReferenceRegistryImpl newRegistry = new ServiceReferenceRegistryImpl(old.factories, lookupRegistry,
- serviceReferenceRegistratorFactory, false);
- copy(old, newRegistry, null);
- return newRegistry;
- }
-
- private static void copy(final ServiceReferenceRegistryImpl old, final ServiceReferenceRegistryImpl newRegistry,
- final String nullableDstTransactionName) {
- for (Entry<ServiceReference, Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration>>
- refNameEntry : old.managementBeans.entrySet()) {
- ObjectName currentImplementation;
- ObjectName currentImplementationSrc = refNameEntry.getValue().getKey().getCurrentImplementation();
- if (nullableDstTransactionName != null) {
- currentImplementation = ObjectNameUtil.withTransactionName(currentImplementationSrc,
- nullableDstTransactionName);
- } else {
- currentImplementation = ObjectNameUtil.withoutTransactionName(currentImplementationSrc);
- }
- try {
- boolean skipChecks = true;
- newRegistry.saveServiceReference(refNameEntry.getKey(), currentImplementation, skipChecks);
- } catch (final InstanceNotFoundException e) {
- LOG.error("Cannot save service reference({}, {})", refNameEntry.getKey(), currentImplementation);
- throw new IllegalStateException("Possible code error", e);
- }
- }
- }
-
- private static Map<String, ModuleFactory> extractFactoriesMap(
- final Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories) {
- Map<String, ModuleFactory> result = new HashMap<>();
- for (Entry<String, Entry<ModuleFactory, BundleContext>> entry : currentlyRegisteredFactories.entrySet()) {
- result.put(entry.getKey(), entry.getValue().getKey());
- }
- return result;
- }
-
- @Override
- public Map<ServiceInterfaceAnnotation, String /* service ref name */> findServiceInterfaces(
- final ModuleIdentifier moduleIdentifier) {
- Map<ServiceInterfaceAnnotation, String /* service ref name */> result = modulesToServiceRef
- .get(moduleIdentifier);
- if (result == null) {
- return Collections.emptyMap();
- }
- return Collections.unmodifiableMap(result);
- }
-
- @Override
- public synchronized Set<String> lookupServiceInterfaceNames(final ObjectName objectName)
- throws InstanceNotFoundException {
- lookupRegistry.checkConfigBeanExists(objectName);
-
- String factoryName = ObjectNameUtil.getFactoryName(objectName);
- Set<String> serviceInterfaceAnnotations = factoryNamesToQNames.get(factoryName);
- if (serviceInterfaceAnnotations == null) {
- LOG.error("Possible error in code: cannot find factory annotations of '{}' extracted from ON {} in {}",
- factoryName, objectName, factoryNamesToQNames);
- throw new IllegalArgumentException("Cannot find factory with name " + factoryName);
- }
- return serviceInterfaceAnnotations;
- }
-
- @Override
- public synchronized String getServiceInterfaceName(final String namespace, final String localName) {
- Map<String /* localName */, ServiceInterfaceAnnotation> ofNamespace = namespacesToAnnotations.get(namespace);
- if (ofNamespace == null) {
- LOG.error("Cannot find namespace {} in {}", namespace, namespacesToAnnotations);
- throw new IllegalArgumentException("Cannot find namespace " + namespace);
- }
- ServiceInterfaceAnnotation sia = ofNamespace.get(localName);
- if (sia == null) {
- LOG.error("Cannot find local name {} in namespace {}, found only {}", localName, namespace, ofNamespace);
- throw new IllegalArgumentException("Cannot find local name " + localName + " in namespace " + namespace);
- }
- return sia.value();
- }
-
- // reading:
-
- @Override
- public synchronized Map<String, Map<String/* refName */, ObjectName>> getServiceMapping() {
- Map<String /* serviceInterfaceName */, Map<String/* refName */, ObjectName>> result = new HashMap<>();
- for (Entry<ServiceReference, ModuleIdentifier> entry : refNames.entrySet()) {
- String name = entry.getKey().getServiceInterfaceQName();
- Map<String /* refName */, ObjectName> innerMap = result.computeIfAbsent(name, k -> new HashMap<>());
- innerMap.put(entry.getKey().getRefName(), getObjectName(entry.getValue()));
- }
- return result;
- }
-
- private ObjectName getObjectName(final ModuleIdentifier moduleIdentifier) {
- ObjectName on;
- try {
- on = lookupRegistry.lookupConfigBean(moduleIdentifier.getFactoryName(), moduleIdentifier.getInstanceName());
- } catch (final InstanceNotFoundException e) {
- LOG.error("Cannot find instance {}", moduleIdentifier);
- throw new IllegalStateException("Cannot find instance " + moduleIdentifier, e);
- }
- return on;
- }
-
- @Override
- public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName,
- final String refName) {
- ServiceReference serviceReference = new ServiceReference(serviceInterfaceQName, refName);
- ModuleIdentifier moduleIdentifier = refNames.get(serviceReference);
- if (moduleIdentifier == null) {
- LOG.error("Cannot find qname {} and refName {} in {}", serviceInterfaceQName, refName, refName);
- throw new IllegalArgumentException("Cannot find " + serviceReference);
- }
- return getObjectName(moduleIdentifier);
- }
-
- @Override
- public synchronized Map<String /* refName */, ObjectName> lookupServiceReferencesByServiceInterfaceName(
- final String serviceInterfaceQName) {
- Map<String, Map<String, ObjectName>> serviceMapping = getServiceMapping();
- Map<String, ObjectName> innerMap = serviceMapping.get(serviceInterfaceQName);
- if (innerMap == null) {
- LOG.error("Cannot find qname {} in {}", serviceInterfaceQName, refNames);
- throw new IllegalArgumentException("Cannot find " + serviceInterfaceQName);
- }
- return innerMap;
- }
-
- @Override
- public synchronized ObjectName getServiceReference(final String serviceInterfaceQName, final String refName)
- throws InstanceNotFoundException {
- ServiceReference serviceReference = new ServiceReference(serviceInterfaceQName, refName);
- if (!managementBeans.containsKey(serviceReference)) {
- throw new InstanceNotFoundException("Cannot find " + serviceReference);
- }
- return getServiceON(serviceReference);
- }
-
- @Override
- public synchronized void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
- String actualTransactionName = ObjectNameUtil.getTransactionName(objectName);
- String expectedTransactionName = serviceReferenceRegistrator.getNullableTransactionName();
- if (writable && actualTransactionName == null
- || writable && !actualTransactionName.equals(expectedTransactionName)) {
- throw new IllegalArgumentException("Mismatched transaction name in " + objectName);
- }
- String serviceQName = ObjectNameUtil.getServiceQName(objectName);
- String referenceName = ObjectNameUtil.getReferenceName(objectName);
- ServiceReference serviceReference = new ServiceReference(serviceQName, referenceName);
- if (!refNames.containsKey(serviceReference)) {
- LOG.warn("Cannot find {} in {}", serviceReference, refNames);
- throw new InstanceNotFoundException("Service reference not found:" + objectName);
- }
- }
-
- // writing:
- private void assertWritable() {
- if (!writable) {
- throw new IllegalStateException("Cannot write to readable registry");
- }
- }
-
- @Override
- public synchronized ObjectName saveServiceReference(final String serviceInterfaceName, final String refName,
- final ObjectName moduleON) throws InstanceNotFoundException {
- assertWritable();
- ServiceReference serviceReference = new ServiceReference(serviceInterfaceName, refName);
- return saveServiceReference(serviceReference, moduleON);
- }
-
- private synchronized ObjectName saveServiceReference(final ServiceReference serviceReference,
- final ObjectName moduleON) throws InstanceNotFoundException {
- return saveServiceReference(serviceReference, moduleON, false);
- }
-
- private synchronized ObjectName saveServiceReference(final ServiceReference serviceReference,
- final ObjectName moduleON, final boolean skipChecks) throws InstanceNotFoundException {
-
- // make sure it is found
- if (!skipChecks) {
- lookupRegistry.checkConfigBeanExists(moduleON);
- }
- String factoryName = ObjectNameUtil.getFactoryName(moduleON);
- String instanceName = ObjectNameUtil.getInstanceName(moduleON);
- ModuleIdentifier moduleIdentifier = new ModuleIdentifier(factoryName, instanceName);
-
- // check that service interface name exist
- Set<String> serviceInterfaceQNames = factoryNamesToQNames.get(moduleIdentifier.getFactoryName());
- if (serviceInterfaceQNames == null) {
- LOG.error("Possible error in code: cannot find factoryName {} in {}, {}", moduleIdentifier.getFactoryName(),
- factoryNamesToQNames, moduleIdentifier);
- throw new IllegalStateException("Possible error in code: cannot find annotations of existing factory "
- + moduleIdentifier.getFactoryName());
- }
- // supplied serviceInterfaceName must exist in this collection
- if (!serviceInterfaceQNames.contains(serviceReference.getServiceInterfaceQName())) {
- LOG.error("Cannot find qName {} with factory name {}, found {}",
- serviceReference.getServiceInterfaceQName(), moduleIdentifier.getFactoryName(),
- serviceInterfaceQNames);
- throw new IllegalArgumentException(
- "Cannot find service interface " + serviceReference.getServiceInterfaceQName() + " within factory "
- + moduleIdentifier.getFactoryName());
- }
-
- // create service reference object name, put to mBeans
- ObjectName result = getServiceON(serviceReference);
- Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> mxBeanEntry =
- managementBeans.get(serviceReference);
- if (mxBeanEntry == null) {
- // create dummy mx bean
- ServiceReferenceMXBeanImpl dummyMXBean = new ServiceReferenceMXBeanImpl(moduleON);
- ServiceReferenceJMXRegistration dummyMXBeanRegistration;
- try {
- dummyMXBeanRegistration = serviceReferenceRegistrator.registerMBean(dummyMXBean, result);
- } catch (final InstanceAlreadyExistsException e) {
- throw new IllegalStateException("Possible error in code. Cannot register " + result, e);
- }
- managementBeans.put(serviceReference, new SimpleImmutableEntry<>(dummyMXBean, dummyMXBeanRegistration));
- } else {
- // update
- mxBeanEntry.getKey().setCurrentImplementation(moduleON);
- }
- // save to refNames
- refNames.put(serviceReference, moduleIdentifier);
- Map<ServiceInterfaceAnnotation, String /* service ref name */> refNamesToAnnotations = modulesToServiceRef
- .computeIfAbsent(moduleIdentifier, k -> new HashMap<>());
-
- ServiceInterfaceAnnotation annotation = serviceQNamesToAnnotations
- .get(serviceReference.getServiceInterfaceQName());
- Preconditions.checkNotNull(annotation,
- "Possible error in code, cannot find annotation for " + serviceReference);
- refNamesToAnnotations.put(annotation, serviceReference.getRefName());
- return result;
- }
-
- private ObjectName getServiceON(final ServiceReference serviceReference) {
- if (writable) {
- return ObjectNameUtil.createTransactionServiceON(serviceReferenceRegistrator.getNullableTransactionName(),
- serviceReference.getServiceInterfaceQName(), serviceReference.getRefName());
- }
-
- return ObjectNameUtil.createReadOnlyServiceON(serviceReference.getServiceInterfaceQName(),
- serviceReference.getRefName());
- }
-
- @Override
- public synchronized void removeServiceReference(final String serviceInterfaceName, final String refName)
- throws InstanceNotFoundException {
- ServiceReference serviceReference = new ServiceReference(serviceInterfaceName, refName);
- removeServiceReference(serviceReference);
- }
-
- private synchronized void removeServiceReference(final ServiceReference serviceReference)
- throws InstanceNotFoundException {
- LOG.debug("Removing service reference {} from {}", serviceReference, this);
- assertWritable();
- // is the qName known?
- if (!allQNames.contains(serviceReference.getServiceInterfaceQName())) {
- LOG.error("Cannot find qname {} in {}", serviceReference.getServiceInterfaceQName(), allQNames);
- throw new IllegalArgumentException(
- "Cannot find service interface " + serviceReference.getServiceInterfaceQName());
- }
- ModuleIdentifier removed = refNames.remove(serviceReference);
- if (removed == null) {
- throw new InstanceNotFoundException("Cannot find " + serviceReference.getServiceInterfaceQName());
- }
- Entry<ServiceReferenceMXBeanImpl, ServiceReferenceJMXRegistration> entry =
- managementBeans.remove(serviceReference);
- if (entry == null) {
- throw new IllegalStateException("Possible code error: cannot remove from mBeans: " + serviceReference);
- }
- entry.getValue().close();
- }
-
- @Override
- public synchronized void removeAllServiceReferences() {
- assertWritable();
- for (ServiceReference serviceReference : managementBeans.keySet()) {
- try {
- removeServiceReference(serviceReference);
- } catch (final InstanceNotFoundException e) {
- throw new IllegalStateException("Possible error in code", e);
- }
- }
- }
-
- @Override
- public synchronized boolean removeServiceReferences(final ObjectName moduleObjectName)
- throws InstanceNotFoundException {
- lookupRegistry.checkConfigBeanExists(moduleObjectName);
- String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName);
- // check that service interface name exist
- Set<String> serviceInterfaceQNames = factoryNamesToQNames.get(factoryName);
- return removeServiceReferences(moduleObjectName, serviceInterfaceQNames);
- }
-
- private boolean removeServiceReferences(final ObjectName moduleObjectName, final Set<String> names)
- throws InstanceNotFoundException {
- ObjectNameUtil.checkType(moduleObjectName, ObjectNameUtil.TYPE_MODULE);
- assertWritable();
- Set<ServiceReference> serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, names);
- for (ServiceReference sr : serviceReferencesLinkingTo) {
- removeServiceReference(sr);
- }
- return !serviceReferencesLinkingTo.isEmpty();
- }
-
- private Set<ServiceReference> findServiceReferencesLinkingTo(final ObjectName moduleObjectName,
- final Set<String> serviceInterfaceQNames) {
- String factoryName = ObjectNameUtil.getFactoryName(moduleObjectName);
- if (serviceInterfaceQNames == null) {
- LOG.warn("Possible error in code: cannot find factoryName {} in {}, object name {}", factoryName,
- factoryNamesToQNames, moduleObjectName);
- throw new IllegalStateException(
- "Possible error in code: cannot find annotations of existing factory " + factoryName);
- }
- String instanceName = ObjectNameUtil.getInstanceName(moduleObjectName);
- ModuleIdentifier moduleIdentifier = new ModuleIdentifier(factoryName, instanceName);
- Set<ServiceReference> result = new HashSet<>();
- for (Entry<ServiceReference, ModuleIdentifier> entry : refNames.entrySet()) {
- if (entry.getValue().equals(moduleIdentifier)) {
- result.add(entry.getKey());
- }
- }
- return result;
- }
-
- @Override
- public String toString() {
- return "ServiceReferenceRegistryImpl{" + "lookupRegistry=" + lookupRegistry + "refNames=" + refNames
- + ", factoryNamesToQNames=" + factoryNamesToQNames + '}';
- }
-
- @Override
- public void close() {
- serviceReferenceRegistrator.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import org.opendaylight.yangtools.concepts.Identifier;
-
-public class TransactionIdentifier implements Identifier {
- private static final long serialVersionUID = 1L;
- private final String name;
-
- public TransactionIdentifier(final String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return "TransactionIdentifier{" + "name='" + name + '\'' + '}';
- }
-
- public String getName() {
- return name;
- }
-
- @Override
- public boolean equals(final Object object) {
- if (this == object) {
- return true;
- }
- if (object == null || getClass() != object.getClass()) {
- return false;
- }
-
- TransactionIdentifier that = (TransactionIdentifier) object;
-
- if (name != null ? !name.equals(that.name) : that.name != null) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- return name != null ? name.hashCode() : 0;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import javax.annotation.concurrent.GuardedBy;
-
-public class TransactionStatus {
- @GuardedBy("this")
- private boolean secondPhaseCommitStarted = false;
- // switches to true during abort or commit failure
- @GuardedBy("this")
- private boolean aborted;
- // switches to true during second phase commit
- @GuardedBy("this")
- private boolean committed;
-
- public synchronized boolean isSecondPhaseCommitStarted() {
- return secondPhaseCommitStarted;
- }
-
- synchronized void setSecondPhaseCommitStarted() {
- this.secondPhaseCommitStarted = true;
- }
-
- public synchronized boolean isAborted() {
- return aborted;
- }
-
- synchronized void setAborted() {
- this.aborted = true;
- }
-
- public synchronized boolean isCommitted() {
- return committed;
- }
-
- synchronized void setCommitted() {
- this.committed = true;
- }
-
- public synchronized boolean isAbortedOrCommitted() {
- return aborted || committed;
- }
-
- public synchronized void checkNotCommitStarted() {
- if (secondPhaseCommitStarted) {
- throw new IllegalStateException("Commit was triggered");
- }
- }
-
- public synchronized void checkCommitStarted() {
- if (!secondPhaseCommitStarted) {
- throw new IllegalStateException("Commit was not triggered");
- }
- }
-
- public synchronized void checkNotAborted() {
- if (aborted) {
- throw new IllegalStateException("Configuration was aborted");
- }
- }
-
- public synchronized void checkNotCommitted() {
- if (committed) {
- throw new IllegalStateException(
- "Cannot use this method after second phase commit");
- }
- }
-
- public synchronized void checkCommitted() {
- if (!committed) {
- throw new IllegalStateException(
- "Cannot use this method before second phase commit");
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dependencyresolver;
-
-import com.google.common.base.Preconditions;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.Set;
-import javax.annotation.concurrent.GuardedBy;
-import javax.management.AttributeNotFoundException;
-import javax.management.InstanceNotFoundException;
-import javax.management.JMX;
-import javax.management.MBeanException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.IdentityAttributeRef;
-import org.opendaylight.controller.config.api.JmxAttribute;
-import org.opendaylight.controller.config.api.JmxAttributeValidationException;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.TransactionStatus;
-import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Protect {@link org.opendaylight.controller.config.spi.Module#getInstance()}
- * by creating proxy that would throw exception if those methods are called
- * during validation. Tracks dependencies for ordering purposes.
- */
-public final class DependencyResolverImpl implements DependencyResolver, Comparable<DependencyResolverImpl> {
- private static final Logger LOG = LoggerFactory.getLogger(DependencyResolverImpl.class);
-
- private final ModulesHolder modulesHolder;
- private final ModuleIdentifier name;
- private final TransactionStatus transactionStatus;
- @GuardedBy("this")
- private final Set<ModuleIdentifier> dependencies = new HashSet<>();
- private final ServiceReferenceReadableRegistry readableRegistry;
- private final BindingContextProvider bindingContextProvider;
- private final String transactionName;
- private final MBeanServer beanServer;
- private Integer maxDependencyDepth;
-
- public DependencyResolverImpl(final ModuleIdentifier currentModule, final TransactionStatus transactionStatus,
- final ModulesHolder modulesHolder, final ServiceReferenceReadableRegistry readableRegistry,
- final BindingContextProvider bindingContextProvider, final String transactionName,
- final MBeanServer beanServer) {
- this.bindingContextProvider = bindingContextProvider;
- this.name = currentModule;
- this.transactionStatus = transactionStatus;
- this.modulesHolder = modulesHolder;
- this.readableRegistry = readableRegistry;
- this.transactionName = transactionName;
- this.beanServer = beanServer;
- }
-
- /**
- * {@inheritDoc}
- */
- // TODO: check for cycles
- @Override
- public void validateDependency(final Class<? extends AbstractServiceInterface> expectedServiceInterface,
- final ObjectName dependentReadOnlyON, final JmxAttribute jmxAttribute) {
-
- this.transactionStatus.checkNotCommitted();
- if (expectedServiceInterface == null) {
- throw new NullPointerException("Parameter 'expectedServiceInterface' is null");
- }
- if (jmxAttribute == null) {
- throw new NullPointerException("Parameter 'jmxAttribute' is null");
- }
-
- JmxAttributeValidationException.checkNotNull(dependentReadOnlyON,
- "is null, expected dependency implementing " + expectedServiceInterface, jmxAttribute);
-
- // check that objectName belongs to this transaction - this should be
- // stripped
- // in DynamicWritableWrapper
- final boolean hasTransaction = ObjectNameUtil.getTransactionName(dependentReadOnlyON) != null;
- JmxAttributeValidationException.checkCondition(!hasTransaction,
- String.format("ObjectName should not contain " + "transaction name. %s set to %s. ", jmxAttribute,
- dependentReadOnlyON),
- jmxAttribute);
-
- final ObjectName newDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
-
- final ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(newDependentReadOnlyON,
- ObjectNameUtil.TYPE_MODULE);
-
- final ModuleFactory foundFactory = this.modulesHolder.findModuleFactory(moduleIdentifier, jmxAttribute);
-
- final boolean implementsSI = foundFactory.isModuleImplementingServiceInterface(expectedServiceInterface);
- if (!implementsSI) {
- final String message = String.format(
- "Found module factory does not expose expected service interface. "
- + "Module name is %s : %s, expected service interface %s, dependent module ON %s , "
- + "attribute %s",
- foundFactory.getImplementationName(), foundFactory, expectedServiceInterface,
- newDependentReadOnlyON, jmxAttribute);
- throw new JmxAttributeValidationException(message, jmxAttribute);
- }
- synchronized (this) {
- this.dependencies.add(moduleIdentifier);
- }
- }
-
- // translate from serviceref to module ON
- private ObjectName translateServiceRefIfPossible(final ObjectName dependentReadOnlyON) {
- ObjectName translatedDependentReadOnlyON = dependentReadOnlyON;
- if (ObjectNameUtil.isServiceReference(translatedDependentReadOnlyON)) {
- final String serviceQName = ObjectNameUtil.getServiceQName(translatedDependentReadOnlyON);
- final String refName = ObjectNameUtil.getReferenceName(translatedDependentReadOnlyON);
- // strip again of transaction name
- translatedDependentReadOnlyON = ObjectNameUtil.withoutTransactionName(
- this.readableRegistry.lookupConfigBeanByServiceInterfaceName(serviceQName, refName));
- }
- return translatedDependentReadOnlyON;
- }
-
- // TODO: check for cycles
- @Override
- public <T> T resolveInstance(final Class<T> expectedType, final ObjectName dependentReadOnlyON,
- final JmxAttribute jmxAttribute) {
- final Module module = resolveModuleInstance(dependentReadOnlyON, jmxAttribute);
-
- synchronized (this) {
- this.dependencies.add(module.getIdentifier());
- }
- final AutoCloseable instance = module.getInstance();
- if (instance == null) {
- final String message = String.format(
- "Error while %s resolving instance %s. getInstance() returned null. Expected type %s, attribute %s",
- this.name, module.getIdentifier(), expectedType, jmxAttribute);
- throw new JmxAttributeValidationException(message, jmxAttribute);
- }
- try {
- return expectedType.cast(instance);
- } catch (final ClassCastException e) {
- final String message = String.format(
- "Instance cannot be cast to expected type. Instance class is %s, expected type %s , attribute %s",
- instance.getClass(), expectedType, jmxAttribute);
- throw new JmxAttributeValidationException(message, e, jmxAttribute);
- }
- }
-
- private Module resolveModuleInstance(final ObjectName dependentReadOnlyON, final JmxAttribute jmxAttribute) {
- Preconditions.checkArgument(dependentReadOnlyON != null, "dependentReadOnlyON");
- Preconditions.checkArgument(jmxAttribute != null, "jmxAttribute");
- final ObjectName translatedDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
- this.transactionStatus.checkCommitStarted();
- this.transactionStatus.checkNotCommitted();
-
- final ModuleIdentifier dependentModuleIdentifier = ObjectNameUtil.fromON(translatedDependentReadOnlyON,
- ObjectNameUtil.TYPE_MODULE);
-
- return Preconditions.checkNotNull(this.modulesHolder.findModule(dependentModuleIdentifier, jmxAttribute));
- }
-
- @Override
- public boolean canReuseDependency(final ObjectName objectName, final JmxAttribute jmxAttribute) {
- Preconditions.checkNotNull(objectName);
- Preconditions.checkNotNull(jmxAttribute);
-
- final Module currentModule = resolveModuleInstance(objectName, jmxAttribute);
- final ModuleIdentifier identifier = currentModule.getIdentifier();
- final ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = this.modulesHolder
- .findModuleInternalTransactionalInfo(identifier);
-
- if (moduleInternalTransactionalInfo.hasOldModule()) {
- final Module oldModule = moduleInternalTransactionalInfo.getOldInternalInfo().getReadableModule()
- .getModule();
- return currentModule.canReuse(oldModule);
- }
- return false;
- }
-
- @Override
- public <T extends BaseIdentity> Class<? extends T> resolveIdentity(final IdentityAttributeRef identityRef,
- final Class<T> expectedBaseClass) {
- final QName qName = QName.create(identityRef.getqNameOfIdentity());
- final Class<?> deserialized = this.bindingContextProvider.getBindingContext().getIdentityClass(qName);
- if (deserialized == null) {
- throw new IllegalStateException("Unable to retrieve identity class for " + qName + ", null response from "
- + this.bindingContextProvider.getBindingContext());
- }
- if (expectedBaseClass.isAssignableFrom(deserialized)) {
- return (Class<T>) deserialized;
- }
- LOG.error("Cannot resolve class of identity {} : deserialized class {} is not a subclass of {}.", identityRef,
- deserialized, expectedBaseClass);
- throw new IllegalArgumentException(
- "Deserialized identity " + deserialized + " cannot be cast to " + expectedBaseClass);
- }
-
- @Override
- public <T extends BaseIdentity> void validateIdentity(final IdentityAttributeRef identityRef,
- final Class<T> expectedBaseClass, final JmxAttribute jmxAttribute) {
- resolveIdentity(identityRef, expectedBaseClass);
- }
-
- @Override
- public int compareTo(final DependencyResolverImpl dependencyResolverImpl) {
- this.transactionStatus.checkCommitStarted();
- return Integer.compare(getMaxDependencyDepth(), dependencyResolverImpl.getMaxDependencyDepth());
- }
-
- int getMaxDependencyDepth() {
- if (this.maxDependencyDepth == null) {
- throw new IllegalStateException("Dependency depth was not computed");
- }
- return this.maxDependencyDepth;
- }
-
- void countMaxDependencyDepth(final DependencyResolverManager manager) {
- // We can calculate the dependency after second phase commit was started
- // Second phase commit starts after validation and validation adds the
- // dependencies into the dependency resolver, which are necessary for the
- // calculation
- // FIXME generated code for abstract module declares validate method as
- // non-final
- // Overriding the validate would cause recreate every time instead of reuse +
- // also possibly wrong close order if there is another module depending
- this.transactionStatus.checkCommitStarted();
- if (this.maxDependencyDepth == null) {
- this.maxDependencyDepth = getMaxDepth(this, manager, new LinkedHashSet<>());
- }
- }
-
- private static int getMaxDepth(final DependencyResolverImpl impl, final DependencyResolverManager manager,
- final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles) {
- int maxDepth = 0;
- final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles2 = new LinkedHashSet<>(chainForDetectingCycles);
- chainForDetectingCycles2.add(impl.getIdentifier());
- for (final ModuleIdentifier dependencyName : impl.dependencies) {
- final DependencyResolverImpl dependentDRI = manager.getOrCreate(dependencyName);
- if (chainForDetectingCycles2.contains(dependencyName)) {
- throw new IllegalStateException(
- String.format("Cycle detected, %s contains %s", chainForDetectingCycles2, dependencyName));
- }
- int subDepth;
- if (dependentDRI.maxDependencyDepth != null) {
- subDepth = dependentDRI.maxDependencyDepth;
- } else {
- subDepth = getMaxDepth(dependentDRI, manager, chainForDetectingCycles2);
- dependentDRI.maxDependencyDepth = subDepth;
- }
- if (subDepth + 1 > maxDepth) {
- maxDepth = subDepth + 1;
- }
- }
- impl.maxDependencyDepth = maxDepth;
- return maxDepth;
- }
-
- @Override
- public ModuleIdentifier getIdentifier() {
- return this.name;
- }
-
- @Override
- @SuppressWarnings("checkstyle:hiddenField")
- public Object getAttribute(final ObjectName name, final String attribute)
- throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
- ObjectName newName = translateServiceRefIfPossible(name);
- // add transaction name
- newName = ObjectNameUtil.withTransactionName(newName, this.transactionName);
- return this.beanServer.getAttribute(newName, attribute);
- }
-
- @Override
- @SuppressWarnings("checkstyle:hiddenField")
- public <T> T newMXBeanProxy(final ObjectName name, final Class<T> interfaceClass) {
- ObjectName newName = translateServiceRefIfPossible(name);
- // add transaction name
- newName = ObjectNameUtil.withTransactionName(newName, this.transactionName);
- return JMX.newMXBeanProxy(this.beanServer, newName, interfaceClass);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dependencyresolver;
-
-import com.google.common.base.Preconditions;
-import com.google.common.reflect.AbstractInvocationHandler;
-import com.google.common.reflect.Reflection;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.annotation.concurrent.GuardedBy;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.MBeanServer;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DependencyResolverFactory;
-import org.opendaylight.controller.config.api.JmxAttribute;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.RuntimeBeanRegistratorAwareModule;
-import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
-import org.opendaylight.controller.config.manager.impl.CommitInfo;
-import org.opendaylight.controller.config.manager.impl.DeadlockMonitor;
-import org.opendaylight.controller.config.manager.impl.ModuleInternalInfo;
-import org.opendaylight.controller.config.manager.impl.TransactionIdentifier;
-import org.opendaylight.controller.config.manager.impl.TransactionStatus;
-import org.opendaylight.controller.config.manager.impl.jmx.TransactionModuleJMXRegistrator.TransactionModuleJMXRegistration;
-import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-/**
- * Holds information about modules being created and destroyed within this
- * transaction. Observes usage of DependencyResolver within modules to figure
- * out dependency tree.
- */
-public class DependencyResolverManager implements DependencyResolverFactory, AutoCloseable {
- @GuardedBy("this")
- private final Map<ModuleIdentifier, DependencyResolverImpl>
- moduleIdentifiersToDependencyResolverMap = new HashMap<>();
- private final TransactionIdentifier transactionIdentifier;
- private final ModulesHolder modulesHolder;
- private final TransactionStatus transactionStatus;
- private final ServiceReferenceReadableRegistry readableRegistry;
- private final BindingContextProvider bindingContextProvider;
- private final DeadlockMonitor deadlockMonitor;
- private final MBeanServer beanServer;
-
- public DependencyResolverManager(final TransactionIdentifier transactionIdentifier,
- final TransactionStatus transactionStatus, final ServiceReferenceReadableRegistry readableRegistry,
- final BindingContextProvider bindingContextProvider, final MBeanServer beanServer) {
- this.transactionIdentifier = transactionIdentifier;
- this.modulesHolder = new ModulesHolder(transactionIdentifier);
- this.transactionStatus = transactionStatus;
- this.readableRegistry = readableRegistry;
- this.bindingContextProvider = bindingContextProvider;
- this.deadlockMonitor = new DeadlockMonitor(transactionIdentifier);
- this.beanServer = beanServer;
- }
-
- @Override
- public DependencyResolver createDependencyResolver(final ModuleIdentifier moduleIdentifier) {
- return getOrCreate(moduleIdentifier);
- }
-
- public synchronized DependencyResolverImpl getOrCreate(final ModuleIdentifier name) {
- DependencyResolverImpl dependencyResolver = moduleIdentifiersToDependencyResolverMap.get(name);
- if (dependencyResolver == null) {
- transactionStatus.checkNotCommitted();
- dependencyResolver = new DependencyResolverImpl(name, transactionStatus, modulesHolder, readableRegistry,
- bindingContextProvider, transactionIdentifier.getName(), beanServer);
- moduleIdentifiersToDependencyResolverMap.put(name, dependencyResolver);
- }
- return dependencyResolver;
- }
-
- /**
- * Get all dependency resolvers, including those that belong to destroyed
- * things?.
- */
- private List<DependencyResolverImpl> getAllSorted() {
- transactionStatus.checkCommitStarted();
- List<DependencyResolverImpl> sorted = new ArrayList<>(moduleIdentifiersToDependencyResolverMap.values());
- for (DependencyResolverImpl dri : sorted) {
- dri.countMaxDependencyDepth(this);
- }
- Collections.sort(sorted);
- return sorted;
- }
-
- public List<ModuleIdentifier> getSortedModuleIdentifiers() {
- List<ModuleIdentifier> result = new ArrayList<>(moduleIdentifiersToDependencyResolverMap.size());
- for (DependencyResolverImpl dri : getAllSorted()) {
- ModuleIdentifier driName = dri.getIdentifier();
- result.add(driName);
- }
- return result;
- }
-
- public ModuleInternalTransactionalInfo destroyModule(final ModuleIdentifier moduleIdentifier) {
- transactionStatus.checkNotCommitted();
- ModuleInternalTransactionalInfo found = modulesHolder.destroyModule(moduleIdentifier);
- moduleIdentifiersToDependencyResolverMap.remove(moduleIdentifier);
- return found;
- }
-
- // protect write access
-
- private static final class ModuleInvocationHandler extends AbstractInvocationHandler {
- private final DeadlockMonitor deadlockMonitor;
- private final ModuleIdentifier moduleIdentifier;
- private final Module module;
-
- // optimization: subsequent calls to getInstance MUST return the same value
- // during transaction,
- // so it is safe to cache the response
- private Object cachedInstance;
-
- ModuleInvocationHandler(final DeadlockMonitor deadlockMonitor, final ModuleIdentifier moduleIdentifier,
- final Module module) {
- this.deadlockMonitor = Preconditions.checkNotNull(deadlockMonitor);
- this.moduleIdentifier = Preconditions.checkNotNull(moduleIdentifier);
- this.module = Preconditions.checkNotNull(module);
- }
-
- @Override
- @SuppressWarnings("checkstyle:avoidHidingCauseException")
- protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
- throws Throwable {
- boolean isGetInstance = "getInstance".equals(method.getName());
- if (isGetInstance) {
- if (cachedInstance != null) {
- return cachedInstance;
- }
-
- Preconditions.checkState(deadlockMonitor.isAlive(), "Deadlock monitor is not alive");
- deadlockMonitor.setCurrentlyInstantiatedModule(moduleIdentifier);
- }
- try {
- Object response = method.invoke(module, args);
- if (isGetInstance) {
- cachedInstance = response;
- }
- return response;
- } catch (final InvocationTargetException e) {
- throw e.getCause();
- } finally {
- if (isGetInstance) {
- deadlockMonitor.setCurrentlyInstantiatedModule(null);
- }
- }
- }
- }
-
- public void put(final ModuleIdentifier moduleIdentifier, final Module module, final ModuleFactory moduleFactory,
- final ModuleInternalInfo maybeOldInternalInfo,
- final TransactionModuleJMXRegistration transactionModuleJMXRegistration, final boolean isDefaultBean,
- final BundleContext bundleContext) {
- transactionStatus.checkNotCommitted();
-
- Class<? extends Module> moduleClass = Module.class;
- if (module instanceof RuntimeBeanRegistratorAwareModule) {
- moduleClass = RuntimeBeanRegistratorAwareModule.class;
- }
- Module proxiedModule = Reflection.newProxy(moduleClass,
- new ModuleInvocationHandler(deadlockMonitor, moduleIdentifier, module));
- ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = new ModuleInternalTransactionalInfo(
- moduleIdentifier, proxiedModule, moduleFactory, maybeOldInternalInfo, transactionModuleJMXRegistration,
- isDefaultBean, module, bundleContext);
- modulesHolder.put(moduleInternalTransactionalInfo);
- }
-
- // wrapped methods:
-
- public CommitInfo toCommitInfo() {
- return modulesHolder.toCommitInfo();
- }
-
- public Module findModule(final ModuleIdentifier moduleIdentifier, final JmxAttribute jmxAttributeForReporting) {
- return modulesHolder.findModule(moduleIdentifier, jmxAttributeForReporting);
- }
-
- public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(
- final ModuleIdentifier moduleIdentifier) {
- return modulesHolder.findModuleInternalTransactionalInfo(moduleIdentifier);
- }
-
- public ModuleFactory findModuleFactory(final ModuleIdentifier moduleIdentifier,
- final JmxAttribute jmxAttributeForReporting) {
- return modulesHolder.findModuleFactory(moduleIdentifier, jmxAttributeForReporting);
- }
-
- public Map<ModuleIdentifier, Module> getAllModules() {
- return modulesHolder.getAllModules();
- }
-
- public void assertNotExists(final ModuleIdentifier moduleIdentifier) throws InstanceAlreadyExistsException {
- modulesHolder.assertNotExists(moduleIdentifier);
- }
-
- public List<ModuleIdentifier> findAllByFactory(final ModuleFactory factory) {
- List<ModuleIdentifier> result = new ArrayList<>();
- for (ModuleInternalTransactionalInfo info : modulesHolder.getAllInfos()) {
- if (factory.equals(info.getModuleFactory())) {
- result.add(info.getIdentifier());
- }
- }
- return result;
- }
-
- @Override
- public void close() {
- modulesHolder.close();
- deadlockMonitor.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dependencyresolver;
-
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.manager.impl.jmx.ModuleJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
-import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager.OsgiRegistration;
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Transfer object representing already committed module that needs to be
- * destroyed. Implements comparable in order to preserve order in which modules
- * were created. Module instances should be closed in order defined by the
- * compareTo method.
- */
-public class DestroyedModule implements AutoCloseable,
- Comparable<DestroyedModule>, Identifiable<ModuleIdentifier> {
- private static final Logger LOG = LoggerFactory
- .getLogger(DestroyedModule.class);
-
- private final ModuleIdentifier identifier;
- private final AutoCloseable instance;
- private final ModuleJMXRegistrator oldJMXRegistrator;
- private final OsgiRegistration osgiRegistration;
- private final int orderingIdx;
- private final RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator;
-
- public DestroyedModule(final ModuleIdentifier identifier, final AutoCloseable instance,
- final ModuleJMXRegistrator oldJMXRegistrator,
- final OsgiRegistration osgiRegistration, final int orderingIdx,
- final RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator) {
- this.identifier = identifier;
- this.instance = instance;
- this.oldJMXRegistrator = oldJMXRegistrator;
- this.osgiRegistration = osgiRegistration;
- this.orderingIdx = orderingIdx;
- this.runtimeBeanRegistrator = runtimeBeanRegistrator;
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- public void close() {
- LOG.trace("Destroying {}", identifier);
- try {
- instance.close();
- } catch (final Exception e) {
- LOG.error("Error while closing instance of {}", identifier, e);
- }
- try {
- oldJMXRegistrator.close();
- } catch (final Exception e) {
- LOG.error("Error while closing jmx registrator of {}", identifier, e);
- }
- try {
- if (runtimeBeanRegistrator != null) {
- runtimeBeanRegistrator.close();
- }
- } catch (final Exception e) {
- LOG.error("Error while closing runtime bean jmx registrator of {}", identifier, e);
- }
- try {
- osgiRegistration.close();
- } catch (final Exception e) {
- LOG.error("Error while closing osgi registration of {}", identifier, e);
- }
- }
-
- @Override
- public int compareTo(final DestroyedModule destroyedModule) {
- return Integer.compare(orderingIdx, destroyedModule.orderingIdx);
- }
-
- @Override
- public ModuleIdentifier getIdentifier() {
- return identifier;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dependencyresolver;
-
-import com.google.common.base.Preconditions;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.manager.impl.ModuleInternalInfo;
-import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
-import org.opendaylight.controller.config.manager.impl.jmx.TransactionModuleJMXRegistrator.TransactionModuleJMXRegistration;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.osgi.framework.BundleContext;
-
-public class ModuleInternalTransactionalInfo implements Identifiable<ModuleIdentifier> {
- private final ModuleIdentifier name;
- private final Module proxiedModule;
- private final Module realModule;
- private final ModuleFactory moduleFactory;
-
- private final TransactionModuleJMXRegistration transactionModuleJMXRegistration;
- private final boolean isDefaultBean;
- private final BundleContext bundleContext;
- @Nullable private ModuleInternalInfo maybeOldInternalInfo;
-
- public ModuleInternalTransactionalInfo(final ModuleIdentifier name, final Module proxiedModule,
- final ModuleFactory moduleFactory,
- final ModuleInternalInfo maybeOldInternalInfo,
- final TransactionModuleJMXRegistration transactionModuleJMXRegistration,
- final boolean isDefaultBean,
- final Module realModule,
- final BundleContext bundleContext) {
- this.name = name;
- this.proxiedModule = proxiedModule;
- this.moduleFactory = moduleFactory;
- this.maybeOldInternalInfo = maybeOldInternalInfo;
- this.transactionModuleJMXRegistration = transactionModuleJMXRegistration;
- this.isDefaultBean = isDefaultBean;
- this.realModule = realModule;
- this.bundleContext = bundleContext;
- }
-
-
- public boolean hasOldModule() {
- return maybeOldInternalInfo != null;
- }
-
- public DestroyedModule toDestroyedModule() {
- if (maybeOldInternalInfo == null) {
- throw new IllegalStateException("Cannot destroy uncommitted module");
- }
- DynamicReadableWrapper oldModule = maybeOldInternalInfo
- .getReadableModule();
- return new DestroyedModule(name, oldModule.getInstance(),
- maybeOldInternalInfo.getModuleJMXRegistrator(),
- maybeOldInternalInfo.getOsgiRegistration(),
- maybeOldInternalInfo.getOrderingIdx(), maybeOldInternalInfo.getRuntimeBeanRegistrator());
- }
-
-
- public Module getProxiedModule() {
- return proxiedModule;
- }
-
- public ModuleFactory getModuleFactory() {
- return moduleFactory;
- }
-
- @Nonnull public ModuleInternalInfo getOldInternalInfo() {
- return Preconditions.checkNotNull(maybeOldInternalInfo);
- }
-
- public void clearOldInternalInfo() {
- Preconditions.checkState(maybeOldInternalInfo != null, "No old internal info present");
- maybeOldInternalInfo = null;
- }
-
- public TransactionModuleJMXRegistration getTransactionModuleJMXRegistration() {
- return transactionModuleJMXRegistration;
- }
-
- @Override
- public ModuleIdentifier getIdentifier() {
- return name;
- }
-
- public boolean isDefaultBean() {
- return isDefaultBean;
- }
-
- public Module getRealModule() {
- return realModule;
- }
-
- public BundleContext getBundleContext() {
- return bundleContext;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dependencyresolver;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.annotation.concurrent.GuardedBy;
-import javax.management.InstanceAlreadyExistsException;
-import org.opendaylight.controller.config.api.JmxAttribute;
-import org.opendaylight.controller.config.api.JmxAttributeValidationException;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.manager.impl.CommitInfo;
-import org.opendaylight.controller.config.manager.impl.TransactionIdentifier;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-
-/**
- * Represents modules to be committed.
- */
-class ModulesHolder implements AutoCloseable {
- private final TransactionIdentifier transactionIdentifier;
- @GuardedBy("this")
- private final Map<ModuleIdentifier, ModuleInternalTransactionalInfo> commitMap = new HashMap<>();
-
- @GuardedBy("this")
- private final Set<ModuleInternalTransactionalInfo> unorderedDestroyedFromPreviousTransactions = new HashSet<>();
-
- ModulesHolder(final TransactionIdentifier transactionIdentifier) {
- this.transactionIdentifier = transactionIdentifier;
- }
-
- public CommitInfo toCommitInfo() {
- List<DestroyedModule> orderedDestroyedFromPreviousTransactions = new ArrayList<>(
- unorderedDestroyedFromPreviousTransactions.size());
- for (ModuleInternalTransactionalInfo toBeDestroyed : unorderedDestroyedFromPreviousTransactions) {
- orderedDestroyedFromPreviousTransactions.add(toBeDestroyed.toDestroyedModule());
- }
- Collections.sort(orderedDestroyedFromPreviousTransactions);
- return new CommitInfo(orderedDestroyedFromPreviousTransactions, commitMap);
- }
-
- private ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(final ModuleIdentifier moduleIdentifier,
- final JmxAttribute jmxAttributeForReporting) {
- ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = commitMap.get(moduleIdentifier);
- JmxAttributeValidationException.checkNotNull(moduleInternalTransactionalInfo,
- "Module " + moduleIdentifier + "" + " not found in transaction " + transactionIdentifier,
- jmxAttributeForReporting);
- return moduleInternalTransactionalInfo;
- }
-
- public ModuleInternalTransactionalInfo findModuleInternalTransactionalInfo(
- final ModuleIdentifier moduleIdentifier) {
- ModuleInternalTransactionalInfo found = commitMap.get(moduleIdentifier);
- if (found == null) {
- throw new IllegalStateException("Not found:" + moduleIdentifier);
- }
- return found;
- }
-
- public Module findModule(final ModuleIdentifier moduleIdentifier, final JmxAttribute jmxAttributeForReporting) {
- return findModuleInternalTransactionalInfo(moduleIdentifier, jmxAttributeForReporting).getProxiedModule();
- }
-
- public ModuleFactory findModuleFactory(final ModuleIdentifier moduleIdentifier,
- final JmxAttribute jmxAttributeForReporting) {
- return findModuleInternalTransactionalInfo(moduleIdentifier, jmxAttributeForReporting).getModuleFactory();
- }
-
- public Map<ModuleIdentifier, Module> getAllModules() {
- Map<ModuleIdentifier, Module> result = new HashMap<>();
- for (ModuleInternalTransactionalInfo entry : commitMap.values()) {
- ModuleIdentifier name = entry.getIdentifier();
- result.put(name, entry.getProxiedModule());
- }
- return result;
- }
-
- public void put(final ModuleInternalTransactionalInfo moduleInternalTransactionalInfo) {
- commitMap.put(moduleInternalTransactionalInfo.getIdentifier(), moduleInternalTransactionalInfo);
- }
-
- public ModuleInternalTransactionalInfo destroyModule(final ModuleIdentifier moduleIdentifier) {
- ModuleInternalTransactionalInfo found = commitMap.remove(moduleIdentifier);
- if (found == null) {
- throw new IllegalStateException("Not found:" + moduleIdentifier);
- }
- if (found.hasOldModule()) {
- unorderedDestroyedFromPreviousTransactions.add(found);
- }
- return found;
- }
-
- public void assertNotExists(final ModuleIdentifier moduleIdentifier) throws InstanceAlreadyExistsException {
- if (commitMap.containsKey(moduleIdentifier)) {
- throw new InstanceAlreadyExistsException("There is an instance registered with name " + moduleIdentifier);
- }
- }
-
- public Collection<ModuleInternalTransactionalInfo> getAllInfos() {
- return commitMap.values();
- }
-
- @Override
- public void close() {
- unorderedDestroyedFromPreviousTransactions.clear();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import java.lang.reflect.Array;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.management.Attribute;
-import javax.management.AttributeList;
-import javax.management.AttributeNotFoundException;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.IntrospectionException;
-import javax.management.ListenerNotFoundException;
-import javax.management.MBeanAttributeInfo;
-import javax.management.MBeanConstructorInfo;
-import javax.management.MBeanException;
-import javax.management.MBeanInfo;
-import javax.management.MBeanNotificationInfo;
-import javax.management.MBeanOperationInfo;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerDelegate;
-import javax.management.MBeanServerNotification;
-import javax.management.NotCompliantMBeanException;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.Description;
-import org.opendaylight.controller.config.api.annotations.RequireInterface;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.util.InterfacesHelper;
-import org.opendaylight.controller.config.spi.Module;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Contains common code for readable/rw dynamic mbean wrappers. Routes all
- * requests (getAttribute, setAttribute, invoke) into the actual instance, but
- * provides additional functionality - namely it disallows setting attribute on
- * a read only wrapper.
- */
-public abstract class AbstractDynamicWrapper implements DynamicMBeanModuleWrapper {
-
- protected final Module module;
- private final MBeanInfo mbeanInfo;
- protected final ObjectName objectNameInternal;
- protected final Map<String, AttributeHolder> attributeHolderMap;
- protected final ModuleIdentifier moduleIdentifier;
- protected final MBeanServer internalServer;
-
- private static final Logger LOG = LoggerFactory.getLogger(AbstractDynamicWrapper.class);
-
- public AbstractDynamicWrapper(final Module module, final boolean writable, final ModuleIdentifier moduleIdentifier,
- final ObjectName thisWrapperObjectName, final MBeanOperationInfo[] operations,
- final MBeanServer internalServer, final MBeanServer configMBeanServer) {
- this.module = module;
- this.moduleIdentifier = moduleIdentifier;
- this.internalServer = internalServer;
- this.objectNameInternal = thisWrapperObjectName;
- // register the actual instance into an mbean server.
- registerActualModule(objectNameInternal, configMBeanServer);
- Set<Class<?>> jmxInterfaces = InterfacesHelper.getMXInterfaces(module.getClass());
- this.attributeHolderMap = buildMBeanInfo(writable, moduleIdentifier, jmxInterfaces, objectNameInternal);
- this.mbeanInfo = generateMBeanInfo(module, attributeHolderMap, operations, jmxInterfaces);
- }
-
- private static final class ModuleNotificationListener implements NotificationListener {
- private final ObjectName objectNameInternal;
- private final MBeanServer internalServer;
- private final MBeanServer configMBeanServer;
-
- private ModuleNotificationListener(final ObjectName objectNameInternal, final MBeanServer internalServer,
- final MBeanServer configMBeanServer) {
- this.objectNameInternal = objectNameInternal;
- this.internalServer = internalServer;
- this.configMBeanServer = configMBeanServer;
- }
-
- @Override
- public void handleNotification(final Notification notification, final Object handback) {
- if (notification instanceof MBeanServerNotification
- && notification.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)
- && ((MBeanServerNotification) notification).getMBeanName().equals(objectNameInternal)) {
- try {
- internalServer.unregisterMBean(objectNameInternal);
- configMBeanServer.removeNotificationListener(MBeanServerDelegate.DELEGATE_NAME, this);
- } catch (MBeanRegistrationException | ListenerNotFoundException | InstanceNotFoundException e) {
- throw new IllegalStateException(e);
- }
- }
- }
- }
-
- /**
- * Register module into an internal mbean server, attach listener to the
- * platform mbean server. Wait until this wrapper gets unregistered, in that
- * case unregister the module and remove listener.
- */
- private NotificationListener registerActualModule(final ObjectName internalObjectName,
- final MBeanServer configMBeanServer) {
- try {
- internalServer.registerMBean(module, internalObjectName);
- } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException
- | IllegalStateException e) {
- throw new IllegalStateException("Error occured during mbean registration with name " + internalObjectName,
- e);
- }
-
- NotificationListener listener = new ModuleNotificationListener(internalObjectName, internalServer,
- configMBeanServer);
- try {
- configMBeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, listener, null, null);
- } catch (final InstanceNotFoundException e) {
- throw new RuntimeException("Could not add notification listener", e);
- }
- return listener;
- }
-
- private static MBeanInfo generateMBeanInfo(final Module module,
- final Map<String, AttributeHolder> attributeHolderMap, final MBeanOperationInfo[] operations,
- final Set<Class<?>> jmxInterfaces) {
-
- String description = findDescription(module.getClass(), jmxInterfaces);
- MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0];
- List<MBeanAttributeInfo> attributes = new ArrayList<>(attributeHolderMap.size());
- for (AttributeHolder attributeHolder : attributeHolderMap.values()) {
- attributes.add(attributeHolder.toMBeanAttributeInfo());
- }
- return new MBeanInfo(module.getClass().getName(), description, attributes.toArray(new MBeanAttributeInfo[0]),
- constructors, operations, new MBeanNotificationInfo[0]);
- }
-
- static String findDescription(final Class<?> clazz, final Set<Class<?>> jmxInterfaces) {
- List<Description> descriptions = AnnotationsHelper.findClassAnnotationInSuperClassesAndIfcs(clazz,
- Description.class, jmxInterfaces);
- return AnnotationsHelper.aggregateDescriptions(descriptions);
- }
-
- protected static MBeanOperationInfo[] getEmptyOperations() {
- return new MBeanOperationInfo[0];
- }
-
- // inspect all exported interfaces ending with MXBean, extract getters &
- // setters into attribute holder
- private Map<String, AttributeHolder> buildMBeanInfo(final boolean writable, final ModuleIdentifier modId,
- final Set<Class<?>> jmxInterfaces, final ObjectName internalObjectName) {
-
- // internal variables for describing MBean elements
- Set<Method> methods = new HashSet<>();
-
- for (Class<?> exportedClass : jmxInterfaces) {
- Method[] ifcMethods = exportedClass.getMethods();
- methods.addAll(Arrays.asList(ifcMethods));
- }
- // TODO: fix reflection, not used
- MBeanInfo internalInfo;
- try {
- internalInfo = internalServer.getMBeanInfo(internalObjectName);
- } catch (InstanceNotFoundException | ReflectionException | IntrospectionException e) {
- throw new RuntimeException("MBean info not found", e);
- }
-
- Map<String, MBeanAttributeInfo> attributeMap = new HashMap<>();
- for (MBeanAttributeInfo a : internalInfo.getAttributes()) {
- attributeMap.put(a.getName(), a);
- }
- Map<String, AttributeHolder> attributeHolderMapLocal = new HashMap<>();
- for (Method method : methods) {
-
- if (method.getParameterTypes().length == 1 && method.getName().startsWith("set")) {
- Method setter;
- String attribName = method.getName().substring(3);
- try {
- setter = module.getClass().getMethod(method.getName(), method.getParameterTypes());
- } catch (final NoSuchMethodException e) {
- throw new RuntimeException("No such method on " + modId, e);
- }
- RequireInterface ifc = AttributeHolder.findRequireInterfaceAnnotation(setter, jmxInterfaces);
- String description = null;
- if (ifc != null) {
- description = AttributeHolder.findDescription(setter, jmxInterfaces);
- }
- AttributeHolder attributeHolder = new AttributeHolder(attribName, module,
- attributeMap.get(attribName).getType(), writable, ifc, description);
- attributeHolderMapLocal.put(attribName, attributeHolder);
- }
- }
- return attributeHolderMapLocal;
- }
-
- // DynamicMBean methods
-
- @Override
- public MBeanInfo getMBeanInfo() {
- return mbeanInfo;
- }
-
- @Override
- public Object getAttribute(final String attributeName)
- throws AttributeNotFoundException, MBeanException, ReflectionException {
- if ("MBeanInfo".equals(attributeName)) {
- return getMBeanInfo();
- }
-
- Object obj = null;
- try {
- obj = internalServer.getAttribute(objectNameInternal, attributeName);
- } catch (final InstanceNotFoundException e) {
- throw new MBeanException(e);
- }
-
- if (obj instanceof ObjectName) {
- AttributeHolder attributeHolder = attributeHolderMap.get(attributeName);
- if (attributeHolder.getRequireInterfaceOrNull() != null) {
- obj = fixObjectName((ObjectName) obj);
- }
- return obj;
- }
-
- if (isDependencyListAttr(attributeName, obj)) {
- obj = fixDependencyListAttribute(obj);
- }
-
- return obj;
- }
-
- private Object fixDependencyListAttribute(final Object attribute) {
- if (!attribute.getClass().isArray()) {
- throw new IllegalArgumentException(
- "Unexpected attribute type, should be an array, but was " + attribute.getClass());
- }
-
- for (int i = 0; i < Array.getLength(attribute); i++) {
-
- Object on = Array.get(attribute, i);
- if (!(on instanceof ObjectName)) {
- throw new IllegalArgumentException(
- "Unexpected attribute type, should be an ObjectName, but was " + on.getClass());
- }
- on = fixObjectName((ObjectName) on);
-
- Array.set(attribute, i, on);
- }
-
- return attribute;
- }
-
- private boolean isDependencyListAttr(final String attributeName, final Object attribute) {
- if (!attributeHolderMap.containsKey(attributeName)) {
- return false;
- }
-
- AttributeHolder attributeHolder = attributeHolderMap.get(attributeName);
-
- boolean isDepList = true;
- isDepList &= attributeHolder.getRequireInterfaceOrNull() != null;
- isDepList &= attribute instanceof ObjectName[];
- return isDepList;
- }
-
- protected ObjectName fixObjectName(final ObjectName on) {
- if (!ObjectNameUtil.ON_DOMAIN.equals(on.getDomain())) {
- throw new IllegalArgumentException(
- "Wrong domain, expected " + ObjectNameUtil.ON_DOMAIN + " setter on " + on);
- }
- // if on contains transaction name, remove it
- String transactionName = ObjectNameUtil.getTransactionName(on);
- if (transactionName != null) {
- return ObjectNameUtil.withoutTransactionName(on);
- }
-
- return on;
- }
-
- @Override
- public AttributeList getAttributes(final String[] attributes) {
- AttributeList result = new AttributeList();
- for (String attributeName : attributes) {
- Object value;
- try {
- value = getAttribute(attributeName);
- result.add(new Attribute(attributeName, value));
- } catch (AttributeNotFoundException | MBeanException | ReflectionException e) {
- LOG.debug("Getting attribute {} failed", attributeName, e);
- }
- }
- return result;
- }
-
- @Override
- public Object invoke(final String actionName, final Object[] params, final String[] signature)
- throws MBeanException, ReflectionException {
- if ("getAttribute".equals(actionName) && params.length == 1 && signature[0].equals(String.class.getName())) {
- try {
- return getAttribute((String) params[0]);
- } catch (final AttributeNotFoundException e) {
- throw new MBeanException(e, "Attribute not found on " + moduleIdentifier);
- }
- } else if ("getAttributes".equals(actionName) && params.length == 1
- && signature[0].equals(String[].class.getName())) {
- return getAttributes((String[]) params[0]);
- } else if ("setAttributes".equals(actionName) && params.length == 1
- && signature[0].equals(AttributeList.class.getName())) {
- return setAttributes((AttributeList) params[0]);
- } else {
- LOG.debug("Operation not found {} ", actionName);
- throw new UnsupportedOperationException(String.format(
- "Operation not found on %s. Method invoke is only supported for getInstance and getAttribute(s) "
- + "method, got actionName %s, params %s, signature %s ",
- moduleIdentifier, actionName, params, signature));
- }
- }
-
- @Override
- public final int hashCode() {
- return module.hashCode();
- }
-
- @Override
- public final boolean equals(final Object other) {
- return module.equals(other);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.ImmutableSet.Builder;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-import org.opendaylight.controller.config.api.annotations.Description;
-
-public final class AnnotationsHelper {
-
- private AnnotationsHelper() {
- }
-
- /**
- * Look for annotation specified by annotationType on method. First observe
- * method's class, then its super classes, then all provided interfaces. Used
- * for finding @Description and @RequireInterface
- *
- * @param <T>
- * generic type of annotation
- * @return list of found annotations
- */
- static <T extends Annotation> List<T> findMethodAnnotationInSuperClassesAndIfcs(final Method setter,
- final Class<T> annotationType, final Set<Class<?>> inspectedInterfaces) {
- Builder<T> result = ImmutableSet.builder();
- Class<?> inspectedClass = setter.getDeclaringClass();
- do {
- try {
- Method foundSetter = inspectedClass.getMethod(setter.getName(), setter.getParameterTypes());
- T annotation = foundSetter.getAnnotation(annotationType);
- if (annotation != null) {
- result.add(annotation);
- }
- // we need to go deeper
- inspectedClass = inspectedClass.getSuperclass();
- // no need to go further
- } catch (final NoSuchMethodException e) {
- inspectedClass = Object.class;
- }
- } while (!inspectedClass.equals(Object.class));
-
- // inspect interfaces
- for (Class<?> ifc : inspectedInterfaces) {
- if (!ifc.isInterface()) {
- throw new IllegalArgumentException(ifc + " is not an interface");
- }
- try {
- Method foundSetter = ifc.getMethod(setter.getName(), setter.getParameterTypes());
- T annotation = foundSetter.getAnnotation(annotationType);
- if (annotation != null) {
- result.add(annotation);
- }
- } catch (final NoSuchMethodException e) {
- break; // FIXME: is this ok?
- }
- }
- return new ArrayList<>(result.build());
- }
-
- /**
- * Look for annotation specified by annotationType on type. First observe class
- * clazz, then its super classes, then all exported interfaces with their super
- * types. Used for finding @Description of modules.
- *
- * @return list of found annotations
- */
- static <T extends Annotation> List<T> findClassAnnotationInSuperClassesAndIfcs(final Class<?> clazz,
- final Class<T> annotationType, final Set<Class<?>> interfaces) {
- List<T> result = new ArrayList<>();
- Class<?> declaringClass = clazz;
- do {
- T annotation = declaringClass.getAnnotation(annotationType);
- if (annotation != null) {
- result.add(annotation);
- }
- declaringClass = declaringClass.getSuperclass();
- } while (!declaringClass.equals(Object.class));
- // inspect interfaces
- for (Class<?> ifc : interfaces) {
- if (!ifc.isInterface()) {
- throw new IllegalArgumentException(ifc + " is not an interface");
- }
- T annotation = ifc.getAnnotation(annotationType);
- if (annotation != null) {
- result.add(annotation);
- }
- }
- return result;
- }
-
- /**
- * Lists aggregate descriptions.
- *
- * @return empty string if no annotation is found, or list of descriptions
- * separated by newline
- */
- static String aggregateDescriptions(final List<Description> descriptions) {
- StringBuilder builder = new StringBuilder();
- for (Description d : descriptions) {
- if (builder.length() != 0) {
- builder.append("\n");
- }
- builder.append(d.value());
-
- }
- return builder.toString();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import java.lang.reflect.Method;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import javax.annotation.Nullable;
-import javax.annotation.concurrent.Immutable;
-import javax.management.MBeanAttributeInfo;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.annotations.Description;
-import org.opendaylight.controller.config.api.annotations.RequireInterface;
-
-@Immutable
-class AttributeHolder {
-
- private final String name;
- private final String description;
- private final Object object;
- private final boolean writable;
-
- @Nullable
- private final RequireInterface requireInterfaceAnnotation;
- private final String attributeType;
-
- protected static final Set<Class<?>> PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER = new HashSet<>();
-
- static {
- PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.add(ObjectName.class);
- PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.add(ObjectName[].class);
- PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.add(List.class);
- }
-
- AttributeHolder(final String name, final Object object, final String returnType, final boolean writable,
- @Nullable final RequireInterface requireInterfaceAnnotation, final String description) {
- if (name == null) {
- throw new NullPointerException();
- }
- this.name = name;
- if (object == null) {
- throw new NullPointerException();
- }
- this.object = object;
- this.writable = writable;
- this.requireInterfaceAnnotation = requireInterfaceAnnotation;
- this.attributeType = returnType;
- this.description = description;
- }
-
- public MBeanAttributeInfo toMBeanAttributeInfo() {
- return new MBeanAttributeInfo(name, attributeType, description, true, true, false);
- }
-
- /**
- * Anotation.
- *
- * @return annotation if setter sets ObjectName or ObjectName[], and is
- * annotated. Return null otherwise.
- */
- RequireInterface getRequireInterfaceOrNull() {
- return requireInterfaceAnnotation;
- }
-
- public String getName() {
- return name;
- }
-
- public Object getObject() {
- return object;
- }
-
- public String getAttributeType() {
- return attributeType;
- }
-
- public boolean isWritable() {
- return writable;
- }
-
- public String getDescription() {
- return description;
- }
-
- /**
- * Find @Description annotations in method class and all its exported
- * interfaces.
- *
- * @param setter setter method
- * @param jmxInterfaces JMX interfaces
- * @return empty string if no annotation is found, or list of descriptions
- * separated by newline
- */
- static String findDescription(final Method setter, final Set<Class<?>> jmxInterfaces) {
- List<Description> descriptions = AnnotationsHelper.findMethodAnnotationInSuperClassesAndIfcs(setter,
- Description.class, jmxInterfaces);
- return AnnotationsHelper.aggregateDescriptions(descriptions);
- }
-
- /**
- * Find @RequireInterface annotation by searching method class and all exported
- * interfaces.
- *
- * @param setter setter method
- * @param inspectedInterfaces interfaces
- * @return null if no annotation is found, otherwise return the annotation
- * @throws IllegalStateException
- * if more than one value is specified by found annotations
- * @throws IllegalArgumentException
- * if set of exported interfaces contains non interface type
- */
- static RequireInterface findRequireInterfaceAnnotation(final Method setter,
- final Set<Class<?>> inspectedInterfaces) {
-
- // only allow setX(ObjectName y) or setX(ObjectName[] y) or
- // setX(List<ObjectName> y) to continue
-
- if (setter.getParameterTypes().length > 1
- || !PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.contains(setter.getParameterTypes()[0])) {
- return null;
- }
-
- List<RequireInterface> foundRequireInterfaces = AnnotationsHelper
- .findMethodAnnotationInSuperClassesAndIfcs(setter, RequireInterface.class, inspectedInterfaces);
- // make sure the list if not empty contains always annotation with same
- // value
- Set<Class<?>> foundValues = new HashSet<>();
- for (RequireInterface ri : foundRequireInterfaces) {
- foundValues.add(ri.value());
- }
- if (foundValues.isEmpty()) {
- return null;
- } else if (foundValues.size() > 1) {
- throw new IllegalStateException(
- "Error finding @RequireInterface. " + "More than one value specified as required interface "
- + foundValues + " of " + setter + " of " + setter.getDeclaringClass());
- } else {
- return foundRequireInterfaces.get(0);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import javax.management.DynamicMBean;
-
-/**
- * Each {@link org.opendaylight.controller.config.spi.Module} in JMX registry
- * will be wrapped in this class.
- */
-public interface DynamicMBeanModuleWrapper extends DynamicMBean {
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import javax.management.Attribute;
-import javax.management.AttributeList;
-import javax.management.AttributeNotFoundException;
-import javax.management.InvalidAttributeValueException;
-import javax.management.MBeanException;
-import javax.management.MBeanServer;
-import javax.management.ReflectionException;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.spi.Module;
-
-/**
- * Wraps {@link org.opendaylight.controller.config.spi.Module} in a
- * {@link DynamicMBeanWithInstance}. Setting attributes is disabled.
- */
-public class DynamicReadableWrapper extends AbstractDynamicWrapper implements
- DynamicMBeanWithInstance {
- private final AutoCloseable instance;
-
- public DynamicReadableWrapper(final Module module, final AutoCloseable instance,
- final ModuleIdentifier moduleIdentifier, final MBeanServer internalServer,
- final MBeanServer configMBeanServer) {
- super(module, false, moduleIdentifier, ObjectNameUtil
- .createReadOnlyModuleON(moduleIdentifier),
- getEmptyOperations(), internalServer, configMBeanServer);
- this.instance = instance;
- }
-
- @Override
- public Module getModule() {
- return module;
- }
-
- @Override
- public AutoCloseable getInstance() {
- return instance;
- }
-
- @Override
- public Object invoke(final String actionName, final Object[] params, final String[] signature)
- throws MBeanException, ReflectionException {
- if ("getInstance".equals(actionName)
- && (params == null || params.length == 0)
- && (signature == null || signature.length == 0)) {
- return getInstance();
- }
- return super.invoke(actionName, params, signature);
- }
-
- @Override
- public Object getAttribute(final String attributeName)
- throws AttributeNotFoundException, MBeanException,
- ReflectionException {
- if ("getInstance".equals(attributeName)) {
- return getInstance();
- }
- return super.getAttribute(attributeName);
- }
-
- @Override
- public void setAttribute(final Attribute attribute)
- throws AttributeNotFoundException, InvalidAttributeValueException,
- MBeanException, ReflectionException {
- throw new UnsupportedOperationException(
- "setAttributes is not supported on " + moduleIdentifier);
- }
-
- @Override
- public AttributeList setAttributes(final AttributeList attributes) {
- throw new UnsupportedOperationException(
- "setAttributes is not supported on " + moduleIdentifier);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import java.lang.reflect.Method;
-import javax.annotation.concurrent.ThreadSafe;
-import javax.management.Attribute;
-import javax.management.AttributeList;
-import javax.management.AttributeNotFoundException;
-import javax.management.DynamicMBean;
-import javax.management.InstanceNotFoundException;
-import javax.management.InvalidAttributeValueException;
-import javax.management.MBeanException;
-import javax.management.MBeanOperationInfo;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.annotations.RequireInterface;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.spi.Module;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Wraps {@link org.opendaylight.controller.config.spi.Module} instance in a
- * {@link DynamicMBean} interface. Inspects dependency attributes, identified by
- * ObjectName getter/setter and {@link RequireInterface} annotation. Used to
- * simplify client calls - to set a dependency, only instance name is needed.
- * This class creates new writable String attribute for each dependency with
- * 'Name' suffix backed by the actual ObjectName attribute.
- * <p>
- * Thread safety - setting attributes is synchronized on 'this'. Synchronization
- * of {@link org.opendaylight.controller.config.spi.Module#validate()} and
- * {@link org.opendaylight.controller.config.spi.Module#getInstance()} is also
- * guaranteed by
- * org.opendaylight.controller.config.manager.impl.ConfigTransactionControllerInternal
- * so the actual {@link org.opendaylight.controller.config.spi.Module} needs not
- * to be thread safe.
- * </p>
- */
-@ThreadSafe
-public class DynamicWritableWrapper extends AbstractDynamicWrapper {
- private static final Logger LOG = LoggerFactory.getLogger(DynamicWritableWrapper.class);
-
- private final ReadOnlyAtomicBoolean configBeanModificationDisabled;
-
- public DynamicWritableWrapper(final Module module, final ModuleIdentifier moduleIdentifier,
- final String transactionIdentifier, final ReadOnlyAtomicBoolean configBeanModificationDisabled,
- final MBeanServer internalServer, final MBeanServer configMBeanServer) {
- super(module, true, moduleIdentifier,
- ObjectNameUtil.createTransactionModuleON(transactionIdentifier, moduleIdentifier),
- getOperations(moduleIdentifier), internalServer, configMBeanServer);
- this.configBeanModificationDisabled = configBeanModificationDisabled;
- }
-
- private static MBeanOperationInfo[] getOperations(final ModuleIdentifier moduleIdentifier) {
- Method validationMethod;
- try {
- validationMethod = DynamicWritableWrapper.class.getMethod("validate");
- } catch (final NoSuchMethodException e) {
- throw new IllegalStateException("No such method exception on " + moduleIdentifier, e);
- }
- return new MBeanOperationInfo[] { new MBeanOperationInfo("Validation", validationMethod) };
- }
-
- @Override
- public synchronized void setAttribute(final Attribute attribute)
- throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
- Attribute newAttribute = attribute;
- if (configBeanModificationDisabled.get()) {
- throw new IllegalStateException("Operation is not allowed now");
- }
-
- if ("Attribute".equals(newAttribute.getName())) {
- setAttribute((Attribute) newAttribute.getValue());
- return;
- }
-
- try {
- if (newAttribute.getValue() instanceof ObjectName) {
- newAttribute = fixDependencyAttribute(newAttribute);
- } else if (newAttribute.getValue() instanceof ObjectName[]) {
- newAttribute = fixDependencyListAttribute(newAttribute);
- }
-
- internalServer.setAttribute(objectNameInternal, newAttribute);
- } catch (final InstanceNotFoundException e) {
- throw new MBeanException(e);
- }
-
- }
-
- private Attribute fixDependencyListAttribute(final Attribute attribute) {
- Attribute newAttribute = attribute;
- AttributeHolder attributeHolder = attributeHolderMap.get(newAttribute.getName());
- if (attributeHolder.getRequireInterfaceOrNull() != null) {
- newAttribute = new Attribute(newAttribute.getName(),
- fixObjectNames((ObjectName[]) newAttribute.getValue()));
- }
- return newAttribute;
- }
-
- private Attribute fixDependencyAttribute(final Attribute attribute) {
- Attribute newAttribute = attribute;
- AttributeHolder attributeHolder = attributeHolderMap.get(newAttribute.getName());
- if (attributeHolder.getRequireInterfaceOrNull() != null) {
- newAttribute = new Attribute(newAttribute.getName(), fixObjectName((ObjectName) newAttribute.getValue()));
- } else {
- newAttribute = new Attribute(newAttribute.getName(), newAttribute.getValue());
- }
- return newAttribute;
- }
-
- private ObjectName[] fixObjectNames(final ObjectName[] dependencies) {
- int index = 0;
-
- for (ObjectName dependencyOn : dependencies) {
- dependencies[index++] = fixObjectName(dependencyOn);
- }
-
- return dependencies;
- }
-
- @Override
- public AttributeList setAttributes(final AttributeList attributes) {
- AttributeList result = new AttributeList();
- for (Object attributeObject : attributes) {
- Attribute attribute = (Attribute) attributeObject;
- try {
- setAttribute(attribute);
- result.add(attribute);
- } catch (final InvalidAttributeValueException | AttributeNotFoundException | MBeanException
- | ReflectionException e) {
- LOG.warn("Setting attribute {} failed on {}", attribute.getName(), moduleIdentifier, e);
- throw new IllegalArgumentException(
- "Setting attribute failed - " + attribute.getName() + " on " + moduleIdentifier, e);
- }
- }
- return result;
- }
-
- @SuppressWarnings("IllegalCatch")
- @Override
- public Object invoke(final String actionName, final Object[] params, final String[] signature)
- throws MBeanException, ReflectionException {
- if ("validate".equals(actionName) && (params == null || params.length == 0)
- && (signature == null || signature.length == 0)) {
- try {
- validate();
- } catch (final Exception e) {
- throw new MBeanException(ValidationException.createForSingleException(moduleIdentifier, e));
- }
- return Void.TYPE;
- }
- return super.invoke(actionName, params, signature);
- }
-
- public void validate() {
- module.validate();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-public interface ReadOnlyAtomicBoolean {
- boolean get();
-
- class ReadOnlyAtomicBooleanImpl implements
- ReadOnlyAtomicBoolean {
- private final AtomicBoolean atomicBoolean;
-
- public ReadOnlyAtomicBooleanImpl(final AtomicBoolean atomicBoolean) {
- this.atomicBoolean = atomicBoolean;
- }
-
- @Override
- public boolean get() {
- return atomicBoolean.get();
- }
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.factoriesresolver;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import org.opendaylight.controller.config.api.ModuleFactoryNotFoundException;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-/**
- * Hold sorted ConfigMBeanFactories by their module names. Check that module
- * names are globally unique.
- */
-public class HierarchicalConfigMBeanFactoriesHolder {
-
- private final Map<String, Map.Entry<ModuleFactory, BundleContext>> moduleNamesToConfigBeanFactories;
- private final Set<String> moduleNames;
- private final List<ModuleFactory> moduleFactories;
-
- /**
- * Create instance.
- *
- * @param factoriesMap map of factories
- * @throws IllegalArgumentException
- * if unique constraint on module names is violated
- */
- public HierarchicalConfigMBeanFactoriesHolder(
- final Map<String, Map.Entry<ModuleFactory, BundleContext>> factoriesMap) {
- this.moduleNamesToConfigBeanFactories = Collections.unmodifiableMap(factoriesMap);
- moduleNames = Collections.unmodifiableSet(new TreeSet<>(moduleNamesToConfigBeanFactories.keySet()));
- List<ModuleFactory> factories = new ArrayList<>(this.moduleNamesToConfigBeanFactories.size());
- Collection<Map.Entry<ModuleFactory, BundleContext>> entryCollection = this.moduleNamesToConfigBeanFactories
- .values();
- for (Map.Entry<ModuleFactory, BundleContext> entry : entryCollection) {
- factories.add(entry.getKey());
- }
- this.moduleFactories = Collections.unmodifiableList(factories);
- }
-
- /**
- * Get ModuleFactory by their name.
- *
- * @param moduleName
- * module name
- * @return module factory
- * @throws IllegalArgumentException
- * if factory is not found
- */
- public ModuleFactory findByModuleName(final String moduleName) {
- Map.Entry<ModuleFactory, BundleContext> result = moduleNamesToConfigBeanFactories.get(moduleName);
- if (result == null) {
- throw new ModuleFactoryNotFoundException(moduleName);
- }
- return result.getKey();
- }
-
- public Set<String> getModuleNames() {
- return moduleNames;
- }
-
- public List<ModuleFactory> getModuleFactories() {
- return moduleFactories;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.factoriesresolver;
-
-import java.util.Map;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-/**
- * org.opendaylight.controller.config.manager.impl.ConfigTransactionControllerImpl
- * receives list of factories using this interface. For testing, this could be
- * implemented as hard coded list of objects, for OSGi this would look for all
- * services in OSGi Service Registry are registered under
- * {@link org.opendaylight.controller.config.spi.ModuleFactory} name.
- */
-public interface ModuleFactoriesResolver {
-
- Map<String, Map.Entry<ModuleFactory, BundleContext>> getAllFactories();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import java.util.Set;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import javax.management.QueryExp;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-
-public class BaseJMXRegistrator implements AutoCloseable, NestableJMXRegistrator {
-
- private final InternalJMXRegistrator internalJMXRegistrator;
-
- public BaseJMXRegistrator(final MBeanServer configMBeanServer) {
- internalJMXRegistrator = InternalJMXRegistrator.create(configMBeanServer);
- }
-
- public BaseJMXRegistrator(final InternalJMXRegistrator internalJMXRegistrator) {
- this.internalJMXRegistrator = internalJMXRegistrator;
- }
-
- public TransactionJMXRegistrator createTransactionJMXRegistrator(final String transactionName) {
- return new TransactionJMXRegistrator(internalJMXRegistrator.createChild(), transactionName);
- }
-
- public ModuleJMXRegistrator createModuleJMXRegistrator() {
- return new ModuleJMXRegistrator(internalJMXRegistrator.createChild());
- }
-
- public RootRuntimeBeanRegistratorImpl createRuntimeBeanRegistrator(final ModuleIdentifier moduleIdentifier) {
- return new RootRuntimeBeanRegistratorImpl(internalJMXRegistrator.createChild(), moduleIdentifier);
- }
-
- public Set<ObjectName> queryNames(final ObjectName name, final QueryExp query) {
- return internalJMXRegistrator.queryNames(name, query);
- }
-
- public Set<ObjectName> getRegisteredObjectNames() {
- return internalJMXRegistrator.getRegisteredObjectNames();
- }
-
- @Override
- public InternalJMXRegistrator createChild() {
- return internalJMXRegistrator.createChild();
- }
-
- @Override
- public void close() {
- internalJMXRegistrator.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.MBeanServer;
-import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
-import org.opendaylight.controller.config.manager.impl.ConfigRegistryImplMXBean;
-
-/**
- * This registrator is used only to register Config Registry to JMX.
- *
- */
-public class ConfigRegistryJMXRegistrator implements AutoCloseable {
- private final InternalJMXRegistrator internalJMXRegistrator;
-
- public ConfigRegistryJMXRegistrator(final MBeanServer configMBeanServer) {
- internalJMXRegistrator = InternalJMXRegistrator.create(configMBeanServer);
- }
-
- public AutoCloseable registerToJMX(final ConfigRegistryImplMXBean configRegistry)
- throws InstanceAlreadyExistsException {
- return internalJMXRegistrator.registerMBean(configRegistry, ConfigRegistryMXBean.OBJECT_NAME);
- }
-
- public AutoCloseable registerToJMXNoNotifications(final ConfigRegistryImplMXBean configRegistry)
- throws InstanceAlreadyExistsException {
- return internalJMXRegistrator.registerMBean(configRegistry, ConfigRegistryMXBean.OBJECT_NAME_NO_NOTIFICATIONS);
- }
-
- @Override
- public void close() {
- internalJMXRegistrator.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import java.util.HashMap;
-import java.util.Map;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.api.runtime.HierarchicalRuntimeBeanRegistration;
-import org.opendaylight.controller.config.api.runtime.RuntimeBean;
-
-public class HierarchicalRuntimeBeanRegistrationImpl implements
- HierarchicalRuntimeBeanRegistration {
- private final ModuleIdentifier moduleIdentifier;
- private final InternalJMXRegistrator internalJMXRegistrator;
- private final Map<String, String> properties;
-
- public HierarchicalRuntimeBeanRegistrationImpl(
- final ModuleIdentifier moduleIdentifier,
- final InternalJMXRegistrator internalJMXRegistrator,
- final Map<String, String> properties) {
- this.moduleIdentifier = moduleIdentifier;
- this.internalJMXRegistrator = internalJMXRegistrator;
- this.properties = properties;
- }
-
- @Override
- public ObjectName getObjectName() {
- return ObjectNameUtil.createRuntimeBeanName(
- moduleIdentifier.getFactoryName(),
- moduleIdentifier.getInstanceName(), properties);
- }
-
- @Override
- public HierarchicalRuntimeBeanRegistrationImpl register(final String key,
- final String value, final RuntimeBean mxBean) {
- Map<String, String> currentProperties = new HashMap<>(properties);
- currentProperties.put(key, value);
- ObjectName on = ObjectNameUtil.createRuntimeBeanName(
- moduleIdentifier.getFactoryName(),
- moduleIdentifier.getInstanceName(), currentProperties);
- InternalJMXRegistrator child = internalJMXRegistrator.createChild();
- try {
- child.registerMBean(mxBean, on);
- } catch (final InstanceAlreadyExistsException e) {
- throw RootRuntimeBeanRegistratorImpl.sanitize(e, moduleIdentifier,
- on);
- }
- return new HierarchicalRuntimeBeanRegistrationImpl(moduleIdentifier,
- child, currentProperties);
- }
-
- @Override
- public void close() {
- internalJMXRegistrator.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import com.google.common.base.Preconditions;
-import javax.management.ObjectName;
-import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
-
-final class InternalJMXRegistration extends AbstractObjectRegistration<ObjectName> {
- private final InternalJMXRegistrator internalJMXRegistrator;
-
- InternalJMXRegistration(final InternalJMXRegistrator internalJMXRegistrator, final ObjectName on) {
- super(on);
- this.internalJMXRegistrator = Preconditions.checkNotNull(internalJMXRegistrator);
- }
-
- @Override
- protected void removeRegistration() {
- internalJMXRegistrator.unregisterMBean(getInstance());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import com.google.common.base.Preconditions;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import javax.annotation.concurrent.GuardedBy;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.JMX;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.NotCompliantMBeanException;
-import javax.management.ObjectName;
-import javax.management.QueryExp;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-abstract class InternalJMXRegistrator implements AutoCloseable {
- private static final class Root extends InternalJMXRegistrator {
- private final MBeanServer mbeanServer;
-
- Root(final MBeanServer mbeanServer) {
- this.mbeanServer = Preconditions.checkNotNull(mbeanServer);
- }
-
- @Override
- MBeanServer getMBeanServer() {
- return mbeanServer;
- }
- }
-
- private static final class Nested extends InternalJMXRegistrator {
- private final InternalJMXRegistrator parent;
-
- Nested(final InternalJMXRegistrator parent) {
- this.parent = Preconditions.checkNotNull(parent);
- }
-
- @Override
- MBeanServer getMBeanServer() {
- return parent.getMBeanServer();
- }
-
- @Override
- public void close() {
- try {
- super.close();
- } finally {
- parent.removeChild(this);
- }
- }
- }
-
- private static final Logger LOG = LoggerFactory.getLogger(InternalJMXRegistrator.class);
- @GuardedBy("this")
- private final Set<ObjectName> registeredObjectNames = new HashSet<>(1);
- @GuardedBy("this")
- private final List<Nested> children = new ArrayList<>();
-
- public static InternalJMXRegistrator create(final MBeanServer configMBeanServer) {
- return new Root(configMBeanServer);
- }
-
- public final synchronized InternalJMXRegistration registerMBean(final Object object, final ObjectName on)
- throws InstanceAlreadyExistsException {
- try {
- getMBeanServer().registerMBean(object, on);
- } catch (final NotCompliantMBeanException e) {
- throw new IllegalArgumentException("Object does not comply to JMX", e);
- } catch (final MBeanRegistrationException e) {
- throw new IllegalStateException("Failed to register " + on, e);
- }
-
- registeredObjectNames.add(on);
- return new InternalJMXRegistration(this, on);
- }
-
- final synchronized void unregisterMBean(final ObjectName on) {
- // first check that on was registered using this instance
- boolean removed = registeredObjectNames.remove(on);
- Preconditions.checkState(removed, "Cannot unregister - ObjectName not found in 'registeredObjectNames': %s",
- on);
-
- try {
- getMBeanServer().unregisterMBean(on);
- } catch (final InstanceNotFoundException e) {
- LOG.warn("MBean {} not found on server", on, e);
- } catch (final MBeanRegistrationException e) {
- throw new IllegalStateException("Failed to unregister MBean " + on, e);
- }
- }
-
- public final synchronized InternalJMXRegistrator createChild() {
- final Nested child = new Nested(this);
- children.add(child);
- return child;
- }
-
- /**
- * Allow close to be called multiple times.
- */
- @Override
- public void close() {
- internalClose();
- }
-
- public final <T> T newMBeanProxy(final ObjectName objectName, final Class<T> interfaceClass) {
- return JMX.newMBeanProxy(getMBeanServer(), objectName, interfaceClass);
- }
-
- public final <T> T newMBeanProxy(final ObjectName objectName, final Class<T> interfaceClass,
- final boolean notificationBroadcaster) {
- return JMX.newMBeanProxy(getMBeanServer(), objectName, interfaceClass, notificationBroadcaster);
- }
-
- public final <T> T newMXBeanProxy(final ObjectName objectName, final Class<T> interfaceClass) {
- return JMX.newMXBeanProxy(getMBeanServer(), objectName, interfaceClass);
- }
-
- public final <T> T newMXBeanProxy(final ObjectName objectName, final Class<T> interfaceClass,
- final boolean notificationBroadcaster) {
- return JMX.newMXBeanProxy(getMBeanServer(), objectName, interfaceClass, notificationBroadcaster);
- }
-
- public final Set<ObjectName> getRegisteredObjectNames() {
- return Collections.unmodifiableSet(registeredObjectNames);
- }
-
- public final Set<ObjectName> queryNames(final ObjectName name, final QueryExp query) {
- // keep only those that were registered using this instance
- return getSameNames(getMBeanServer().queryNames(name, query));
- }
-
- abstract MBeanServer getMBeanServer();
-
- synchronized void removeChild(final InternalJMXRegistrator child) {
- children.remove(child);
- }
-
- private synchronized void internalClose() {
- // close all children
- for (InternalJMXRegistrator child : children) {
- // This bypasses the call to removeChild(), preventing a potential deadlock when children are being closed
- // concurrently
- child.internalClose();
- }
- children.clear();
-
- // close registered ONs
- for (ObjectName on : registeredObjectNames) {
- try {
- getMBeanServer().unregisterMBean(on);
- } catch (final InstanceNotFoundException | MBeanRegistrationException e) {
- LOG.warn("Ignoring error while unregistering {}", on, e);
- }
- }
- registeredObjectNames.clear();
- }
-
- private synchronized Set<ObjectName> getSameNames(final Set<ObjectName> superSet) {
- final Set<ObjectName> result = new HashSet<>(superSet);
- result.retainAll(registeredObjectNames);
-
- for (InternalJMXRegistrator child : children) {
- result.addAll(child.getSameNames(superSet));
- }
- return result;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.NotCompliantMBeanException;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.api.jmx.notifications.ConfigJMXNotification;
-import org.opendaylight.controller.config.manager.impl.ConfigRegistryImplMXBean;
-
-/**
- * Thin wrapper over ConfigRegistry emitting JMX notifications.
- */
-public class JMXNotifierConfigRegistry implements ConfigRegistryImplMXBean, AutoCloseable {
-
- private final ConfigRegistryImplMXBean delegate;
- private final NotifierMXBeanImpl notifier;
- private final MBeanServer beanServer;
-
- public JMXNotifierConfigRegistry(final ConfigRegistryImplMXBean delegate, final MBeanServer beanServer) {
- this.delegate = delegate;
- notifier = new NotifierMXBeanImpl();
- this.beanServer = beanServer;
- registerMBean(notifier, this.beanServer, ConfigJMXNotification.OBJECT_NAME);
- }
-
- private static void registerMBean(final Object instance, final MBeanServer mbs, final ObjectName on) {
- try {
- mbs.registerMBean(instance, on);
- } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
- throw new IllegalStateException("Unable to register " + instance + " as " + on, e);
- }
- }
-
- @Override
- public long getVersion() {
- return delegate.getVersion();
- }
-
- @Override
- public ObjectName beginConfig() {
- return delegate.beginConfig();
- }
-
- @Override
- public CommitStatus commitConfig(final ObjectName transactionControllerON)
- throws ConflictingVersionException, ValidationException {
- final CommitStatus commitStatus = delegate.commitConfig(transactionControllerON);
- notifier.notifyCommit(ObjectNameUtil.getTransactionName(transactionControllerON));
- return commitStatus;
- }
-
- @Override
- public List<ObjectName> getOpenConfigs() {
- return delegate.getOpenConfigs();
- }
-
- @Override
- public boolean isHealthy() {
- return delegate.isHealthy();
- }
-
- @Override
- public Set<String> getAvailableModuleNames() {
- return delegate.getAvailableModuleNames();
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans() {
- return delegate.lookupConfigBeans();
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName) {
- return delegate.lookupConfigBeans(moduleName);
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
- return delegate.lookupConfigBeans(moduleName, instanceName);
- }
-
- @Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- return delegate.lookupConfigBean(moduleName, instanceName);
- }
-
- @Override
- public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
- delegate.checkConfigBeanExists(objectName);
- }
-
- @Override
- public Set<String> getAvailableModuleFactoryQNames() {
- return delegate.getAvailableModuleFactoryQNames();
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans() {
- return delegate.lookupRuntimeBeans();
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
- return delegate.lookupRuntimeBeans(moduleName, instanceName);
- }
-
- @Override
- public ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
- return delegate.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
- }
-
- @Override
- public Map<String, Map<String, ObjectName>> getServiceMapping() {
- return delegate.getServiceMapping();
- }
-
- @Override
- public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
- return delegate.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
- }
-
- @Override
- public Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
- return delegate.lookupServiceInterfaceNames(objectName);
- }
-
- @Override
- public String getServiceInterfaceName(final String namespace, final String localName) {
- return delegate.getServiceInterfaceName(namespace, localName);
- }
-
- @Override
- public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName)
- throws InstanceNotFoundException {
- return delegate.getServiceReference(serviceInterfaceQName, refName);
- }
-
- @Override
- public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
- delegate.checkServiceReferenceExists(objectName);
- }
-
- @Override
- public void close() {
- try {
- beanServer.unregisterMBean(ConfigJMXNotification.OBJECT_NAME);
- } catch (InstanceNotFoundException | MBeanRegistrationException e) {
- throw new IllegalStateException(
- "Notifier: " + ConfigJMXNotification.OBJECT_NAME + " not found in JMX when closing", e);
- }
- }
-
- public interface NotifierMXBean {
- }
-
- public static class NotifierMXBeanImpl extends NotificationBroadcasterSupport implements NotifierMXBean {
-
- private void notifyCommit(final String transactionName) {
- sendNotification(ConfigJMXNotification.afterCommit(this, "commit success " + transactionName));
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import com.google.common.base.Preconditions;
-import java.io.Closeable;
-import javax.annotation.concurrent.ThreadSafe;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-/**
- * This subclass is used for registering readable module into JMX, it is also
- * used as underlying provider in RuntimeBeanRegistratorImpl. Closing
- * the instance thus unregisters all JMX beans related to the module excluding
- * currently open transactions.
- */
-@ThreadSafe
-public class ModuleJMXRegistrator implements Closeable {
- private final InternalJMXRegistrator childJMXRegistrator;
-
- ModuleJMXRegistrator(final InternalJMXRegistrator internalJMXRegistrator) {
- this.childJMXRegistrator = Preconditions.checkNotNull(internalJMXRegistrator);
- }
-
- static class ModuleJMXRegistration implements AutoCloseable {
- private final InternalJMXRegistration internalJMXRegistration;
-
- ModuleJMXRegistration(final InternalJMXRegistration registration) {
- this.internalJMXRegistration = registration;
- }
-
- @Override
- public void close() {
- internalJMXRegistration.close();
- }
- }
-
- public ModuleJMXRegistration registerMBean(final Object object, final ObjectName on)
- throws InstanceAlreadyExistsException {
- ObjectNameUtil.checkType(on, ObjectNameUtil.TYPE_MODULE);
- if (ObjectNameUtil.getTransactionName(on) != null) {
- throw new IllegalArgumentException(
- "Transaction name not expected in " + on);
- }
- return new ModuleJMXRegistration(childJMXRegistrator.registerMBean(
- object, on));
- }
-
- @Override
- public void close() {
- childJMXRegistrator.close();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-public interface NestableJMXRegistrator {
-
- InternalJMXRegistrator createChild();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import com.google.common.base.Preconditions;
-import java.util.Collections;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
-import org.opendaylight.controller.config.api.runtime.RuntimeBean;
-
-public class RootRuntimeBeanRegistratorImpl implements RootRuntimeBeanRegistrator {
- private final InternalJMXRegistrator internalJMXRegistrator;
- private final ModuleIdentifier moduleIdentifier;
- private final ObjectName defaultRuntimeON;
-
- RootRuntimeBeanRegistratorImpl(final InternalJMXRegistrator internalJMXRegistrator,
- final ModuleIdentifier moduleIdentifier) {
- this.internalJMXRegistrator = Preconditions.checkNotNull(internalJMXRegistrator);
- this.moduleIdentifier = moduleIdentifier;
- defaultRuntimeON = ObjectNameUtil.createRuntimeBeanName(moduleIdentifier.getFactoryName(),
- moduleIdentifier.getInstanceName(), Collections.<String, String>emptyMap());
- }
-
- @Override
- public HierarchicalRuntimeBeanRegistrationImpl registerRoot(final RuntimeBean mxBean) {
- try {
- internalJMXRegistrator.registerMBean(mxBean, defaultRuntimeON);
- } catch (final InstanceAlreadyExistsException e) {
- throw sanitize(e, moduleIdentifier, defaultRuntimeON);
- }
- return new HierarchicalRuntimeBeanRegistrationImpl(moduleIdentifier, internalJMXRegistrator,
- Collections.<String, String>emptyMap());
- }
-
- @Override
- public void close() {
- internalJMXRegistrator.close();
- }
-
- static IllegalStateException sanitize(final InstanceAlreadyExistsException exception,
- final ModuleIdentifier moduleIdentifier, final ObjectName on) {
- throw new IllegalStateException("Could not register runtime bean in " + moduleIdentifier + " under name " + on,
- exception);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-public class ServiceReference {
- private final String serviceInterfaceName;
- private final String refName;
-
- public ServiceReference(final String serviceInterfaceName, final String refName) {
- this.serviceInterfaceName = serviceInterfaceName;
- this.refName = refName;
- }
-
- public String getServiceInterfaceQName() {
- return serviceInterfaceName;
- }
-
- public String getRefName() {
- return refName;
- }
-
- @Override
- public boolean equals(final Object object) {
- if (this == object) {
- return true;
- }
- if (object == null || getClass() != object.getClass()) {
- return false;
- }
-
- ServiceReference that = (ServiceReference) object;
-
- if (!refName.equals(that.refName)) {
- return false;
- }
- if (!serviceInterfaceName.equals(that.serviceInterfaceName)) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = serviceInterfaceName.hashCode();
- result = 31 * result + refName.hashCode();
- return result;
- }
-
- @Override
- public String toString() {
- return "ServiceReference{" + "serviceInterfaceName='" + serviceInterfaceName + '\'' + ", refName='" + refName
- + '\'' + '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean;
-
-public class ServiceReferenceMXBeanImpl implements ServiceReferenceMXBean {
- private ObjectName currentImplementation;
-
- public ServiceReferenceMXBeanImpl(final ObjectName currentImplementation) {
- this.currentImplementation = currentImplementation;
- }
-
- @Override
- public ObjectName getCurrentImplementation() {
- return currentImplementation;
- }
-
- public void setCurrentImplementation(final ObjectName currentImplementation) {
- this.currentImplementation = currentImplementation;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-public interface ServiceReferenceRegistrator extends AutoCloseable {
-
- String getNullableTransactionName();
-
- ServiceReferenceJMXRegistration registerMBean(ServiceReferenceMXBeanImpl object, ObjectName on)
- throws InstanceAlreadyExistsException;
-
- @Override
- void close();
-
- class ServiceReferenceJMXRegistration implements AutoCloseable {
- private final InternalJMXRegistration registration;
-
- ServiceReferenceJMXRegistration(final InternalJMXRegistration registration) {
- this.registration = registration;
- }
-
- @Override
- public void close() {
- registration.close();
- }
- }
-
- interface ServiceReferenceTransactionRegistratorFactory {
- ServiceReferenceRegistrator create();
- }
-
- class ServiceReferenceRegistratorImpl implements ServiceReferenceRegistrator {
- private final InternalJMXRegistrator currentJMXRegistrator;
- private final String nullableTransactionName;
-
- public ServiceReferenceRegistratorImpl(final NestableJMXRegistrator parentRegistrator,
- final String nullableTransactionName) {
- currentJMXRegistrator = parentRegistrator.createChild();
- this.nullableTransactionName = nullableTransactionName;
- }
-
- @Override
- public String getNullableTransactionName() {
- return nullableTransactionName;
- }
-
- @Override
- public ServiceReferenceJMXRegistration registerMBean(final ServiceReferenceMXBeanImpl object,
- final ObjectName on) throws InstanceAlreadyExistsException {
- String actualTransactionName = ObjectNameUtil.getTransactionName(on);
- boolean broken = false;
- broken |= nullableTransactionName == null != (actualTransactionName == null);
- broken |= nullableTransactionName != null && !nullableTransactionName.equals(actualTransactionName);
- if (broken) {
- throw new IllegalArgumentException("Transaction name mismatch between expected "
- + nullableTransactionName + ", got " + actualTransactionName + " in " + on);
- }
- if (!ObjectNameUtil.isServiceReference(on)) {
- throw new IllegalArgumentException("Invalid type of " + on);
- }
- return new ServiceReferenceJMXRegistration(currentJMXRegistrator.registerMBean(object, on));
- }
-
- @Override
- public void close() {
- currentJMXRegistrator.close();
- }
-
- public interface ServiceReferenceTransactionRegistratorFactory {
- ServiceReferenceRegistrator create();
- }
- }
-
- class ServiceReferenceTransactionRegistratorFactoryImpl implements ServiceReferenceTransactionRegistratorFactory {
- private final NestableJMXRegistrator parentRegistrator;
- private final String nullableTransactionName;
-
- public ServiceReferenceTransactionRegistratorFactoryImpl(
- final TransactionModuleJMXRegistrator parentRegistrator, final String nullableTransactionName) {
- this.parentRegistrator = parentRegistrator;
- this.nullableTransactionName = nullableTransactionName;
- }
-
- public ServiceReferenceTransactionRegistratorFactoryImpl(final BaseJMXRegistrator baseJMXRegistrator) {
- this.parentRegistrator = baseJMXRegistrator;
- this.nullableTransactionName = null;
- }
-
- @Override
- public ServiceReferenceRegistrator create() {
- return new ServiceReferenceRegistratorImpl(parentRegistrator, nullableTransactionName);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import com.google.common.base.Preconditions;
-import java.io.Closeable;
-import java.util.Set;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-import javax.management.QueryExp;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-/**
- * Contains constraints on passed {@link ObjectName} parameters. Only allow (un)
- * registration of ObjectNames that have expected transaction name.
- */
-public class TransactionJMXRegistrator implements Closeable {
- private final InternalJMXRegistrator childJMXRegistrator;
- private final String transactionName;
-
- TransactionJMXRegistrator(final InternalJMXRegistrator internalJMXRegistrator,
- final String transactionName) {
- this.childJMXRegistrator = Preconditions.checkNotNull(internalJMXRegistrator);
- this.transactionName = transactionName;
- }
-
- public static class TransactionJMXRegistration implements AutoCloseable {
- private final InternalJMXRegistration registration;
-
- TransactionJMXRegistration(final InternalJMXRegistration registration) {
- this.registration = registration;
- }
-
- @Override
- public void close() {
- registration.close();
- }
- }
-
- public TransactionJMXRegistration registerMBean(final Object object, final ObjectName on)
- throws InstanceAlreadyExistsException {
- if (!transactionName.equals(ObjectNameUtil.getTransactionName(on))) {
- throw new IllegalArgumentException(
- "Transaction name mismatch between expected "
- + transactionName + " " + "and " + on);
- }
- ObjectNameUtil.checkType(on, ObjectNameUtil.TYPE_CONFIG_TRANSACTION);
- return new TransactionJMXRegistration(
- childJMXRegistrator.registerMBean(object, on));
- }
-
- public Set<ObjectName> queryNames(final ObjectName name, final QueryExp query) {
- return childJMXRegistrator.queryNames(name, query);
- }
-
- public TransactionModuleJMXRegistrator createTransactionModuleJMXRegistrator() {
- return new TransactionModuleJMXRegistrator(childJMXRegistrator,
- transactionName);
- }
-
- @Override
- public void close() {
- // closes also all child TransactionModuleJMXRegistrator instances
- childJMXRegistrator.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.jmx;
-
-import java.io.Closeable;
-import java.util.Set;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-import javax.management.QueryExp;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-public class TransactionModuleJMXRegistrator implements Closeable, NestableJMXRegistrator {
- private final InternalJMXRegistrator currentJMXRegistrator;
- private final String transactionName;
-
- public TransactionModuleJMXRegistrator(
- final InternalJMXRegistrator internalJMXRegistrator,
- final String transactionName) {
- this.currentJMXRegistrator = internalJMXRegistrator.createChild();
- this.transactionName = transactionName;
- }
-
- public static class TransactionModuleJMXRegistration implements
- AutoCloseable {
- private final InternalJMXRegistration registration;
-
- TransactionModuleJMXRegistration(final InternalJMXRegistration registration) {
- this.registration = registration;
- }
-
- @Override
- public void close() {
- registration.close();
- }
- }
-
- public TransactionModuleJMXRegistration registerMBean(final Object object,
- final ObjectName on) throws InstanceAlreadyExistsException {
- if (!transactionName.equals(ObjectNameUtil.getTransactionName(on))) {
- throw new IllegalArgumentException("Transaction name mismatch between expected "
- + transactionName + " " + "and " + on);
- }
- ObjectNameUtil.checkTypeOneOf(on, ObjectNameUtil.TYPE_MODULE);
- return new TransactionModuleJMXRegistration(
- currentJMXRegistrator.registerMBean(object, on));
- }
-
- public Set<ObjectName> queryNames(final ObjectName name, final QueryExp query) {
- return currentJMXRegistrator.queryNames(name, query);
- }
-
- @Override
- public void close() {
- currentJMXRegistrator.close();
- }
-
- public String getTransactionName() {
- return transactionName;
- }
-
- @Override
- public InternalJMXRegistrator createChild() {
- return currentJMXRegistrator.createChild();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.osgi;
-
-import com.google.common.base.Preconditions;
-import java.util.Dictionary;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import javax.annotation.concurrent.GuardedBy;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Registers instantiated beans as OSGi services and unregisters these services
- * if beans are destroyed.
- */
-public class BeanToOsgiServiceManager {
- private static final String SERVICE_NAME_OSGI_PROP = "name";
-
- /**
- * To be called for every created, reconfigured and recreated config bean. It is
- * expected that before using this method OSGi service registry will be cleaned
- * from previous registrations.
- *
- * @param instance instance
- * @param moduleIdentifier module identifier
- * @param bundleContext bundle context
- * @param serviceNamesToAnnotations service names annotations
- * @return OSGI registration
- */
- public OsgiRegistration registerToOsgi(final AutoCloseable instance, final ModuleIdentifier moduleIdentifier,
- final BundleContext bundleContext,
- final Map<ServiceInterfaceAnnotation, String> serviceNamesToAnnotations) {
- return new OsgiRegistration(instance, moduleIdentifier, bundleContext, serviceNamesToAnnotations);
- }
-
- public static class OsgiRegistration implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(OsgiRegistration.class);
-
- @GuardedBy("this")
- private AutoCloseable instance;
- private final ModuleIdentifier moduleIdentifier;
- @GuardedBy("this")
- private final Set<ServiceRegistration<?>> serviceRegistrations;
- @GuardedBy("this")
- private final Map<ServiceInterfaceAnnotation, String> serviceNamesToAnnotations;
-
- public OsgiRegistration(final AutoCloseable instance, final ModuleIdentifier moduleIdentifier,
- final BundleContext bundleContext,
- final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
- this.instance = instance;
- this.moduleIdentifier = moduleIdentifier;
- this.serviceNamesToAnnotations = serviceNamesToAnnotations;
- this.serviceRegistrations = registerToSR(instance, bundleContext, serviceNamesToAnnotations);
- }
-
- private static Set<ServiceRegistration<?>> registerToSR(final AutoCloseable instance,
- final BundleContext bundleContext,
- final Map<ServiceInterfaceAnnotation, String /* service ref name */> serviceNamesToAnnotations) {
- Set<ServiceRegistration<?>> serviceRegistrations = new HashSet<>();
- for (Entry<ServiceInterfaceAnnotation, String /* service ref name */> entry : serviceNamesToAnnotations
- .entrySet()) {
- ServiceInterfaceAnnotation annotation = entry.getKey();
- Class<?> requiredInterface = annotation.osgiRegistrationType();
-
- if (!annotation.registerToOsgi()) {
- LOG.debug("registerToOsgi for service interface {} is false - not registering", requiredInterface);
- continue;
- }
-
- Preconditions.checkState(requiredInterface.isInstance(instance),
- instance.getClass().getName() + " instance should implement " + requiredInterface.getName());
- Dictionary<String, String> propertiesForOsgi = createProps(entry.getValue());
- ServiceRegistration<?> serviceRegistration = bundleContext.registerService(requiredInterface.getName(),
- instance, propertiesForOsgi);
- serviceRegistrations.add(serviceRegistration);
- }
- return serviceRegistrations;
- }
-
- @Override
- public synchronized void close() {
- for (ServiceRegistration<?> serviceRegistration : serviceRegistrations) {
- try {
- serviceRegistration.unregister();
- } catch (final IllegalStateException e) {
- LOG.trace("Cannot unregister {}", serviceRegistration, e);
- }
- }
- serviceRegistrations.clear();
- }
-
- public synchronized void updateRegistrations(
- final Map<ServiceInterfaceAnnotation, String /* service ref name */> newAnnotationMapping,
- final BundleContext bundleContext, final AutoCloseable newInstance) {
- boolean notEquals = !this.instance.equals(newInstance);
- notEquals |= !newAnnotationMapping.equals(serviceNamesToAnnotations);
- if (notEquals) {
- // FIXME: changing from old state to new state can be improved by computing the
- // diff
- LOG.debug("Detected change in service registrations for {}: old: {}, new: {}", moduleIdentifier,
- serviceNamesToAnnotations, newAnnotationMapping);
- close();
- this.instance = newInstance;
- Set<ServiceRegistration<?>> newRegs = registerToSR(instance, bundleContext, newAnnotationMapping);
- serviceRegistrations.clear();
- serviceRegistrations.addAll(newRegs);
- }
- }
-
- private static Dictionary<String, String> createProps(final String serviceName) {
- Hashtable<String, String> result = new Hashtable<>();
- result.put(SERVICE_NAME_OSGI_PROP, serviceName);
- return result;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.osgi;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.ServiceReference;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Every time factory is added or removed, blank transaction is triggered to
- * handle.
- */
-public class BlankTransactionServiceTracker implements ServiceTrackerCustomizer<ModuleFactory, Object> {
- private static final Logger LOG = LoggerFactory.getLogger(BlankTransactionServiceTracker.class);
-
- public static final int DEFAULT_MAX_ATTEMPTS = 10;
-
- private final BlankTransaction blankTransaction;
- private final ExecutorService txExecutor;
- private final int maxAttempts;
-
- public BlankTransactionServiceTracker(final ConfigRegistryImpl configRegistry) {
- this(() -> {
- ObjectName tx = configRegistry.beginConfig(true);
- return configRegistry.commitConfig(tx);
- });
- }
-
- public BlankTransactionServiceTracker(final BlankTransaction blankTransaction) {
- this(blankTransaction, DEFAULT_MAX_ATTEMPTS, Executors
- .newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("config-blank-txn-%d").build()));
- }
-
- @VisibleForTesting
- BlankTransactionServiceTracker(final BlankTransaction blankTx, final int maxAttempts,
- final ExecutorService txExecutor) {
- this.blankTransaction = blankTx;
- this.maxAttempts = maxAttempts;
- this.txExecutor = txExecutor;
- }
-
- @Override
- public Object addingService(final ServiceReference<ModuleFactory> moduleFactoryServiceReference) {
- blankTransactionAsync();
- return null;
- }
-
- private void blankTransactionAsync() {
- txExecutor.execute(this::blankTransactionSync);
- }
-
- void blankTransactionSync() {
- // race condition check: config-persister might push new configuration while
- // server is starting up.
- ConflictingVersionException lastException = null;
- for (int i = 0; i < maxAttempts; i++) {
- try {
- // create transaction
- CommitStatus commitStatus = blankTransaction.hit();
- LOG.debug("Committed blank transaction with status {}", commitStatus);
- return;
- } catch (final ConflictingVersionException e) {
- lastException = e;
- try {
- Thread.sleep(1000);
- } catch (final InterruptedException interruptedException) {
- Thread.currentThread().interrupt();
- LOG.debug("blankTransactionSync was interrupted");
- return;
- }
- } catch (final ValidationException e) {
- LOG.error("Validation exception while running blank transaction indicates programming error", e);
- }
- }
-
- LOG.error("Maximal number of attempts reached and still cannot get optimistic lock from config manager",
- lastException);
- }
-
- @Override
- public void modifiedService(final ServiceReference<ModuleFactory> moduleFactoryServiceReference,
- final Object object) {
- blankTransactionAsync();
- }
-
- @Override
- public void removedService(final ServiceReference<ModuleFactory> moduleFactoryServiceReference,
- final Object object) {
- blankTransactionAsync();
- }
-
- @VisibleForTesting
- interface BlankTransaction {
- CommitStatus hit() throws ValidationException, ConflictingVersionException;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.osgi;
-
-import java.util.AbstractMap;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Retrieves list of currently registered Module Factories using bundlecontext.
- */
-public class BundleContextBackedModuleFactoriesResolver implements ModuleFactoriesResolver {
- private static final Logger LOG = LoggerFactory.getLogger(BundleContextBackedModuleFactoriesResolver.class);
- private final BundleContext bundleContext;
-
- public BundleContextBackedModuleFactoriesResolver(final BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-
- @Override
- public Map<String, Map.Entry<ModuleFactory, BundleContext>> getAllFactories() {
- Collection<ServiceReference<ModuleFactory>> serviceReferences;
- try {
- serviceReferences = bundleContext.getServiceReferences(ModuleFactory.class, null);
- } catch (final InvalidSyntaxException e) {
- throw new IllegalStateException(e);
- }
- Map<String, Map.Entry<ModuleFactory, BundleContext>> result = new HashMap<>(serviceReferences.size());
- for (ServiceReference<ModuleFactory> serviceReference : serviceReferences) {
- ModuleFactory factory = bundleContext.getService(serviceReference);
- // null if the service is not registered, the service object
- // returned by a ServiceFactory does not
- // implement the classes under which it was registered or the
- // ServiceFactory threw an exception.
- if (factory == null) {
- throw new NullPointerException(
- "ServiceReference of class" + serviceReference.getClass() + "not found.");
- }
-
- String moduleName = factory.getImplementationName();
- if (moduleName == null || moduleName.isEmpty()) {
- throw new IllegalStateException("Invalid implementation name for " + factory);
- }
- if (serviceReference.getBundle() == null || serviceReference.getBundle().getBundleContext() == null) {
- throw new NullPointerException("Bundle context of " + factory + " ModuleFactory not found.");
- }
- LOG.debug("Reading factory {} {}", moduleName, factory);
-
- Map.Entry<ModuleFactory, BundleContext> conflicting = result.get(moduleName);
- if (conflicting != null) {
- String error = String.format(
- "Module name is not unique. Found two conflicting factories with same name '%s': '%s' '%s'",
- moduleName, conflicting.getKey(), factory);
- LOG.error(error);
- throw new IllegalArgumentException(error);
- }
-
- result.put(moduleName,
- new AbstractMap.SimpleImmutableEntry<>(factory, serviceReference.getBundle().getBundleContext()));
- }
- return result;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.osgi;
-
-import java.lang.management.ManagementFactory;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.MBeanServer;
-import org.opendaylight.controller.config.api.ConfigRegistry;
-import org.opendaylight.controller.config.api.ConfigSystemService;
-import org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl;
-import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.JMXNotifierConfigRegistry;
-import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
-import org.opendaylight.controller.config.manager.impl.osgi.mapping.ModuleInfoBundleTracker;
-import org.opendaylight.controller.config.manager.impl.osgi.mapping.RefreshingSCPModuleInfoRegistry;
-import org.opendaylight.controller.config.manager.impl.util.OsgiRegistrationUtil;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
-import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
-import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.SynchronousBundleListener;
-import org.osgi.util.tracker.BundleTracker;
-import org.osgi.util.tracker.ServiceTracker;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConfigManagerActivator implements BundleActivator, SynchronousBundleListener, ConfigSystemService {
-
- private static final Logger LOG = LoggerFactory.getLogger(ConfigManagerActivator.class);
-
- private static final long SYSTEM_BUNDLE_ID = 0;
-
- private final MBeanServer configMBeanServer = ManagementFactory.getPlatformMBeanServer();
-
- private AutoCloseable autoCloseable;
-
- private ConfigRegistryImpl configRegistry;
-
- @Override
- public void start(final BundleContext context) {
- LOG.info("Config manager starting...");
- try {
- // the inner strategy is backed by thread context cl?
- final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
-
- final BindingContextProvider bindingContextProvider = new BindingContextProvider();
-
- final RefreshingSCPModuleInfoRegistry moduleInfoRegistryWrapper = new RefreshingSCPModuleInfoRegistry(
- moduleInfoBackedContext, moduleInfoBackedContext, moduleInfoBackedContext, moduleInfoBackedContext,
- bindingContextProvider, context);
-
- final ModuleInfoBundleTracker moduleInfoBundleTracker = new ModuleInfoBundleTracker(
- moduleInfoRegistryWrapper);
-
- // start config registry
- final BundleContextBackedModuleFactoriesResolver bundleContextBackedModuleFactoriesResolver =
- new BundleContextBackedModuleFactoriesResolver(context);
- this.configRegistry = new ConfigRegistryImpl(bundleContextBackedModuleFactoriesResolver,
- this.configMBeanServer, bindingContextProvider);
-
- // track bundles containing factories
- final BlankTransactionServiceTracker blankTransactionServiceTracker = new BlankTransactionServiceTracker(
- this.configRegistry);
- final ModuleFactoryBundleTracker moduleFactoryTracker = new ModuleFactoryBundleTracker(
- blankTransactionServiceTracker);
-
- BundleTracker<Collection<ObjectRegistration<YangModuleInfo>>> moduleInfoResolvedBundleTracker =
- new BundleTracker<>(context, Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING | Bundle.ACTIVE,
- moduleInfoBundleTracker);
- ExtensibleBundleTracker<?> moduleFactoryBundleTracker = new ExtensibleBundleTracker<>(context,
- moduleFactoryTracker);
- moduleInfoBundleTracker.open(moduleInfoResolvedBundleTracker);
-
- // start extensible tracker
- moduleFactoryBundleTracker.open();
-
- // Wrap config registry with JMX notification publishing adapter
- final JMXNotifierConfigRegistry notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry,
- this.configMBeanServer);
-
- // register config registry to OSGi
- final AutoCloseable clsReg = OsgiRegistrationUtil.registerService(context, moduleInfoBackedContext,
- ClassLoadingStrategy.class);
- final AutoCloseable configRegReg = OsgiRegistrationUtil.registerService(context, notifyingConfigRegistry,
- ConfigRegistry.class);
-
- // register config registry to jmx
- final ConfigRegistryJMXRegistrator configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(
- this.configMBeanServer);
- try {
- configRegistryJMXRegistrator.registerToJMXNoNotifications(this.configRegistry);
- } catch (final InstanceAlreadyExistsException e) {
- configRegistryJMXRegistrator.close();
- throw new IllegalStateException("Config Registry was already registered to JMX", e);
- }
-
- // register config registry to jmx
- final ConfigRegistryJMXRegistrator configRegistryJMXRegistratorWithNotifications =
- new ConfigRegistryJMXRegistrator(this.configMBeanServer);
- try {
- configRegistryJMXRegistrator.registerToJMX(notifyingConfigRegistry);
- } catch (final InstanceAlreadyExistsException e) {
- configRegistryJMXRegistrator.close();
- configRegistryJMXRegistratorWithNotifications.close();
- throw new IllegalStateException("Config Registry was already registered to JMX", e);
- }
-
- // TODO wire directly via moduleInfoBundleTracker
- final ServiceTracker<ModuleFactory, Object> serviceTracker = new ServiceTracker<>(context,
- ModuleFactory.class, blankTransactionServiceTracker);
- serviceTracker.open();
-
- final AutoCloseable configMgrReg = OsgiRegistrationUtil.registerService(context, this,
- ConfigSystemService.class);
-
- final List<AutoCloseable> list = Arrays.asList(bindingContextProvider, clsReg,
- OsgiRegistrationUtil.wrap(moduleFactoryBundleTracker), moduleInfoBundleTracker, configRegReg,
- configRegistryJMXRegistrator, configRegistryJMXRegistratorWithNotifications,
- OsgiRegistrationUtil.wrap(serviceTracker), moduleInfoRegistryWrapper, notifyingConfigRegistry,
- configMgrReg);
- this.autoCloseable = OsgiRegistrationUtil.aggregate(list);
-
- context.addBundleListener(this);
- } catch (final IllegalStateException e) {
- LOG.error("Error starting config manager", e);
- }
-
- LOG.info("Config manager start complete");
- }
-
- @Override
- public void stop(final BundleContext context) throws Exception {
- LOG.info("Config manager stopping");
- context.removeBundleListener(this);
- this.autoCloseable.close();
- }
-
- @Override
- public void bundleChanged(final BundleEvent event) {
- if (this.configRegistry == null) {
- return;
- }
-
- // If the system bundle (id 0) is stopping close the ConfigRegistry so it
- // destroys all modules. On
- // shutdown the system bundle is stopped first.
- if (event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) {
- this.configRegistry.close();
- }
- }
-
- @Override
- public void closeAllConfigModules() {
- if (this.configRegistry != null) {
- this.configRegistry.close();
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.osgi;
-
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.ThreadFactory;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.util.tracker.BundleTracker;
-import org.osgi.util.tracker.BundleTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Extensible bundle tracker. Takes several BundleTrackerCustomizers and
- * propagates bundle events to all of them.
- *
- * <p>
- * Primary customizer may return tracking object, which will be passed to it
- * during invocation of
- * {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)}
- *
- * <p>
- * This extender modifies behavior to not leak platform thread in
- * {@link BundleTrackerCustomizer#addingBundle(Bundle, BundleEvent)} but deliver
- * this event from its own single threaded executor.
- *
- * <p>
- * If bundle is removed before event for adding bundle was executed, that event
- * is cancelled. If addingBundle event is currently in progress or was already
- * executed, platform thread is block until addingBundle finishes so bundle
- * could be removed correctly in platform thread.
- *
- * <p>
- * Method
- * {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)} is
- * never invoked on registered trackers.
- *
- * @param <T> value
- */
-public final class ExtensibleBundleTracker<T> extends BundleTracker<Future<T>> {
- private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
- .setNameFormat("config-bundle-tracker-%d").build();
- private final ExecutorService eventExecutor;
- private final BundleTrackerCustomizer<T> primaryTracker;
- private final BundleTrackerCustomizer<?>[] additionalTrackers;
-
- private static final Logger LOG = LoggerFactory.getLogger(ExtensibleBundleTracker.class);
-
- public ExtensibleBundleTracker(final BundleContext context,
- final BundleTrackerCustomizer<T> primaryBundleTrackerCustomizer,
- final BundleTrackerCustomizer<?>... additionalBundleTrackerCustomizers) {
- this(context, Bundle.ACTIVE, primaryBundleTrackerCustomizer, additionalBundleTrackerCustomizers);
- }
-
- public ExtensibleBundleTracker(final BundleContext context, final int bundleState,
- final BundleTrackerCustomizer<T> primaryBundleTrackerCustomizer,
- final BundleTrackerCustomizer<?>... additionalBundleTrackerCustomizers) {
- super(context, bundleState, null);
- this.primaryTracker = primaryBundleTrackerCustomizer;
- this.additionalTrackers = additionalBundleTrackerCustomizers;
- eventExecutor = Executors.newSingleThreadExecutor(THREAD_FACTORY);
- LOG.trace("Registered as extender with context {} and bundle state {}", context, bundleState);
- }
-
- @Override
- public Future<T> addingBundle(final Bundle bundle, final BundleEvent event) {
- LOG.trace("Submiting AddingBundle for bundle {} and event {} to be processed asynchronously", bundle, event);
- return eventExecutor.submit(() -> {
- T primaryTrackerRetVal = primaryTracker.addingBundle(bundle, event);
-
- forEachAdditionalBundle(tracker -> tracker.addingBundle(bundle, event));
- LOG.trace("AddingBundle for {} and event {} finished successfully", bundle, event);
- return primaryTrackerRetVal;
- });
- }
-
- @Override
- public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Future<T> object) {
- // Intentionally NOOP
- }
-
- @Override
- public void removedBundle(final Bundle bundle, final BundleEvent event, final Future<T> object) {
- if (!object.isDone() && object.cancel(false)) {
- // We canceled adding event before it was processed
- // so it is safe to return
- LOG.trace("Adding Bundle event for {} was cancelled. No additional work required.", bundle);
- return;
- }
- try {
- LOG.trace("Invoking removedBundle event for {}", bundle);
- primaryTracker.removedBundle(bundle, event, object.get());
- forEachAdditionalBundle(tracker -> tracker.removedBundle(bundle, event, null));
- LOG.trace("Removed bundle event for {} finished successfully.", bundle);
- } catch (final ExecutionException | InterruptedException e) {
- LOG.error("Failed to remove bundle {}", bundle, e);
- }
- }
-
- private void forEachAdditionalBundle(final BundleStrategy lambda) {
- for (BundleTrackerCustomizer<?> trac : additionalTrackers) {
- lambda.execute(trac);
- }
- }
-
- private interface BundleStrategy {
- void execute(BundleTrackerCustomizer<?> tracker);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.osgi;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.io.Resources;
-import java.io.IOException;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.BundleTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * OSGi extender that listens for bundle activation events. Reads file
- * META-INF/services/org.opendaylight.controller.config.spi.ModuleFactory, each
- * line should contain an implementation of ModuleFactory interface. Creates new
- * instance with default constructor and registers it into OSGi service
- * registry. There is no need for listening for implementing removedBundle as
- * the services are unregistered automatically. Code based on
- * http://www.toedter.com/blog/?p=236
- */
-public class ModuleFactoryBundleTracker implements BundleTrackerCustomizer<Boolean> {
- private final BlankTransactionServiceTracker blankTransactionServiceTracker;
- private static final Logger LOG = LoggerFactory.getLogger(ModuleFactoryBundleTracker.class);
-
- public ModuleFactoryBundleTracker(final BlankTransactionServiceTracker blankTransactionServiceTracker) {
- this.blankTransactionServiceTracker = blankTransactionServiceTracker;
- }
-
- @Override
- public Boolean addingBundle(final Bundle bundle, final BundleEvent event) {
- URL resource = bundle.getEntry("META-INF/services/" + ModuleFactory.class.getName());
- LOG.trace("Got addingBundle event of bundle {}, resource {}, event {}", bundle, resource, event);
- if (resource != null) {
- try {
- for (String factoryClassName : Resources.readLines(resource, StandardCharsets.UTF_8)) {
- registerFactory(factoryClassName, bundle);
- }
-
- return Boolean.TRUE;
- } catch (final IOException e) {
- LOG.error("Error while reading {}", resource, e);
- throw new RuntimeException(e);
- }
- }
-
- return Boolean.FALSE;
- }
-
- @Override
- public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Boolean hasFactory) {
- // NOOP
- }
-
- @Override
- public void removedBundle(final Bundle bundle, final BundleEvent event, final Boolean hasFactory) {
- if (hasFactory) {
- // workaround for service tracker not getting removed service event
- blankTransactionServiceTracker.blankTransactionSync();
- }
- }
-
- @VisibleForTesting
- protected static ServiceRegistration<?> registerFactory(final String factoryClassName, final Bundle bundle) {
- String errorMessage;
- Exception ex = null;
- try {
- Class<?> clazz = bundle.loadClass(factoryClassName);
- if (ModuleFactory.class.isAssignableFrom(clazz)) {
- try {
- LOG.debug("Registering {} in bundle {}", clazz.getName(), bundle);
- return bundle.getBundleContext().registerService(ModuleFactory.class.getName(), clazz.newInstance(),
- null);
- } catch (final InstantiationException e) {
- errorMessage = logMessage("Could not instantiate {} in bundle {}, reason {}", factoryClassName,
- bundle, e);
- ex = e;
- } catch (final IllegalAccessException e) {
- errorMessage = logMessage("Illegal access during instantiation of class {} in bundle {}, reason {}",
- factoryClassName, bundle, e);
- ex = e;
- }
- } else {
- errorMessage = logMessage("Class {} does not implement {} in bundle {}", clazz, ModuleFactory.class,
- bundle);
- }
- } catch (final ClassNotFoundException e) {
- errorMessage = logMessage("Could not find class {} in bundle {}, reason {}", factoryClassName, bundle, e);
- ex = e;
- }
-
- throw ex == null ? new IllegalStateException(errorMessage) : new IllegalStateException(errorMessage, ex);
- }
-
- public static String logMessage(final String slfMessage, final Object... params) {
- LOG.info(slfMessage, params);
- String formatMessage = slfMessage.replaceAll("\\{\\}", "%s");
- return String.format(formatMessage, params);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.osgi.mapping;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
-import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-
-/**
- * Creates and initializes {@link BindingRuntimeContext}, which is used to
- * resolve Identity classes from QName. An instance of
- * {@link BindingRuntimeContext} is available only after first schema context
- * was successfully built.
- */
-// TODO move to yang runtime
-public class BindingContextProvider implements AutoCloseable {
-
- private BindingRuntimeContext current;
-
- public synchronized void update(final ClassLoadingStrategy classLoadingStrategy,
- final SchemaContextProvider ctxProvider) {
- this.current = BindingRuntimeContext.create(classLoadingStrategy, ctxProvider.getSchemaContext());
- }
-
- public synchronized BindingRuntimeContext getBindingContext() {
- Preconditions.checkState(this.current != null, "Binding context not yet initialized");
- return this.current;
- }
-
- @Override
- public synchronized void close() throws Exception {
- this.current = null;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.osgi.mapping;
-
-import com.google.common.io.Resources;
-import java.io.IOException;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
-import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
-import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleEvent;
-import org.osgi.util.tracker.BundleTracker;
-import org.osgi.util.tracker.BundleTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Tracks bundles and attempts to retrieve YangModuleInfo, which is then fed
- * into ModuleInfoRegistry.
- */
-public final class ModuleInfoBundleTracker
- implements AutoCloseable, BundleTrackerCustomizer<Collection<ObjectRegistration<YangModuleInfo>>> {
-
- private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBundleTracker.class);
-
- public static final String MODULE_INFO_PROVIDER_PATH_PREFIX = "META-INF/services/";
- private static final String YANG_MODULE_INFO_SERVICE_PATH = MODULE_INFO_PROVIDER_PATH_PREFIX
- + YangModelBindingProvider.class.getName();
-
- private final RefreshingSCPModuleInfoRegistry moduleInfoRegistry;
-
- private BundleTracker<Collection<ObjectRegistration<YangModuleInfo>>> tracker;
- private boolean starting;
-
- public ModuleInfoBundleTracker(final RefreshingSCPModuleInfoRegistry moduleInfoRegistry) {
- this.moduleInfoRegistry = moduleInfoRegistry;
- }
-
- public void open(final BundleTracker<Collection<ObjectRegistration<YangModuleInfo>>> bundleTracker) {
- LOG.debug("ModuleInfoBundleTracker open starting with bundleTracker {}", bundleTracker);
-
- if (bundleTracker != null) {
- this.tracker = bundleTracker;
- starting = true;
- bundleTracker.open();
-
- starting = false;
- moduleInfoRegistry.updateService();
- } else {
- starting = false;
- }
-
- LOG.debug("ModuleInfoBundleTracker open complete");
- }
-
- @Override
- public void close() {
- if (tracker != null) {
- tracker.close();
- tracker = null;
- }
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- public Collection<ObjectRegistration<YangModuleInfo>> addingBundle(final Bundle bundle, final BundleEvent event) {
- URL resource = bundle.getEntry(YANG_MODULE_INFO_SERVICE_PATH);
- LOG.debug("Got addingBundle({}) with YangModelBindingProvider resource {}", bundle, resource);
- if (resource == null) {
- return Collections.emptyList();
- }
- List<ObjectRegistration<YangModuleInfo>> registrations = new LinkedList<>();
-
- try {
- for (String moduleInfoName : Resources.readLines(resource, StandardCharsets.UTF_8)) {
- LOG.trace("Retrieve ModuleInfo({}, {})", moduleInfoName, bundle);
- YangModuleInfo moduleInfo = retrieveModuleInfo(moduleInfoName, bundle);
- registrations.add(moduleInfoRegistry.registerModuleInfo(moduleInfo));
- }
-
- if (!starting) {
- moduleInfoRegistry.updateService();
- }
- } catch (final IOException e) {
- LOG.error("Error while reading {} from bundle {}", resource, bundle, e);
- } catch (final RuntimeException e) {
- LOG.error("Failed to process {} for bundle {}", resource, bundle, e);
- }
-
- LOG.trace("Got following registrations {}", registrations);
- return registrations;
- }
-
- @Override
- public void modifiedBundle(final Bundle bundle, final BundleEvent event,
- final Collection<ObjectRegistration<YangModuleInfo>> object) {
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- public void removedBundle(final Bundle bundle, final BundleEvent event,
- final Collection<ObjectRegistration<YangModuleInfo>> regs) {
- if (regs == null) {
- return;
- }
-
- for (ObjectRegistration<YangModuleInfo> reg : regs) {
- try {
- reg.close();
- } catch (final Exception e) {
- LOG.error("Unable to unregister YangModuleInfo {}", reg.getInstance(), e);
- }
- }
- }
-
- private static YangModuleInfo retrieveModuleInfo(final String moduleInfoClass, final Bundle bundle) {
- String errorMessage;
- Class<?> clazz = loadClass(moduleInfoClass, bundle);
-
- if (!YangModelBindingProvider.class.isAssignableFrom(clazz)) {
- errorMessage = logMessage("Class {} does not implement {} in bundle {}", clazz,
- YangModelBindingProvider.class, bundle);
- throw new IllegalStateException(errorMessage);
- }
- final YangModelBindingProvider instance;
- try {
- Object instanceObj = clazz.newInstance();
- instance = YangModelBindingProvider.class.cast(instanceObj);
- } catch (final InstantiationException e) {
- errorMessage = logMessage("Could not instantiate {} in bundle {}, reason {}", moduleInfoClass, bundle, e);
- throw new IllegalStateException(errorMessage, e);
- } catch (final IllegalAccessException e) {
- errorMessage = logMessage("Illegal access during instantiation of class {} in bundle {}, reason {}",
- moduleInfoClass, bundle, e);
- throw new IllegalStateException(errorMessage, e);
- }
-
- try {
- return instance.getModuleInfo();
- } catch (NoClassDefFoundError | ExceptionInInitializerError e) {
- throw new IllegalStateException("Error while executing getModuleInfo on " + instance, e);
- }
- }
-
- private static Class<?> loadClass(final String moduleInfoClass, final Bundle bundle) {
- try {
- return bundle.loadClass(moduleInfoClass);
- } catch (final ClassNotFoundException e) {
- String errorMessage = logMessage("Could not find class {} in bundle {}, reason {}", moduleInfoClass, bundle,
- e);
- throw new IllegalStateException(errorMessage);
- }
- }
-
- public static String logMessage(final String slfMessage, final Object... params) {
- LOG.info(slfMessage, params);
- String formatMessage = slfMessage.replaceAll("\\{\\}", "%s");
- return String.format(formatMessage, params);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.impl.osgi.mapping;
-
-import java.util.Dictionary;
-import java.util.Hashtable;
-import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
-import org.opendaylight.mdsal.binding.generator.api.ModuleInfoRegistry;
-import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
-import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
-import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Update SchemaContext service in Service Registry each time new YangModuleInfo
- * is added or removed.
- */
-public class RefreshingSCPModuleInfoRegistry implements ModuleInfoRegistry, AutoCloseable {
- private final ModuleInfoRegistry moduleInfoRegistry;
- private final SchemaContextProvider schemaContextProvider;
- private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
- private final BindingContextProvider bindingContextProvider;
- private final ClassLoadingStrategy classLoadingStrat;
-
- private volatile ServiceRegistration<SchemaContextProvider> osgiReg;
-
- public RefreshingSCPModuleInfoRegistry(final ModuleInfoRegistry moduleInfoRegistry,
- final SchemaContextProvider schemaContextProvider, final ClassLoadingStrategy classLoadingStrat,
- final SchemaSourceProvider<YangTextSchemaSource> sourceProvider,
- final BindingContextProvider bindingContextProvider, final BundleContext bundleContext) {
-
- this.moduleInfoRegistry = moduleInfoRegistry;
- this.schemaContextProvider = schemaContextProvider;
- this.classLoadingStrat = classLoadingStrat;
- this.sourceProvider = sourceProvider;
- this.bindingContextProvider = bindingContextProvider;
- this.osgiReg = bundleContext.registerService(SchemaContextProvider.class, schemaContextProvider,
- new Hashtable<String, String>());
- }
-
- public synchronized void updateService() {
- if (this.osgiReg != null) {
- this.bindingContextProvider.update(this.classLoadingStrat, this.schemaContextProvider);
-
- final Dictionary<String, Object> props = new Hashtable<>();
- props.put(BindingRuntimeContext.class.getName(), this.bindingContextProvider.getBindingContext());
- props.put(SchemaSourceProvider.class.getName(), this.sourceProvider);
- // send modifiedService event
- this.osgiReg.setProperties(props);
- }
- }
-
- @Override
- public ObjectRegistration<YangModuleInfo> registerModuleInfo(final YangModuleInfo yangModuleInfo) {
- final ObjectRegistration<YangModuleInfo> yangModuleInfoObjectRegistration = this.moduleInfoRegistry
- .registerModuleInfo(yangModuleInfo);
- return new ObjectRegistrationWrapper(yangModuleInfoObjectRegistration);
- }
-
- @Override
- public synchronized void close() throws Exception {
- if (this.osgiReg != null) {
- this.osgiReg.unregister();
- }
-
- this.osgiReg = null;
- }
-
- private class ObjectRegistrationWrapper implements ObjectRegistration<YangModuleInfo> {
- private final ObjectRegistration<YangModuleInfo> inner;
-
- ObjectRegistrationWrapper(final ObjectRegistration<YangModuleInfo> inner) {
- this.inner = inner;
- }
-
- @Override
- public YangModuleInfo getInstance() {
- return this.inner.getInstance();
- }
-
- @Override
- public void close() {
- this.inner.close();
- // send modify event when a bundle disappears
- updateService();
- }
-
- @Override
- public String toString() {
- return this.inner.toString();
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.util;
-
-import com.google.common.collect.ImmutableSet;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-import javax.management.JMX;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-
-public final class InterfacesHelper {
-
- private InterfacesHelper() {
- }
-
- public static Set<Class<?>> getAllInterfaces(Class<?> clazz) {
- if (clazz.isInterface()) {
- throw new IllegalArgumentException(clazz + " should not be an interface");
- }
- // getInterfaces gets interfaces implemented directly by this class
- Set<Class<?>> toBeInspected = new HashSet<>();
- while (!clazz.equals(Object.class)) {
- toBeInspected.addAll(Arrays.asList(clazz.getInterfaces()));
- // get parent class
- clazz = clazz.getSuperclass();
- }
- return getAllSuperInterfaces(toBeInspected);
-
- }
-
- private static Set<Class<?>> getAllSuperInterfaces(final Set<? extends Class<?>> ifcs) {
- Set<Class<?>> interfaces = new HashSet<>(ifcs); // create copy to modify
- // each interface can extend other interfaces
- Set<Class<?>> result = new HashSet<>();
- while (!interfaces.isEmpty()) {
- Iterator<Class<?>> iterator = interfaces.iterator();
- Class<?> ifc = iterator.next();
- iterator.remove();
- if (!ifc.isInterface()) {
- throw new IllegalArgumentException(ifc + " should be an interface");
- }
- interfaces.addAll(Arrays.asList(ifc.getInterfaces()));
- result.add(ifc);
- }
- return result;
- }
-
- /**
- * Get interfaces that this class is derived from that are JMX interfaces.
- *
- * @param configBeanClass
- * config bean class
- * @return set containing classes
- */
- public static Set<Class<?>> getMXInterfaces(final Class<? extends Module> configBeanClass) {
- Set<Class<?>> allInterfaces = getAllInterfaces(configBeanClass);
- Set<Class<?>> result = new HashSet<>();
- for (Class<?> clazz : allInterfaces) {
- if (JMX.isMXBeanInterface(clazz)) {
- result.add(clazz);
- }
- }
- return result;
- }
-
- /**
- * Get all implemented interfaces that have
- * {@link org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation}
- * annotation.
- *
- * @param configBeanClass
- * config bean class
- * @return set containing classes
- */
- public static Set<Class<?>> getServiceInterfaces(final Class<? extends Module> configBeanClass) {
- Set<Class<?>> allInterfaces = getAllInterfaces(configBeanClass);
- Set<Class<?>> result = new HashSet<>();
- for (Class<?> clazz : allInterfaces) {
- if (AbstractServiceInterface.class.isAssignableFrom(clazz)) {
- ServiceInterfaceAnnotation annotation = clazz.getAnnotation(ServiceInterfaceAnnotation.class);
- if (annotation != null) {
- result.add(clazz);
- }
- }
- }
- return result;
- }
-
- public static Set<Class<? extends AbstractServiceInterface>> getAllAbstractServiceClasses(
- final Class<? extends Module> configBeanClass) {
-
- Set<Class<? extends AbstractServiceInterface>> foundGeneratedSIClasses = new HashSet<>();
- for (Class<?> clazz : getAllInterfaces(configBeanClass)) {
- if (AbstractServiceInterface.class.isAssignableFrom(clazz)
- && !AbstractServiceInterface.class.equals(clazz)) {
- foundGeneratedSIClasses.add((Class<? extends AbstractServiceInterface>) clazz);
- }
- }
- return getAllAbstractServiceInterfaceClasses(foundGeneratedSIClasses);
- }
-
- /**
- * Get OSGi registration types under which config bean instance should be
- * registered. This is specified in
- * {@link org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation#osgiRegistrationType()}
- *
- * @param configBeanClass config bean class
- * @return set of classes
- */
- public static Set<Class<?>> getOsgiRegistrationTypes(final Class<? extends Module> configBeanClass) {
- Set<Class<?>> serviceInterfaces = getServiceInterfaces(configBeanClass);
- Set<Class<?>> result = new HashSet<>();
- for (Class<?> clazz : serviceInterfaces) {
- ServiceInterfaceAnnotation annotation = clazz.getAnnotation(ServiceInterfaceAnnotation.class);
- result.add(annotation.osgiRegistrationType());
- }
- return result;
- }
-
- public static Set<String> getQNames(final Set<ServiceInterfaceAnnotation> siAnnotations) {
- Set<String> names = new HashSet<>();
- for (ServiceInterfaceAnnotation sia : siAnnotations) {
- names.add(sia.value());
- }
- return ImmutableSet.copyOf(names);
- }
-
- public static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(final ModuleFactory factory) {
- Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces = Collections
- .unmodifiableSet(factory.getImplementedServiceIntefaces());
- return getServiceInterfaceAnnotations(implementedServiceIntefaces);
- }
-
- private static Set<ServiceInterfaceAnnotation> getServiceInterfaceAnnotations(
- final Set<Class<? extends AbstractServiceInterface>> implementedServiceIntefaces) {
- Set<Class<? extends AbstractServiceInterface>> inspected = getAllAbstractServiceInterfaceClasses(
- implementedServiceIntefaces);
- Set<ServiceInterfaceAnnotation> result = new HashSet<>();
- // SIs can form hierarchies, inspect superclass until it does not extend
- // AbstractSI
- for (Class<?> clazz : inspected) {
- ServiceInterfaceAnnotation annotation = clazz.getAnnotation(ServiceInterfaceAnnotation.class);
- if (annotation != null) {
- result.add(annotation);
- }
- }
- return Collections.unmodifiableSet(result);
- }
-
- static Set<Class<? extends AbstractServiceInterface>> getAllAbstractServiceInterfaceClasses(
- final Set<Class<? extends AbstractServiceInterface>> directlyImplementedAbstractSIs) {
-
- Set<Class<?>> allInterfaces = getAllSuperInterfaces(directlyImplementedAbstractSIs);
- Set<Class<? extends AbstractServiceInterface>> result = new HashSet<>();
- for (Class<?> ifc : allInterfaces) {
- if (AbstractServiceInterface.class.isAssignableFrom(ifc) && !ifc.equals(AbstractServiceInterface.class)) {
- result.add((Class<? extends AbstractServiceInterface>) ifc);
- }
- }
- return result;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.util;
-
-import java.util.Set;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.LookupRegistry;
-
-public final class LookupBeansUtil {
-
- private LookupBeansUtil() {
- }
-
- public static ObjectName lookupConfigBean(final LookupRegistry lookupRegistry,
- final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- Set<ObjectName> objectNames = lookupRegistry.lookupConfigBeans(
- moduleName, instanceName);
- if (objectNames.isEmpty()) {
- throw new InstanceNotFoundException("No instance found");
- } else if (objectNames.size() > 1) {
- throw new InstanceNotFoundException("Too many instances found");
- }
- return objectNames.iterator().next();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.util;
-
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.yangtools.yang.binding.annotations.ModuleQName;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.osgi.framework.BundleContext;
-
-public final class ModuleQNameUtil {
-
- private ModuleQNameUtil() {
- }
-
- public static Set<String> getQNames(final Map<String, Entry<ModuleFactory, BundleContext>> resolved) {
- final Set<String> result = new HashSet<>();
- for (final Entry<ModuleFactory, BundleContext> entry : resolved.values()) {
- Class<?> inspected = entry.getKey().getClass();
- if (inspected.isInterface()) {
- throw new IllegalArgumentException("Unexpected interface " + inspected);
- }
- ModuleQName annotation = null;
- while (annotation == null && inspected != null) {
- annotation = inspected.getAnnotation(ModuleQName.class);
- inspected = inspected.getSuperclass();
- }
- if (annotation != null) {
- result.add(QName.create(annotation.namespace(), annotation.revision(), annotation.name()).toString());
- }
- }
- return result;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.impl.util;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.ListIterator;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.BundleTracker;
-import org.osgi.util.tracker.ServiceTracker;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class OsgiRegistrationUtil {
- private static final Logger LOG = LoggerFactory.getLogger(OsgiRegistrationUtil.class);
-
- private OsgiRegistrationUtil() {
- }
-
- @SafeVarargs
- public static <T> AutoCloseable registerService(final BundleContext bundleContext, final T service,
- final Class<? super T>... interfaces) {
- checkNotNull(service);
- checkNotNull(interfaces);
- List<AutoCloseable> autoCloseableList = new ArrayList<>();
- for (Class<? super T> ifc : interfaces) {
- ServiceRegistration<? super T> serviceRegistration = bundleContext.registerService(ifc, service, null);
- autoCloseableList.add(wrap(serviceRegistration));
- }
- return aggregate(autoCloseableList);
- }
-
- public static AutoCloseable wrap(final ServiceRegistration<?> reg) {
- checkNotNull(reg);
- return reg::unregister;
- }
-
- public static AutoCloseable wrap(final BundleTracker<?> bundleTracker) {
- checkNotNull(bundleTracker);
- return bundleTracker::close;
- }
-
- public static AutoCloseable wrap(final ServiceTracker<?, ?> serviceTracker) {
- checkNotNull(serviceTracker);
- return serviceTracker::close;
- }
-
- @SuppressWarnings("IllegalCatch")
- public static AutoCloseable aggregate(final List<? extends AutoCloseable> list) {
- checkNotNull(list);
-
- return () -> {
- Exception firstException = null;
- for (ListIterator<? extends AutoCloseable> it = list.listIterator(list.size()); it.hasPrevious();) {
- AutoCloseable ac = it.previous();
- try {
- ac.close();
- } catch (final Exception e) {
- LOG.warn("Exception while closing {}", ac, e);
- if (firstException == null) {
- firstException = e;
- } else {
- firstException.addSuppressed(e);
- }
- }
- }
- if (firstException != null) {
- throw firstException;
- }
- };
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verifyZeroInteractions;
-
-import java.lang.management.ManagementFactory;
-import org.junit.Test;
-import org.opendaylight.controller.config.manager.impl.AbstractLockedPlatformMBeanServerTest;
-import org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConfigRegistryImplTest extends AbstractLockedPlatformMBeanServerTest {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigRegistryImplTest.class);
-
- @Test
- @SuppressWarnings("IllegalCatch")
- public void testFailOnTwoFactoriesExportingSameImpl() {
- ModuleFactory factory = new TestingFixedThreadPoolModuleFactory();
- BundleContext context = mock(BundleContext.class);
- ConfigRegistryImpl configRegistry = null;
- try {
- ModuleFactoriesResolver resolver = new HardcodedModuleFactoriesResolver(mock(BundleContext.class), factory,
- factory);
-
- configRegistry = new ConfigRegistryImpl(resolver, ManagementFactory.getPlatformMBeanServer(), null);
-
- configRegistry.beginConfig();
- fail();
- } catch (final IllegalArgumentException e) {
- assertTrue(e.getMessage(), e.getMessage().startsWith(
- "Module name is not unique. Found two conflicting factories with same name " + "'fixed':"));
- verifyZeroInteractions(context);
- } finally {
- try {
- configRegistry.close();
- } catch (final Exception e) {
- // ignore
- LOG.warn("Ignoring exception", e);
- }
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
-
-import com.google.common.base.Preconditions;
-import java.io.File;
-import java.io.IOException;
-import java.lang.management.ManagementFactory;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Proxy;
-import java.util.Dictionary;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import javax.management.RuntimeMBeanException;
-import org.junit.After;
-import org.junit.Before;
-import org.mockito.Matchers;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.JMXNotifierConfigRegistry;
-import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
-import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-
-/**
- * Each test that relies on
- * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl}
- * needs to subclass this test.
- * {@link org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl} is
- * registered to platform MBean Server using
- * {@link #initConfigTransactionManagerImpl(org.opendaylight.controller
- * .config.manager.impl.factoriesresolver.ModuleFactoriesResolver)}
- * typically during setting up the each test.
- */
-public abstract class AbstractConfigTest extends AbstractLockedPlatformMBeanServerTest {
- protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
- protected ConfigRegistryImpl configRegistry;
- private JMXNotifierConfigRegistry notifyingConfigRegistry;
- protected ConfigRegistryJMXClient configRegistryClient;
- protected BaseJMXRegistrator baseJmxRegistrator;
- @Mock
- protected BundleContext mockedContext;
- @Mock
- protected ServiceRegistration<?> mockedServiceRegistration;
- protected BundleContextServiceRegistrationHandler currentBundleContextServiceRegistrationHandler;
-
- @Before
- public void setUpMocks() {
- MockitoAnnotations.initMocks(this);
- }
-
- // Default handler for OSGi service registration
- protected static class RecordingBundleContextServiceRegistrationHandler
- implements BundleContextServiceRegistrationHandler {
- private final List<RegistrationHolder> registrations = new LinkedList<>();
-
- @Override
- public void handleServiceRegistration(final Class<?> clazz, final Object serviceInstance,
- final Dictionary<String, ?> props) {
- this.registrations.add(new RegistrationHolder(clazz, serviceInstance, props));
- }
-
- public List<RegistrationHolder> getRegistrations() {
- return this.registrations;
- }
-
- protected static class RegistrationHolder {
- protected final Class<?> clazz;
- protected final Object instance;
- protected final Dictionary<String, ?> props;
-
- public RegistrationHolder(final Class<?> clazz, final Object instance, final Dictionary<String, ?> props) {
- this.clazz = clazz;
- this.instance = instance;
- this.props = props;
- }
- }
- }
-
- protected BundleContextServiceRegistrationHandler getBundleContextServiceRegistrationHandler(
- final Class<?> serviceType) {
- return this.currentBundleContextServiceRegistrationHandler;
- }
-
- // this method should be called in @Before
- protected void initConfigTransactionManagerImpl(final ModuleFactoriesResolver resolver) {
-
- final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
-
- this.configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(platformMBeanServer);
- initBundleContext();
-
- this.baseJmxRegistrator = new BaseJMXRegistrator(platformMBeanServer);
-
- this.configRegistry = new ConfigRegistryImpl(resolver, platformMBeanServer, this.baseJmxRegistrator,
- new BindingContextProvider() {
- @Override
- public synchronized void update(final ClassLoadingStrategy classLoadingStrategy,
- final SchemaContextProvider ctxProvider) {
- // NOOP
- }
-
- @Override
- public synchronized BindingRuntimeContext getBindingContext() {
- return getBindingRuntimeContext();
- }
- });
- this.notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry, platformMBeanServer);
-
- try {
- this.configRegistryJMXRegistrator.registerToJMXNoNotifications(this.configRegistry);
- this.configRegistryJMXRegistrator.registerToJMX(this.notifyingConfigRegistry);
- } catch (final InstanceAlreadyExistsException e) {
- throw new RuntimeException(e);
- }
- this.configRegistryClient = new ConfigRegistryJMXClient(platformMBeanServer);
- this.currentBundleContextServiceRegistrationHandler = new RecordingBundleContextServiceRegistrationHandler();
- }
-
- private void initBundleContext() {
- doNothing().when(this.mockedServiceRegistration).unregister();
- final RegisterServiceAnswer answer = new RegisterServiceAnswer();
- doAnswer(answer).when(this.mockedContext).registerService(Matchers.<String>any(), any(),
- Matchers.<Dictionary<String, ?>>any());
- doAnswer(answer).when(this.mockedContext).registerService(Matchers.<Class<?>>any(), any(),
- Matchers.<Dictionary<String, ?>>any());
- }
-
- @After
- public final void cleanUpConfigTransactionManagerImpl() {
- this.configRegistryJMXRegistrator.close();
- this.notifyingConfigRegistry.close();
- this.configRegistry.close();
- TestingFixedThreadPool.cleanUp();
- TestingScheduledThreadPoolImpl.cleanUp();
- }
-
- /**
- * Can be called in @After of tests if some other cleanup is needed that would
- * be discarded by closing config beans in this method.
- */
- protected void destroyAllConfigBeans() throws Exception {
- final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
- Set<ObjectName> all = transaction.lookupConfigBeans();
- // workaround for getting same Module more times
- while (all.size() > 0) {
- transaction.destroyModule(all.iterator().next());
- all = transaction.lookupConfigBeans();
- }
- transaction.commit();
- }
-
- protected void assertStatus(final CommitStatus status, final int expectedNewInstances,
- final int expectedRecreatedInstances, final int expectedReusedInstances) {
- assertEquals("New instances mismatch in " + status, expectedNewInstances, status.getNewInstances().size());
- assertEquals("Recreated instances mismatch in " + status, expectedRecreatedInstances,
- status.getRecreatedInstances().size());
- assertEquals("Reused instances mismatch in " + status, expectedReusedInstances,
- status.getReusedInstances().size());
- }
-
- protected void assertBeanCount(final int index, final String configMXBeanName) {
- assertEquals(index, this.configRegistry.lookupConfigBeans(configMXBeanName).size());
- }
-
- /**
- * Empty constructor.
- *
- * @param configBeanClass
- * Empty constructor class of config bean to be instantiated whenever
- * create
- * @param implementationName name
- * @return factory
- */
- protected ClassBasedModuleFactory createClassBasedCBF(final Class<? extends Module> configBeanClass,
- final String implementationName) {
- return new ClassBasedModuleFactory(implementationName, configBeanClass);
- }
-
- protected BindingRuntimeContext getBindingRuntimeContext() {
- return mock(BindingRuntimeContext.class);
- }
-
- public interface BundleContextServiceRegistrationHandler {
- void handleServiceRegistration(Class<?> clazz, Object serviceInstance, Dictionary<String, ?> props);
- }
-
- private class RegisterServiceAnswer implements Answer<ServiceRegistration<?>> {
- @Override
- public ServiceRegistration<?> answer(final InvocationOnMock invocation) throws Throwable {
- final Object[] args = invocation.getArguments();
-
- Preconditions.checkArgument(args.length == 3, "Unexpected arguments size (expected 3 was %s)", args.length);
-
- final Object serviceTypeRaw = args[0];
- final Object serviceInstance = args[1];
- @SuppressWarnings("unchecked")
- final Dictionary<String, ?> props = (Dictionary<String, ?>) args[2];
-
- if (serviceTypeRaw instanceof Class) {
- final Class<?> serviceType = (Class<?>) serviceTypeRaw;
- invokeServiceHandler(serviceInstance, serviceType, props);
- } else if (serviceTypeRaw instanceof String[]) {
- for (final String className : (String[]) serviceTypeRaw) {
- invokeServiceHandler(serviceInstance, className, props);
- }
- } else if (serviceTypeRaw instanceof String) {
- invokeServiceHandler(serviceInstance, (String) serviceTypeRaw, props);
- } else {
- throw new IllegalStateException(
- "Not handling service registration of type, Unknown type" + serviceTypeRaw);
- }
-
- return AbstractConfigTest.this.mockedServiceRegistration;
- }
-
- public void invokeServiceHandler(final Object serviceInstance, final String className,
- final Dictionary<String, ?> props) {
- try {
- final Class<?> serviceType = Class.forName(className);
- invokeServiceHandler(serviceInstance, serviceType, props);
- } catch (final ClassNotFoundException e) {
- throw new IllegalStateException("Not handling service registration of type " + className, e);
- }
- }
-
- private void invokeServiceHandler(final Object serviceInstance, final Class<?> serviceType,
- final Dictionary<String, ?> props) {
- final BundleContextServiceRegistrationHandler serviceRegistrationHandler =
- getBundleContextServiceRegistrationHandler(serviceType);
-
- if (serviceRegistrationHandler != null) {
- serviceRegistrationHandler.handleServiceRegistration(serviceType, serviceInstance, props);
- }
- }
- }
-
- /**
- * Expand inner exception wrapped by JMX.
- *
- * @param innerObject
- * jmx proxy which will be wrapped and returned
- */
- protected <T> T rethrowCause(final T innerObject) {
- @SuppressWarnings({ "unchecked", "checkstyle:avoidHidingCauseException" })
- final T proxy = (T) Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
- innerObject.getClass().getInterfaces(), (proxy1, method, args) -> {
- try {
- return method.invoke(innerObject, args);
- } catch (final InvocationTargetException e) {
- try {
- throw e.getTargetException();
- } catch (final RuntimeMBeanException e2) {
- throw e2.getTargetException();
- }
- }
- });
- return proxy;
- }
-
- /**
- * removes contents of the directory.
- *
- * @param dir
- * to be cleaned
- * @throws IOException IO exception
- */
- protected void cleanDirectory(final File dir) throws IOException {
- if (!dir.isDirectory()) {
- throw new IllegalStateException("dir must be a directory");
- }
-
- final File[] files = dir.listFiles();
- if (files == null) {
- throw new IOException("Failed to list contents of " + dir);
- }
-
- for (final File file : files) {
- if (file.isDirectory()) {
- cleanDirectory(dir);
- }
- file.delete();
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import java.lang.management.ManagementFactory;
-import java.util.concurrent.locks.ReentrantLock;
-import javax.management.MBeanServer;
-import org.junit.After;
-import org.junit.Before;
-
-/**
- * Each test that works with platform MBeanServer should extend this class.
- */
-public abstract class AbstractLockedPlatformMBeanServerTest {
- private static final ReentrantLock LOCK = new ReentrantLock();
- protected static MBeanServer platformMBeanServer = ManagementFactory
- .getPlatformMBeanServer();
-
- @Before
- public void acquireLock() {
- LOCK.lock();
- }
-
- @After
- public void unlock() {
- LOCK.unlock();
- }
-
- public static class SimpleBean implements SimpleBeanMBean {
- }
-
- public interface SimpleBeanMBean {
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.spi.Module;
-
-public abstract class AbstractMockedModule implements Module {
-
- protected final AutoCloseable instance;
- private final ModuleIdentifier id;
-
- protected abstract AutoCloseable prepareMockedInstance() throws Exception;
-
- @SuppressWarnings("IllegalCatch")
- public AbstractMockedModule(final DynamicMBeanWithInstance old, final ModuleIdentifier id) {
- if (old != null) {
- instance = old.getInstance();
- } else {
- try {
- instance = prepareMockedInstance();
- } catch (final Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- this.id = id == null ? new ModuleIdentifier(getClass().getCanonicalName(), "mock") : id;
- }
-
- @Override
- public boolean canReuse(final Module oldModule) {
- return instance != null;
- }
-
- @Override
- public void validate() {
- }
-
- @Override
- public AutoCloseable getInstance() {
- return instance;
- }
-
- @Override
- public ModuleIdentifier getIdentifier() {
- return id;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import com.google.common.base.Preconditions;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DependencyResolverFactory;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.manager.impl.util.InterfacesHelper;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-/**
- * Creates new modules by reflection. Provided class must have this constructor:
- * ctor(DynamicMBeanWithInstance.class, ModuleIdentifier.class). When
- * reconfiguring, both parameters will be non null. When creating new instance
- * first parameter will be null.
- *
- */
-public class ClassBasedModuleFactory implements ModuleFactory {
- private final String implementationName;
- private final Class<? extends Module> configBeanClass;
-
- /**
- * Module factory constructor.
- *
- * @param implementationName
- * name of the implementation
- * @param configBeanClass
- * class that will be instantiated when createModule is called. This
- * class must implement Module interface and all exported interfaces.
- */
- public ClassBasedModuleFactory(final String implementationName, final Class<? extends Module> configBeanClass) {
- this.implementationName = implementationName;
- this.configBeanClass = configBeanClass;
- }
-
- @Override
- public String getImplementationName() {
- return implementationName;
- }
-
- @Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
- final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
- Preconditions.checkNotNull(old);
- return constructModule(instanceName, dependencyResolver, old);
- }
-
- @Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
- final BundleContext bundleContext) {
- try {
- return constructModule(instanceName, dependencyResolver, null);
- } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
- throw new RuntimeException(e);
- }
- }
-
- private Module constructModule(final String instanceName, final DependencyResolver dependencyResolver,
- final DynamicMBeanWithInstance old)
- throws InstantiationException, IllegalAccessException, InvocationTargetException {
- Preconditions.checkNotNull(dependencyResolver);
- ModuleIdentifier moduleIdentifier = new ModuleIdentifier(implementationName, instanceName);
- Constructor<? extends Module> declaredConstructor;
- try {
- declaredConstructor = configBeanClass.getDeclaredConstructor(DynamicMBeanWithInstance.class,
- ModuleIdentifier.class);
- } catch (final NoSuchMethodException e) {
- throw new IllegalStateException(
- "Did not find constructor with parameters (DynamicMBeanWithInstance) in " + configBeanClass, e);
- }
- Preconditions.checkState(declaredConstructor != null);
- return declaredConstructor.newInstance(old, moduleIdentifier);
- }
-
- @Override
- public boolean isModuleImplementingServiceInterface(
- final Class<? extends AbstractServiceInterface> serviceInterface) {
- Class<?>[] classes = configBeanClass.getInterfaces();
- List<Class<?>> ifc = Arrays.asList(classes);
- if (ifc.contains(serviceInterface)) {
- return true;
- }
- for (Class<?> c : classes) {
- ifc = Arrays.asList(c.getInterfaces());
- if (ifc.contains(serviceInterface)) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
- final BundleContext bundleContext) {
- return new HashSet<>();
- }
-
- @Override
- public Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces() {
- return InterfacesHelper.getAllAbstractServiceClasses(configBeanClass);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-
-import com.google.common.collect.Sets;
-import java.lang.management.ManagementFactory;
-import java.lang.reflect.Field;
-import java.util.Collections;
-import java.util.Map;
-import java.util.Set;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.api.runtime.RuntimeBean;
-import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
-import org.opendaylight.controller.config.manager.impl.runtimembean.TestingRuntimeBean;
-
-public class ConfigRegistryImplLookupTest extends AbstractLockedPlatformMBeanServerTest {
-
- private ConfigRegistryImpl configRegistryImpl;
- private BaseJMXRegistrator baseJMXRegistrator;
-
- private static final String MODULE_NAMEA = "moduleA";
- private static final String MODULE_NAMEB = "moduleB";
-
- private static final String INSTANCE_NAMEA = "instA";
- private static final String INSTANCE_NAMEB = "instB";
- private static final String INSTANCE_NAMEC = "instC";
-
- private static final ObjectName NAME1 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEA);
- private static final ObjectName NAME2 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEB);
- private static final ObjectName NAME3 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEA, INSTANCE_NAMEC);
- private static final ObjectName NAME4 = ObjectNameUtil.createReadOnlyModuleON(MODULE_NAMEB, INSTANCE_NAMEA);
-
- private static final ObjectName NAME5 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEA, INSTANCE_NAMEA,
- Collections.<String, String>emptyMap());
- private static final ObjectName NAME6 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEA, INSTANCE_NAMEB,
- Collections.<String, String>emptyMap());
- private static final ObjectName NAME8 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEB, INSTANCE_NAMEA,
- Collections.<String, String>emptyMap());
-
- private static final ObjectName NAME9 = ObjectNameUtil.createTransactionModuleON("transaction", MODULE_NAMEA,
- INSTANCE_NAMEA);
-
- @Before
- public void setUp() throws Exception {
- configRegistryImpl = new ConfigRegistryImpl(null, ManagementFactory.getPlatformMBeanServer(), null);
- Field field = configRegistryImpl.getClass().getDeclaredField("baseJMXRegistrator");
- field.setAccessible(true);
- baseJMXRegistrator = (BaseJMXRegistrator) field.get(configRegistryImpl);
-
- registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME1);
- registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME2);
- registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME3);
- registerModuleBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME4);
-
- registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME5);
- registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME6);
- registerRuntimeBean(new TestingRuntimeBean(), baseJMXRegistrator, NAME8);
-
- baseJMXRegistrator.createTransactionJMXRegistrator("transaction").createTransactionModuleJMXRegistrator()
- .registerMBean(new TestingRuntimeBean(), NAME9);
-
- }
-
- private static void registerModuleBean(final TestingRuntimeBean testingRuntimeBean,
- final BaseJMXRegistrator baseJMXRegistrator, final ObjectName objectName)
- throws InstanceAlreadyExistsException {
- baseJMXRegistrator.createModuleJMXRegistrator().registerMBean(testingRuntimeBean, objectName);
- }
-
- private static void registerRuntimeBean(final RuntimeBean object, final BaseJMXRegistrator baseJMXRegistrator,
- final ObjectName runtimeON) throws InstanceAlreadyExistsException {
- String factoryName = ObjectNameUtil.getFactoryName(runtimeON);
- String instanceName = ObjectNameUtil.getInstanceName(runtimeON);
- Map<String, String> properties = ObjectNameUtil.getAdditionalPropertiesOfRuntimeBeanName(runtimeON);
-
- RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = baseJMXRegistrator
- .createRuntimeBeanRegistrator(new ModuleIdentifier(factoryName, instanceName));
-
- assertThat(properties.isEmpty(), is(true));
-
- runtimeBeanRegistrator.registerRoot(object);
- }
-
- @After
- public void cleanUp() {
- baseJMXRegistrator.close();
- }
-
- @Test
- public void testLookupConfigBeans() throws Exception {
- Set<ObjectName> beans = configRegistryImpl.lookupConfigBeans();
- assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3, NAME4), beans);
- beans = configRegistryImpl.lookupConfigBeans();
- assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3, NAME4), beans);
- }
-
- @Test
- public void testLookupConfigBeanWithModuleName() throws Exception {
- Set<ObjectName> bean = configRegistryImpl.lookupConfigBeans(MODULE_NAMEA);
- assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3), bean);
- }
-
- @Test
- public void testLookupConfigBeanWithModuleNameAndInstanceName() throws Exception {
- Set<ObjectName> bean = configRegistryImpl.lookupConfigBeans(MODULE_NAMEA, INSTANCE_NAMEA);
- assertEquals(Sets.newHashSet(NAME1), bean);
- }
-
- @Test
- public void testLookupRuntimeBeans() throws Exception {
- Set<ObjectName> beans = configRegistryImpl.lookupRuntimeBeans();
- assertEquals(Sets.newHashSet(NAME5, NAME6, NAME8), beans);
- beans = configRegistryImpl.lookupRuntimeBeans(null, null);
- assertEquals(Sets.newHashSet(NAME5, NAME6, NAME8), beans);
- }
-
- @Test
- public void testLookupRuntimeBeansWithIFcNameAndImplName() throws Exception {
- Set<ObjectName> beans = configRegistryImpl.lookupRuntimeBeans(MODULE_NAMEA, INSTANCE_NAMEA);
- assertEquals(Sets.newHashSet(NAME5), beans);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import static org.junit.Assert.assertEquals;
-
-import com.google.common.collect.Sets;
-import java.lang.management.ManagementFactory;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.ObjectName;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.TransactionJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.TransactionModuleJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.runtimembean.TestingRuntimeBean;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-public class ConfigTransactionControllerImplTest extends AbstractLockedPlatformMBeanServerTest {
-
- private BaseJMXRegistrator baseJMXRegistrator;
-
- private ConfigTransactionControllerImpl testedTxController;
- private MBeanServer transactionsMBeanServer;
-
- private static final String TRANSACTION_NAME123 = "testTX1";
- private static final String TRANSACTION_NAME4 = "testTX2";
-
- private static final String MODULE_NAME124 = "module124";
- private static final String MODULE_NAME3 = "module3";
-
- private static final String INSTANCE_NAME134 = "instA";
- private static final String INSTANCE_NAME2 = "instB";
-
- private static final ObjectName NAME1 =
- ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123, MODULE_NAME124, INSTANCE_NAME134);
- private static final ObjectName NAME2 =
- ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123,
- MODULE_NAME124, INSTANCE_NAME2);
- private static final ObjectName NAME3 =
- ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME123, MODULE_NAME3, INSTANCE_NAME134);
- private static final ObjectName NAME4 =
- ObjectNameUtil.createTransactionModuleON(TRANSACTION_NAME4, MODULE_NAME124, INSTANCE_NAME134);
-
- @Before
- public void setUp() throws Exception {
- baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
- transactionsMBeanServer = MBeanServerFactory.createMBeanServer();
- Map<String, Map.Entry<ModuleFactory, BundleContext>> currentlyRegisteredFactories = new HashMap<>();
-
- ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(
- new TransactionIdentifier(TRANSACTION_NAME123),
- () -> baseJMXRegistrator.createTransactionJMXRegistrator(TRANSACTION_NAME123),
- currentlyRegisteredFactories);
-
- SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl
- .createSRWritableRegistry(ServiceReferenceRegistryImpl.createInitialSRLookupRegistry(),
- txLookupRegistry, currentlyRegisteredFactories);
-
- testedTxController = new ConfigTransactionControllerImpl(txLookupRegistry, 1, null, 1,
- currentlyRegisteredFactories, transactionsMBeanServer, ManagementFactory.getPlatformMBeanServer(),
- false, writableRegistry);
- TransactionModuleJMXRegistrator transactionModuleJMXRegistrator123 = testedTxController
- .getTxModuleJMXRegistrator();
- transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME1);
- transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME2);
- transactionModuleJMXRegistrator123.registerMBean(new TestingRuntimeBean(), NAME3);
- TransactionJMXRegistrator jmxRegistrator4 = baseJMXRegistrator
- .createTransactionJMXRegistrator(TRANSACTION_NAME4);
- jmxRegistrator4.createTransactionModuleJMXRegistrator().registerMBean(new TestingRuntimeBean(), NAME4);
- }
-
- @After
- public void cleanUp() {
- baseJMXRegistrator.close();
- MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
- }
-
- /**
- * Tests if lookup method returns all beans with defined transaction name.
- */
- @Test
- public void testLookupConfigBeans() {
- Set<ObjectName> beans = testedTxController.lookupConfigBeans();
- assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3), beans);
- }
-
- @Test
- public void testLookupConfigBeansWithModuleName() {
- Set<ObjectName> beans = testedTxController.lookupConfigBeans(MODULE_NAME124);
- assertEquals(Sets.newHashSet(NAME1, NAME2), beans);
- }
-
- @Test
- public void lookupConfigBeansWithModuleNameAndImplName() throws Exception {
- Set<ObjectName> beans = testedTxController.lookupConfigBeans(MODULE_NAME124, INSTANCE_NAME134);
- assertEquals(Sets.newHashSet(NAME1), beans);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.mock;
-
-import javax.management.InstanceAlreadyExistsException;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-
-public class ConfigTransactionManagerImplTest extends
- AbstractConfigTest {
-
- @Before
- public void setUp() {
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext));
-
- }
-
- @Test
- public void testSingleton() {
- ConfigRegistryImpl mockedRegistry = mock(ConfigRegistryImpl.class);
- try {
- configRegistryJMXRegistrator.registerToJMX(mockedRegistry);
- fail();
- } catch (final InstanceAlreadyExistsException e) {
- assertTrue(e instanceof InstanceAlreadyExistsException);
- }
- }
-
- @Test
- public void testCleanUp() {
- super.cleanUpConfigTransactionManagerImpl();
- setUp();
- }
-
- @Test
- public void testRemoteCallsUsingJMX() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient
- .createTransaction();
- transaction.commit();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.opendaylight.controller.config.api.jmx.ObjectNameUtil.withoutTransactionName;
-
-import com.google.common.collect.ImmutableMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.management.Attribute;
-import javax.management.AttributeNotFoundException;
-import javax.management.InstanceNotFoundException;
-import javax.management.JMX;
-import javax.management.MBeanException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest.RecordingBundleContextServiceRegistrationHandler.RegistrationHolder;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.test.AbstractParallelAPSPTest;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.TestingThreadPoolServiceInterface;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-
-public class ServiceReferenceRegistryImplTest extends AbstractParallelAPSPTest {
-
- @Before
- public void setUp() {
- super.initConfigTransactionManagerImpl(
- new HardcodedModuleFactoriesResolver(mockedContext, new TestingFixedThreadPoolModuleFactory(),
- new TestingParallelAPSPModuleFactory(), new TestingScheduledThreadPoolModuleFactory()));
- }
-
- @Override
- protected String getThreadPoolImplementationName() {
- return TestingFixedThreadPoolModuleFactory.NAME;
- }
-
- @Test
- public void test() throws Exception {
- ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction();
- // create fixed1
- int fixedNrOfThreads = 20;
- int scheduledNrOfThreads = 30;
-
- ObjectName fixedTPTransactionON = transaction1.createModule(getThreadPoolImplementationName(), fixed1);
- platformMBeanServer.setAttribute(fixedTPTransactionON, new Attribute("ThreadCount", fixedNrOfThreads));
-
- ObjectName scheduledTPTransactionON = transaction1.createModule(TestingScheduledThreadPoolModuleFactory.NAME,
- "scheduled1");
- platformMBeanServer.setAttribute(scheduledTPTransactionON, new Attribute("ThreadCount", scheduledNrOfThreads));
-
- String refName = "ref";
- ObjectName serviceReference = transaction1.saveServiceReference(TestingThreadPoolServiceInterface.QNAME,
- refName, fixedTPTransactionON);
- // create apsp-parallel
- createParallelAPSP(transaction1, serviceReference);
- transaction1.commit();
-
- // check fixed1 is used
- ServiceReferenceMXBean serviceReferenceMXBean = JMX.newMXBeanProxy(platformMBeanServer,
- withoutTransactionName(serviceReference), ServiceReferenceMXBean.class);
- assertEquals(withoutTransactionName(fixedTPTransactionON), serviceReferenceMXBean.getCurrentImplementation());
- checkApspThreadCount(fixedNrOfThreads);
- // check OSGi SR
- List<RegistrationHolder> registrations =
- ((RecordingBundleContextServiceRegistrationHandler) currentBundleContextServiceRegistrationHandler)
- .getRegistrations();
- assertEquals(1, registrations.size());
- RegistrationHolder record = registrations.get(0);
- assertEquals(TestingThreadPoolIfc.class, record.clazz);
- assertEquals(ImmutableMap.of("name", "ref"), record.props);
-
- // switch reference to scheduled
- ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction();
- transaction2.saveServiceReference(TestingThreadPoolServiceInterface.QNAME, refName,
- ObjectNameUtil.withTransactionName(scheduledTPTransactionON, transaction2.getTransactionName()));
- transaction2.commit();
- // check scheduled is used
- checkApspThreadCount(scheduledNrOfThreads);
- // check that dummy MXBean points to scheduled
- assertEquals(withoutTransactionName(scheduledTPTransactionON),
- serviceReferenceMXBean.getCurrentImplementation());
-
- // empty transaction
- configRegistryClient.createTransaction().commit();
-
- // get service mapping
- Map<String, Map<String, ObjectName>> serviceMapping = configRegistryClient.getServiceMapping();
- Map<String, Map<String, ObjectName>> expectedMapping = ImmutableMap.of(TestingThreadPoolServiceInterface.QNAME,
- (Map<String, ObjectName>) ImmutableMap.of(refName, withoutTransactionName(scheduledTPTransactionON)));
- assertEquals(expectedMapping, serviceMapping);
-
- // destroy all
- ConfigTransactionJMXClient transaction4 = configRegistryClient.createTransaction();
- Set<ObjectName> objectNames = transaction4.lookupConfigBeans();
- for (ObjectName on : objectNames) {
- transaction4.destroyModule(on);
- }
- transaction4.commit();
-
- serviceMapping = configRegistryClient.getServiceMapping();
- assertTrue(serviceMapping.isEmpty());
- }
-
- private void checkApspThreadCount(final int fixedNrOfThreads)
- throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
- ObjectName apspON = ObjectNameUtil.createReadOnlyModuleON(TestingParallelAPSPModuleFactory.NAME, apsp1);
- assertEquals(fixedNrOfThreads, platformMBeanServer.getAttribute(apspON, "MaxNumberOfThreads"));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dependencyresolver;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.reset;
-
-import java.util.Arrays;
-import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.JmxAttribute;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.AbstractLockedPlatformMBeanServerTest;
-import org.opendaylight.controller.config.manager.impl.ModuleInternalInfo;
-import org.opendaylight.controller.config.manager.impl.TransactionIdentifier;
-import org.opendaylight.controller.config.manager.impl.TransactionStatus;
-import org.opendaylight.controller.config.manager.impl.jmx.TransactionModuleJMXRegistrator.TransactionModuleJMXRegistration;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-public class DependencyResolverManagerTest extends AbstractLockedPlatformMBeanServerTest {
-
- final ModuleIdentifier apspName = new ModuleIdentifier("apsp", "apsp"); // depends
- // on:
- final ModuleIdentifier threadPoolName = new ModuleIdentifier("threadpool", "threadpool"); // depends on:
- final ModuleIdentifier threadFactoryName = new ModuleIdentifier("threadfactory", "threadfactory");
-
- private DependencyResolverManager tested;
- TransactionStatus transactionStatus;
-
- @Before
- public void setUp() {
- transactionStatus = mock(TransactionStatus.class);
- ServiceReferenceReadableRegistry mockedRegistry = mock(ServiceReferenceReadableRegistry.class);
- tested = new DependencyResolverManager(new TransactionIdentifier("txName"), transactionStatus, mockedRegistry,
- null, platformMBeanServer);
- doNothing().when(transactionStatus).checkCommitStarted();
- doNothing().when(transactionStatus).checkNotCommitted();
- }
-
- @Test
- public void testOrdering() {
- final DependencyResolverImpl apspDRI = tested.getOrCreate(apspName);
- mockGetInstance(tested, apspName);
- final DependencyResolverImpl threadPoolDRI = tested.getOrCreate(threadPoolName);
- mockGetInstance(tested, threadPoolName);
- tested.getOrCreate(threadFactoryName);
- mockGetInstance(tested, threadFactoryName);
-
- // set threadfactory as dependency of threadpool
- declareDependency(threadPoolDRI, threadFactoryName);
- // set threadpool as dependency of apsp
- declareDependency(apspDRI, threadPoolName);
-
- // switch to second phase committed
- reset(transactionStatus);
- doNothing().when(transactionStatus).checkCommitStarted();
- doNothing().when(transactionStatus).checkCommitted();
- doNothing().when(transactionStatus).checkNotCommitted();
-
- List<ModuleIdentifier> sortedModuleIdentifiers = tested.getSortedModuleIdentifiers();
- assertEquals(Arrays.asList(threadFactoryName, threadPoolName, apspName), sortedModuleIdentifiers);
- }
-
- /**
- * Simulate dependentResolver resolving its dependency identified by
- * dependentName.
- */
- private static void declareDependency(final DependencyResolverImpl dependerResolver,
- final ModuleIdentifier dependentName) {
- JmxAttribute dummyAttribute = new JmxAttribute("dummy");
- dependerResolver.resolveInstance(Object.class, ObjectNameUtil.createReadOnlyModuleON(dependentName),
- dummyAttribute);
- }
-
- private static void mockGetInstance(final DependencyResolverManager tested,
- final ModuleIdentifier moduleIdentifier) {
-
- ModuleFactory moduleFactory = mock(ModuleFactory.class);
- ModuleInternalInfo maybeOldInternalInfo = null;
- TransactionModuleJMXRegistration transactionModuleJMXRegistration = null;
- boolean isDefaultBean = false;
-
- tested.put(moduleIdentifier, mockedModule(), moduleFactory, maybeOldInternalInfo,
- transactionModuleJMXRegistration, isDefaultBean, mock(BundleContext.class));
- }
-
- private static Module mockedModule() {
- Module mockedModule = mock(Module.class);
- doReturn(mock(AutoCloseable.class)).when(mockedModule).getInstance();
- doReturn(new ModuleIdentifier("fact", "instance")).when(mockedModule).getIdentifier();
- return mockedModule;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import static org.junit.Assert.assertEquals;
-
-import java.lang.management.ManagementFactory;
-import javax.management.Attribute;
-import javax.management.AttributeList;
-import javax.management.DynamicMBean;
-import javax.management.JMX;
-import javax.management.MBeanInfo;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.ObjectName;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.AbstractLockedPlatformMBeanServerTest;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolConfigMXBean;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModule;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
-import org.opendaylight.controller.config.spi.Module;
-
-public abstract class AbstractDynamicWrapperTest extends AbstractLockedPlatformMBeanServerTest {
- protected final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
- private static final String MODULE_NAME = "impl";
- protected final ObjectName threadPoolDynamicWrapperON =
- ObjectNameUtil.createReadOnlyModuleON(MODULE_NAME, "fixed1");
- protected static final String THREAD_COUNT = "ThreadCount";
- protected static final String TRIGGER_NEW_INSTANCE_CREATION = "TriggerNewInstanceCreation";
-
- protected final int threadCount = 5;
- protected TestingFixedThreadPoolModule threadPoolConfigBean;
- private static final ModuleIdentifier MODULE_IDENTIFIER =
- new ModuleIdentifier(MODULE_NAME, "clientname2");
-
- protected MBeanServer internalServer;
-
- @Before
- public void registerToJMX() throws Exception {
- internalServer = MBeanServerFactory.createMBeanServer();
- TestingFixedThreadPoolModuleFactory testingFixedThreadPoolConfigBeanFactory =
- new TestingFixedThreadPoolModuleFactory();
- threadPoolConfigBean = testingFixedThreadPoolConfigBeanFactory.createModule("", null, null);
-
- threadPoolConfigBean.setThreadCount(threadCount);
- AbstractDynamicWrapper dynamicWrapper = getDynamicWrapper(threadPoolConfigBean, MODULE_IDENTIFIER);
- platformMBeanServer.registerMBean(dynamicWrapper, threadPoolDynamicWrapperON);
- }
-
- @After
- public void unregisterFromJMX() throws Exception {
- TestingFixedThreadPool.cleanUp();
- platformMBeanServer.unregisterMBean(threadPoolDynamicWrapperON);
- MBeanServerFactory.releaseMBeanServer(internalServer);
- }
-
- protected abstract AbstractDynamicWrapper getDynamicWrapper(Module module, ModuleIdentifier moduleIdentifier);
-
- @Test
- public void testReadAttributes() throws Exception {
- DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class);
-
- assertEquals(threadCount, proxy.getAttribute(THREAD_COUNT));
-
- assertEquals(threadPoolConfigBean.isTriggerNewInstanceCreation(),
- proxy.getAttribute(TRIGGER_NEW_INSTANCE_CREATION));
-
- AttributeList attributes = proxy.getAttributes(new String[] { THREAD_COUNT, TRIGGER_NEW_INSTANCE_CREATION });
- assertEquals(2, attributes.size());
- Attribute threadCountAttr = (Attribute) attributes.get(0);
- assertEquals(THREAD_COUNT, threadCountAttr.getName());
- assertEquals(threadCount, threadCountAttr.getValue());
- Attribute boolTestAttr = (Attribute) attributes.get(1);
- assertEquals(TRIGGER_NEW_INSTANCE_CREATION, boolTestAttr.getName());
- assertEquals(threadPoolConfigBean.isTriggerNewInstanceCreation(), boolTestAttr.getValue());
-
- MBeanInfo beanInfo = proxy.getMBeanInfo();
- assertEquals(2, beanInfo.getAttributes().length);
- }
-
- @Test
- public void testGettersWithMXBeanProxy() {
- TestingFixedThreadPoolConfigMXBean proxy = JMX.newMXBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON,
- TestingFixedThreadPoolConfigMXBean.class);
- assertEquals(threadCount, proxy.getThreadCount());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import com.google.common.base.Throwables;
-import com.google.common.collect.Sets;
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.Executor;
-import java.util.concurrent.ExecutorService;
-import javax.management.ObjectName;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.api.annotations.Description;
-import org.opendaylight.controller.config.api.annotations.RequireInterface;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-
-public class AnnotationsTest {
-
- private final String setSomethingString = "setSomething";
-
- private static void assertRequireInterfaceAnnotationHasCorrectValue(final Class<?> clazz, final String methodName,
- final Set<Class<?>> inspectedInterfaces, final Class<? extends AbstractServiceInterface> expectedValue) {
- Method setter = findMethod(clazz, methodName);
- RequireInterface found = AttributeHolder.findRequireInterfaceAnnotation(setter, inspectedInterfaces);
- if (expectedValue == null) {
- assertNull(found);
- } else {
- assertNotNull(found);
- assertEquals(expectedValue, found.value());
- }
- }
-
- private static Method findMethod(final Class<?> clazz, final String methodName) {
- Method setter;
- try {
- setter = clazz.getMethod(methodName, new Class[] { ObjectName.class });
- } catch (final NoSuchMethodException e) {
- throw Throwables.propagate(e);
- }
- return setter;
- }
-
- private static void assertDescription(final Class<?> clazz, final String methodName,
- final Set<Class<?>> exportedInterfaces, final String expectedValue) {
- Method setter = findMethod(clazz, methodName);
- String found = AttributeHolder.findDescription(setter, exportedInterfaces);
- if (expectedValue == null) {
- assertNull(found);
- } else {
- assertNotNull(found);
- assertEquals(expectedValue, found);
- }
- }
-
- private static void assertDescriptionOnClass(final Class<?> clazz, final Set<Class<?>> jmxInterfaces,
- final String expectedValue) {
- String found = AbstractDynamicWrapper.findDescription(clazz, jmxInterfaces);
- if (expectedValue == null) {
- assertNull(found);
- } else {
- assertNotNull(found);
- assertEquals(expectedValue, found);
- }
- }
-
- private static void assertNoDescriptionOnClass(final Class<?> clazz, final Set<Class<?>> jmxInterfaces) {
- String found = AbstractDynamicWrapper.findDescription(clazz, jmxInterfaces);
- assertTrue(found.isEmpty());
- }
-
- static final String SIMPLE = "simple";
- static final String SUBCLASS2 = "subclass2";
-
- @ServiceInterfaceAnnotation(value = SIMPLE,
- osgiRegistrationType = Executor.class,
- namespace = "ns", revision = "rev", localName = SIMPLE)
- interface SimpleSI extends AbstractServiceInterface {
- }
-
- @Description("class")
- public static class SuperClass {
- @RequireInterface(SimpleSI.class)
- @Description("descr")
- public void setSomething(final ObjectName objectName) {
-
- }
- }
-
- private static Set<Class<?>> emptySetOfInterfaces() {
- return Collections.emptySet();
- }
-
- @Test
- public void testFindAnnotation_directly() throws Exception {
- assertRequireInterfaceAnnotationHasCorrectValue(SuperClass.class, setSomethingString, emptySetOfInterfaces(),
- SimpleSI.class);
- assertDescription(SuperClass.class, setSomethingString, emptySetOfInterfaces(), "descr");
- assertDescriptionOnClass(SuperClass.class, emptySetOfInterfaces(), "class");
- }
-
- public static class SubClassWithout extends SuperClass {
-
- }
-
- @Test
- public void testFindAnnotation_subclassWithout() throws Exception {
- assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithout.class, setSomethingString,
- emptySetOfInterfaces(), SimpleSI.class);
- assertDescription(SubClassWithout.class, setSomethingString, emptySetOfInterfaces(), "descr");
- assertDescriptionOnClass(SuperClass.class, emptySetOfInterfaces(), "class");
- }
-
- public static class SubClassWithEmptyMethod extends SuperClass {
- @Override
- public void setSomething(final ObjectName objectName) {
-
- }
- }
-
- @Test
- public void testOverridingWithoutAnnotation() throws Exception {
- assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithEmptyMethod.class, setSomethingString,
- emptySetOfInterfaces(), SimpleSI.class);
- assertDescription(SubClassWithEmptyMethod.class, setSomethingString, emptySetOfInterfaces(), "descr");
- assertDescriptionOnClass(SubClassWithEmptyMethod.class, emptySetOfInterfaces(), "class");
- }
-
- interface SubSI extends SimpleSI {
-
- }
-
- @ServiceInterfaceAnnotation(value = SUBCLASS2,
- osgiRegistrationType = ExecutorService.class, namespace = "ns", revision = "rev", localName = SUBCLASS2)
- interface SubSI2 extends SubSI {
- }
-
- public static class SubClassWithAnnotation extends SuperClass {
- @Override
- @RequireInterface(SubSI2.class)
- @Description("descr2")
- public void setSomething(final ObjectName objectName) {
-
- }
- }
-
- @Test
- public void testFindAnnotation_SubClassWithAnnotation() throws Exception {
- assertDescription(SubClassWithAnnotation.class, setSomethingString, emptySetOfInterfaces(), "descr2\ndescr");
- try {
- assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithAnnotation.class, setSomethingString,
- emptySetOfInterfaces(), SubSI2.class);
- fail();
- } catch (final IllegalStateException e) {
- assertTrue(e.getMessage(),
- e.getMessage().startsWith("Error finding @RequireInterface. More than one value specified"));
- }
- }
-
- public interface HasSomeMethod {
- void setSomething(ObjectName objectName);
- }
-
- public static class SubClassWithoutMethodWithInterface extends SuperClass implements HasSomeMethod {
-
- }
-
- @Test
- public void testFindAnnotation_SubClassWithoutMethodWithInterface() throws Exception {
- assertRequireInterfaceAnnotationHasCorrectValue(SubClassWithoutMethodWithInterface.class, setSomethingString,
- emptySetOfInterfaces(), SimpleSI.class);
- assertDescription(SubClassWithoutMethodWithInterface.class, setSomethingString, emptySetOfInterfaces(),
- "descr");
- }
-
- abstract static class SuperClassWithInterface implements HasSomeMethod {
- @Override
- @RequireInterface(SubSI2.class)
- @Description("descr")
- public void setSomething(final ObjectName objectName) {
- }
- }
-
- @Description("class")
- public static class SubClassOfSuperClassWithInterface extends SuperClassWithInterface {
- }
-
- @Test
- public void testFindAnnotation_SubClassOfSuperClassWithInterface() throws Exception {
- assertRequireInterfaceAnnotationHasCorrectValue(SubClassOfSuperClassWithInterface.class, setSomethingString,
- emptySetOfInterfaces(), SubSI2.class);
- assertDescription(SubClassOfSuperClassWithInterface.class, setSomethingString, emptySetOfInterfaces(), "descr");
- assertDescriptionOnClass(SubClassOfSuperClassWithInterface.class, emptySetOfInterfaces(), "class");
- }
-
- @Test
- public void testFindAnnotation2() throws Exception {
- assertNoDescriptionOnClass(SuperClassWithInterface.class, emptySetOfInterfaces());
- }
-
- @Description("class")
- interface HasSomeMethodWithAnnotations {
- @RequireInterface(SubSI2.class)
- @Description("descr")
- void setSomething(ObjectName objectName);
- }
-
- static class HasSomeMethodWithAnnotationsImpl implements HasSomeMethodWithAnnotations {
- @Override
- public void setSomething(final ObjectName objectName) {
- }
- }
-
- @Test
- public void testHasSomeMethodWithAnnotationsImpl() {
- HashSet<Class<?>> exportedInterfaces = Sets.<Class<?>>newHashSet(HasSomeMethodWithAnnotations.class);
- assertRequireInterfaceAnnotationHasCorrectValue(HasSomeMethodWithAnnotationsImpl.class, setSomethingString,
- exportedInterfaces, SubSI2.class);
-
- assertDescription(HasSomeMethodWithAnnotationsImpl.class, setSomethingString, exportedInterfaces, "descr");
-
- assertDescriptionOnClass(HasSomeMethodWithAnnotationsImpl.class,
- new HashSet<>(Arrays.asList(HasSomeMethodWithAnnotations.class)), "class");
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import java.lang.management.ManagementFactory;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.spi.Module;
-
-public class DynamicReadableWrapperTest extends AbstractDynamicWrapperTest {
-
- @Override
- protected AbstractDynamicWrapper getDynamicWrapper(final Module module,
- final ModuleIdentifier moduleIdentifier) {
- return new DynamicReadableWrapper(module, null, moduleIdentifier,
- internalServer, ManagementFactory.getPlatformMBeanServer());
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.dynamicmbean;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-import javax.management.Attribute;
-import javax.management.AttributeList;
-import javax.management.DynamicMBean;
-import javax.management.JMX;
-import javax.management.MBeanServerFactory;
-import javax.management.ObjectName;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.dynamicmbean.ReadOnlyAtomicBoolean.ReadOnlyAtomicBooleanImpl;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPConfigMXBean;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModule;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolConfigMXBean;
-import org.opendaylight.controller.config.spi.Module;
-
-public class DynamicWritableWrapperTest extends AbstractDynamicWrapperTest {
- private final int newThreadCount = 10;
- private final AtomicBoolean atomicBoolean = new AtomicBoolean();
- private final ReadOnlyAtomicBoolean readOnlyAtomicBoolean = new ReadOnlyAtomicBooleanImpl(atomicBoolean);
-
- @Override
- protected AbstractDynamicWrapper getDynamicWrapper(final Module module, final ModuleIdentifier moduleIdentifier) {
- return new DynamicWritableWrapper(module, moduleIdentifier, "transaction-1", readOnlyAtomicBoolean,
- MBeanServerFactory.createMBeanServer(), platformMBeanServer);
- }
-
- @Test
- public void testSetAttribute() throws Exception {
- DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class);
-
- proxy.setAttribute(new Attribute(THREAD_COUNT, newThreadCount));
-
- assertEquals(newThreadCount, proxy.getAttribute(THREAD_COUNT));
- assertEquals(newThreadCount, threadPoolConfigBean.getThreadCount());
-
- AttributeList attributeList = new AttributeList();
- attributeList.add(new Attribute(THREAD_COUNT, threadCount));
- boolean bool = true;
- attributeList.add(new Attribute(TRIGGER_NEW_INSTANCE_CREATION, bool));
- proxy.setAttributes(attributeList);
-
- assertEquals(threadCount, threadPoolConfigBean.getThreadCount());
- assertEquals(bool, threadPoolConfigBean.isTriggerNewInstanceCreation());
- }
-
- @Test
- public void testSettersWithMXBeanProxy() {
- TestingFixedThreadPoolConfigMXBean proxy = JMX.newMXBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON,
- TestingFixedThreadPoolConfigMXBean.class);
- proxy.setThreadCount(newThreadCount);
- assertEquals(newThreadCount, threadPoolConfigBean.getThreadCount());
- }
-
- /*
- * Try to call setter with ObjectName containing transaction name. Verify that
- * ObjectName without transaction name was actually passed on the config bean.
- */
- @Test
- public void testObjectNameSetterWithONContainingTransaction_shouldBeTranslatedToReadOnlyON() throws Exception {
- TestingParallelAPSPModuleFactory testingParallelAPSPConfigBeanFactory = new TestingParallelAPSPModuleFactory();
- TestingParallelAPSPModule apspConfigBean = testingParallelAPSPConfigBeanFactory.createModule("", null, null);
- ModuleIdentifier moduleIdentifier2 = new ModuleIdentifier("apsp", "parallel");
- ObjectName dynON2 = ObjectNameUtil.createReadOnlyModuleON(moduleIdentifier2);
- AbstractDynamicWrapper dyn = getDynamicWrapper(apspConfigBean, moduleIdentifier2);
- platformMBeanServer.registerMBean(dyn, dynON2);
- try {
- TestingParallelAPSPConfigMXBean proxy = JMX.newMBeanProxy(platformMBeanServer, dynON2,
- TestingParallelAPSPConfigMXBean.class);
- ObjectName withTransactionName = ObjectNameUtil.createTransactionModuleON("transaction1", "moduleName",
- "instanceName");
- proxy.setThreadPool(withTransactionName);
- ObjectName withoutTransactionName = ObjectNameUtil.withoutTransactionName(withTransactionName);
- assertEquals(withoutTransactionName, proxy.getThreadPool());
- } finally {
- platformMBeanServer.unregisterMBean(dynON2);
- }
- }
-
- private void setNumberOfThreads(final int numberOfThreads) throws Exception {
- DynamicMBean proxy = JMX.newMBeanProxy(platformMBeanServer, threadPoolDynamicWrapperON, DynamicMBean.class);
-
- proxy.setAttribute(new Attribute(THREAD_COUNT, numberOfThreads));
-
- }
-
- @Test
- public void testDisablingOfWriteOperations() throws Exception {
- setNumberOfThreads(newThreadCount);
- atomicBoolean.set(true);
- try {
- setNumberOfThreads(newThreadCount);
- fail();
- } catch (final IllegalStateException e) {
- assertEquals("Operation is not allowed now", e.getMessage());
- } finally {
- atomicBoolean.set(false);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.factoriesresolver;
-
-import java.util.AbstractMap;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-public class HardcodedModuleFactoriesResolver implements ModuleFactoriesResolver {
- private final Map<String, Map.Entry<ModuleFactory, BundleContext>> factories;
-
- public HardcodedModuleFactoriesResolver(final BundleContext bundleContext, final ModuleFactory... list) {
- this.factories = new HashMap<>(list.length);
- for (ModuleFactory moduleFactory : list) {
- String moduleName = moduleFactory.getImplementationName();
- if (moduleName == null || moduleName.isEmpty()) {
- throw new IllegalStateException("Invalid implementation name for " + moduleFactory);
- }
- Map.Entry<ModuleFactory, BundleContext> conflicting = factories.get(moduleName);
- if (conflicting == null) {
- factories.put(moduleName, new AbstractMap.SimpleEntry<>(moduleFactory, bundleContext));
- } else {
- throw new IllegalArgumentException(String.format(
- "Module name is not unique. Found two conflicting factories with same name '%s':\n\t%s\n\t%s\n",
- moduleName, conflicting.getKey(), moduleFactory));
- }
- }
- }
-
- @Override
- public Map<String, Map.Entry<ModuleFactory, BundleContext>> getAllFactories() {
- return factories;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.factoriesresolver;
-
-public class HierarchicalConfigMBeanFactoriesHolderTest {
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.impl.osgi;
-
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import com.google.common.util.concurrent.MoreExecutors;
-import java.util.Collections;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.ServiceReference;
-
-public class BlankTransactionServiceTrackerTest {
- @Mock
- private BlankTransactionServiceTracker.BlankTransaction blankTx;
- private BlankTransactionServiceTracker tracker;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- doReturn(new CommitStatus(Collections.<ObjectName>emptyList(), Collections.<ObjectName>emptyList(),
- Collections.<ObjectName>emptyList())).when(blankTx).hit();
- tracker = new BlankTransactionServiceTracker(blankTx, 10, MoreExecutors.newDirectExecutorService());
- }
-
- @Test
- public void testBlankTransaction() throws Exception {
- tracker.addingService(getMockServiceReference());
- tracker.modifiedService(getMockServiceReference(), null);
- tracker.removedService(getMockServiceReference(), null);
- verify(blankTx, times(3)).hit();
- }
-
- @Test
- public void testValidationException() throws Exception {
- IllegalArgumentException argumentException = new IllegalArgumentException();
- ValidationException validationException = ValidationException
- .createForSingleException(new ModuleIdentifier("m", "i"), argumentException);
- doThrow(validationException).when(blankTx).hit();
-
- tracker.addingService(getMockServiceReference());
- verify(blankTx, times(10)).hit();
- }
-
- @Test
- public void testConflictingException() throws Exception {
- int maxAttempts = 2;
- tracker = new BlankTransactionServiceTracker(blankTx, maxAttempts, MoreExecutors.newDirectExecutorService());
-
- final ConflictingVersionException ex = new ConflictingVersionException();
- doThrow(ex).when(blankTx).hit();
-
- tracker.addingService(getMockServiceReference());
- verify(blankTx, times(maxAttempts)).hit();
- }
-
- private static ServiceReference<ModuleFactory> getMockServiceReference() {
- return mock(ServiceReference.class);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.impl.osgi;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import com.google.common.collect.Lists;
-import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-
-public class BundleContextBackedModuleFactoriesResolverTest {
-
- @Mock
- private BundleContext bundleContext;
- private BundleContextBackedModuleFactoriesResolver resolver;
- private ServiceReference<?> s1;
- private ServiceReference<?> s2;
- private ModuleFactory f1;
- private ModuleFactory f2;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- s1 = getServiceRef();
- s2 = getServiceRef();
- doReturn(Lists.newArrayList(s1, s2)).when(bundleContext).getServiceReferences(ModuleFactory.class, null);
- f1 = getMockFactory("f1");
- doReturn(f1).when(bundleContext).getService(s1);
- f2 = getMockFactory("f2");
- doReturn(f2).when(bundleContext).getService(s2);
- resolver = new BundleContextBackedModuleFactoriesResolver(bundleContext);
- }
-
- private static ModuleFactory getMockFactory(final String name) {
- ModuleFactory mock = mock(ModuleFactory.class);
- doReturn(name).when(mock).toString();
- doReturn(name).when(mock).getImplementationName();
- return mock;
- }
-
- private ServiceReference<?> getServiceRef() {
- ServiceReference<?> mock = mock(ServiceReference.class);
- doReturn("serviceRef").when(mock).toString();
- final Bundle bundle = mock(Bundle.class);
- doReturn(bundleContext).when(bundle).getBundleContext();
- doReturn(bundle).when(mock).getBundle();
- return mock;
- }
-
- @Test
- public void testGetAllFactories() throws Exception {
- Map<String, Map.Entry<ModuleFactory, BundleContext>> allFactories = resolver.getAllFactories();
- assertEquals(2, allFactories.size());
- assertTrue(allFactories.containsKey(f1.getImplementationName()));
- assertEquals(f1, allFactories.get(f1.getImplementationName()).getKey());
- assertEquals(bundleContext, allFactories.get(f1.getImplementationName()).getValue());
- assertTrue(allFactories.containsKey(f2.getImplementationName()));
- assertEquals(f2, allFactories.get(f2.getImplementationName()).getKey());
- assertEquals(bundleContext, allFactories.get(f2.getImplementationName()).getValue());
- }
-
- @Test
- @SuppressWarnings("IllegalCatch")
- public void testDuplicateFactories() throws Exception {
- doReturn(f1).when(bundleContext).getService(s2);
- try {
- resolver.getAllFactories();
- } catch (final Exception e) {
- assertThat(e.getMessage(), containsString(f1.getImplementationName()));
- assertThat(e.getMessage(), containsString("unique"));
- return;
- }
-
- fail("Should fail with duplicate factory name");
- }
-
- @Test(expected = NullPointerException.class)
- public void testNullFactory() throws Exception {
- doReturn(null).when(bundleContext).getService(s2);
- resolver.getAllFactories();
- }
-
- @Test(expected = IllegalStateException.class)
- public void testNullFactoryName() throws Exception {
- doReturn(null).when(f1).getImplementationName();
- resolver.getAllFactories();
- }
-
- @Test(expected = NullPointerException.class)
- public void testNullBundleName() throws Exception {
- doReturn(null).when(s1).getBundle();
- resolver.getAllFactories();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.impl.osgi;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.verifyZeroInteractions;
-
-import com.google.common.util.concurrent.Futures;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.InOrder;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.util.tracker.BundleTrackerCustomizer;
-
-public class ExtensibleBundleTrackerTest {
-
- @Mock
- private BundleContext bundleContext;
- @Mock
- private Bundle bundle;
- @Mock
- private BundleEvent bundleEvent;
-
- @Mock
- private BundleTrackerCustomizer<Object> primaryTracker;
- @Mock
- private BundleTrackerCustomizer<?> additionalTracker;
-
- private ExtensibleBundleTracker<Object> extensibleBundleTracker;
- private Object primaryValue = new Object();
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- doReturn("bundle").when(bundle).toString();
- doReturn("bundleEvent").when(bundleEvent).toString();
-
- doReturn(primaryValue).when(primaryTracker).addingBundle(bundle, bundleEvent);
- doNothing().when(primaryTracker).modifiedBundle(bundle, bundleEvent, primaryValue);
- doNothing().when(primaryTracker).removedBundle(bundle, bundleEvent, primaryValue);
-
- doReturn(new Object()).when(additionalTracker).addingBundle(bundle, bundleEvent);
- doNothing().when(additionalTracker).modifiedBundle(bundle, bundleEvent, null);
- doNothing().when(additionalTracker).removedBundle(bundle, bundleEvent, null);
- extensibleBundleTracker = new ExtensibleBundleTracker<>(bundleContext, primaryTracker, additionalTracker);
- }
-
- @Test
- public void testAddingBundle() throws Exception {
- assertEquals(primaryValue, extensibleBundleTracker.addingBundle(bundle, bundleEvent).get());
- InOrder inOrder = Mockito.inOrder(primaryTracker, additionalTracker);
- inOrder.verify(primaryTracker).addingBundle(bundle, bundleEvent);
- inOrder.verify(additionalTracker).addingBundle(bundle, bundleEvent);
- }
-
- @Test
- public void testRemovedBundle() throws Exception {
- extensibleBundleTracker.removedBundle(bundle, bundleEvent, Futures.immediateFuture(primaryValue));
- InOrder inOrder = Mockito.inOrder(primaryTracker, additionalTracker);
- inOrder.verify(primaryTracker).removedBundle(bundle, bundleEvent, primaryValue);
- inOrder.verify(additionalTracker).removedBundle(bundle, bundleEvent, null);
- }
-
- @Test
- public void testRemovedBundleWithEx() throws Exception {
- IllegalStateException throwable = new IllegalStateException();
- extensibleBundleTracker.removedBundle(bundle, bundleEvent, Futures.immediateFailedFuture(throwable));
- verifyZeroInteractions(primaryTracker);
- verifyZeroInteractions(additionalTracker);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.impl.osgi;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
-
-import java.util.Dictionary;
-import java.util.Set;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DependencyResolverFactory;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.ServiceRegistration;
-
-public class ModuleFactoryBundleTrackerTest {
-
- @Mock
- private Bundle bundle;
- @Mock
- private BundleContext context;
- @Mock
- private ServiceRegistration<?> reg;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- doAnswer(invocation -> getClass().getClassLoader().loadClass((String) invocation.getArguments()[0]))
- .when(bundle).loadClass(anyString());
- doReturn("mockBundle").when(bundle).toString();
- doReturn(context).when(bundle).getBundleContext();
- doReturn(reg).when(context).registerService(anyString(), anyObject(), any(Dictionary.class));
- }
-
- @Test
- public void testRegisterFactory() throws Exception {
- ModuleFactoryBundleTracker.registerFactory(TestingFactory.class.getName(), bundle);
- verify(context).registerService(ModuleFactory.class.getName(), TestingFactory.currentInstance, null);
- }
-
- @Test
- @SuppressWarnings("IllegalCatch")
- public void testRegisterFactoryInstantiateEx() throws Exception {
- try {
- ModuleFactoryBundleTracker.registerFactory(WrongConstructorTestingFactory.class.getName(), bundle);
- } catch (final Exception e) {
- verifyZeroInteractions(context);
- assertNotNull(e.getCause());
- assertEquals(InstantiationException.class, e.getCause().getClass());
- return;
- }
-
- fail("Cannot register without proper constructor");
- }
-
- @Test
- @SuppressWarnings("IllegalCatch")
- public void testRegisterFactoryInstantiateExAccess() throws Exception {
- try {
- ModuleFactoryBundleTracker.registerFactory(NoAccessConstructorTestingFactory.class.getName(), bundle);
- } catch (final Exception e) {
- verifyZeroInteractions(context);
- assertNotNull(e.getCause());
- assertEquals(IllegalAccessException.class, e.getCause().getClass());
- return;
- }
-
- fail("Cannot register without proper constructor");
- }
-
- @Test
- @SuppressWarnings("IllegalCatch")
- public void testRegisterFactoryNotExtending() throws Exception {
- try {
- ModuleFactoryBundleTracker.registerFactory(NotExtendingTestingFactory.class.getName(), bundle);
- } catch (final Exception e) {
- verifyZeroInteractions(context);
- return;
- }
-
- fail("Cannot register without extend");
- }
-
- @Test
- @SuppressWarnings("IllegalCatch")
- public void testRegisterFactoryNotExisting() throws Exception {
- try {
- ModuleFactoryBundleTracker.registerFactory("Unknown class", bundle);
- } catch (final Exception e) {
- verifyZeroInteractions(context);
- assertNotNull(e.getCause());
- assertEquals(ClassNotFoundException.class, e.getCause().getClass());
- return;
- }
-
- fail("Cannot register without extend");
- }
-
- @Mock
- private BlankTransactionServiceTracker blankTxTracker;
-
- @Test
- public void testAddingBundle() throws Exception {
- final ModuleFactoryBundleTracker tracker = new ModuleFactoryBundleTracker(blankTxTracker);
- doReturn(getClass().getResource("/module-factories/module-factory-ok")).when(bundle).getEntry(anyString());
- tracker.addingBundle(bundle, mock(BundleEvent.class));
- verify(context).registerService(ModuleFactory.class.getName(), TestingFactory.currentInstance, null);
- }
-
- @Test
- @SuppressWarnings("IllegalCatch")
- public void testAddingBundleError() throws Exception {
- final ModuleFactoryBundleTracker tracker = new ModuleFactoryBundleTracker(blankTxTracker);
- doReturn(getClass().getResource("/module-factories/module-factory-fail")).when(bundle).getEntry(anyString());
- try {
- tracker.addingBundle(bundle, mock(BundleEvent.class));
- } catch (final Exception e) {
- verifyZeroInteractions(context);
- return;
- }
-
- fail("Cannot register");
- }
-
- static class WrongConstructorTestingFactory extends TestingFactory {
- WrongConstructorTestingFactory(final String randomParam) {
- }
- }
-
- static class NotExtendingTestingFactory {
- }
-
- static final class NoAccessConstructorTestingFactory extends TestingFactory {
- private NoAccessConstructorTestingFactory() {
- }
- }
-
- static class TestingFactory implements ModuleFactory {
-
- static TestingFactory currentInstance;
-
- TestingFactory() {
- currentInstance = this;
- }
-
- @Override
- public String getImplementationName() {
- return "Testing";
- }
-
- @Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
- final BundleContext bundleContext) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
- final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isModuleImplementingServiceInterface(
- final Class<? extends AbstractServiceInterface> serviceInterface) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Set<? extends Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
- final BundleContext bundleContext) {
- throw new UnsupportedOperationException();
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.runtimembean;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Maps;
-import java.lang.management.ManagementFactory;
-import java.util.Map;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.api.runtime.HierarchicalRuntimeBeanRegistration;
-import org.opendaylight.controller.config.manager.impl.AbstractLockedPlatformMBeanServerTest;
-import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
-import org.opendaylight.controller.config.manager.impl.jmx.HierarchicalRuntimeBeanRegistrationImpl;
-import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
-
-public class RuntimeBeanRegistratorImplTest extends AbstractLockedPlatformMBeanServerTest {
- private static final String MODULE1 = "module1";
- private static final String INSTANCE_NAME = "instanceName";
- String additionalKey = "key";
- String additionalValue = "value";
- Map<String, String> additionalProperties = ImmutableMap.of(additionalKey, additionalValue);
-
- private BaseJMXRegistrator baseJMXRegistrator;
- private RootRuntimeBeanRegistratorImpl tested;
- private final ModuleIdentifier moduleIdentifier = new ModuleIdentifier(MODULE1, INSTANCE_NAME);
-
- @Before
- public void setUp() {
- baseJMXRegistrator = new BaseJMXRegistrator(ManagementFactory.getPlatformMBeanServer());
- tested = baseJMXRegistrator.createRuntimeBeanRegistrator(moduleIdentifier);
- }
-
- @After
- public void tearDown() {
- tested.close();
- assertEquals(0, baseJMXRegistrator.getRegisteredObjectNames().size());
- }
-
- protected void checkExists(final ObjectName on) throws Exception {
- platformMBeanServer.getMBeanInfo(on);
- }
-
- protected void checkNotExists(final ObjectName on) throws Exception {
- try {
- platformMBeanServer.getMBeanInfo(on);
- fail();
- } catch (final InstanceNotFoundException e) {
- // FIXME: should it be empty?
- }
- }
-
- @Test
- public void testRegisterMBeanWithoutAdditionalProperties() throws Exception {
- createRoot();
- }
-
- private HierarchicalRuntimeBeanRegistrationImpl createRoot() throws Exception {
- HierarchicalRuntimeBeanRegistrationImpl rootRegistration = tested.registerRoot(new TestingRuntimeBean());
-
- ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(MODULE1, INSTANCE_NAME,
- Maps.<String, String>newHashMap());
-
- assertEquals(expectedON1, rootRegistration.getObjectName());
- checkExists(rootRegistration.getObjectName());
- return rootRegistration;
- }
-
- @Test
- public void testRegisterMBeanWithAdditionalProperties() throws Exception {
- HierarchicalRuntimeBeanRegistrationImpl rootRegistration = createRoot();
- createAdditional(rootRegistration);
- }
-
- private HierarchicalRuntimeBeanRegistration createAdditional(
- final HierarchicalRuntimeBeanRegistrationImpl rootRegistration) throws Exception {
-
- HierarchicalRuntimeBeanRegistrationImpl registration = rootRegistration.register(additionalKey, additionalValue,
- new TestingRuntimeBean());
-
- ObjectName expectedON1 = ObjectNameUtil.createRuntimeBeanName(MODULE1, INSTANCE_NAME, additionalProperties);
-
- assertEquals(expectedON1, registration.getObjectName());
- checkExists(registration.getObjectName());
- return registration;
- }
-
- @Test
- public void testCloseRegistration() throws Exception {
- HierarchicalRuntimeBeanRegistrationImpl rootRegistration = createRoot();
- rootRegistration.close();
- checkNotExists(rootRegistration.getObjectName());
- }
-
- @Test
- public void testCloseRegistrator() throws Exception {
- HierarchicalRuntimeBeanRegistrationImpl rootRegistration = createRoot();
- HierarchicalRuntimeBeanRegistration childRegistration = createAdditional(rootRegistration);
- tested.close();
- checkNotExists(rootRegistration.getObjectName());
- checkNotExists(childRegistration.getObjectName());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testRegistration_overrideType() throws Exception {
- HierarchicalRuntimeBeanRegistrationImpl rootRegistration = createRoot();
- rootRegistration.register("type", "xxx", new TestingRuntimeBean());
- }
-
- @Test
- public void testRegistrationException() throws Exception {
- HierarchicalRuntimeBeanRegistrationImpl rootRegistration = createRoot();
- try {
- createRoot();
- fail();
- } catch (final IllegalStateException e) {
- assertThat(e.getMessage(), containsString(rootRegistration.getObjectName().toString()));
- assertThat(e.getMessage(), containsString("Could not register runtime bean"));
- assertThat(e.getMessage(), containsString(moduleIdentifier.toString()));
- }
- }
-
- @Test
- public void testIgnoringExceptionInClose() throws Exception {
- HierarchicalRuntimeBeanRegistrationImpl rootRegistration = createRoot();
- platformMBeanServer.unregisterMBean(rootRegistration.getObjectName());
- rootRegistration.close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.runtimembean;
-
-public class TestingRuntimeBean implements TestingRuntimeBeanMXBean {
-
- @Override
- public int getStat() {
- return 0;
- }
-
- @Override
- public void setStat() {
-
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.runtimembean;
-
-import org.opendaylight.controller.config.api.runtime.RuntimeBean;
-
-public interface TestingRuntimeBeanMXBean extends RuntimeBean {
- int getStat();
-
- void setStat();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.impl.util;
-
-import static org.junit.Assert.assertEquals;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Sets;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-import javax.management.MXBean;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.TestingScheduledThreadPoolServiceInterface;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.TestingThreadPoolServiceInterface;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.yangtools.concepts.Identifiable;
-
-public class InterfacesHelperTest {
-
- public interface SuperA {
-
- }
-
- public interface SuperBMXBean {
-
- }
-
- public interface SuperC extends SuperA, SuperBMXBean {
-
- }
-
- public class SuperClass implements SuperC {
-
- }
-
- @MXBean
- public interface SubA {
-
- }
-
- @ServiceInterfaceAnnotation(value = "a", osgiRegistrationType =
- SuperA.class, namespace = "n", revision = "r", localName = "l")
- public interface Service extends AbstractServiceInterface {
- }
-
- @ServiceInterfaceAnnotation(value = "b", osgiRegistrationType =
- SuperC.class, namespace = "n", revision = "r", localName = "l")
- public interface SubService extends Service {
- }
-
- public abstract class SubClass extends SuperClass implements SubA, Module {
-
- }
-
- public abstract class SubClassWithService implements SubService, Module {
-
- }
-
- @Test
- public void testGetAllInterfaces() {
- Set<Class<?>> expected = Sets.<Class<?>>newHashSet(SuperA.class, SuperBMXBean.class, SuperC.class, SubA.class,
- Identifiable.class, Module.class);
- assertEquals(expected, InterfacesHelper.getAllInterfaces(SubClass.class));
- }
-
- @Test
- public void testGetServiceInterfaces() throws Exception {
- assertEquals(Collections.<Class<?>>emptySet(), InterfacesHelper.getServiceInterfaces(SubClass.class));
- assertEquals(Sets.<Class<?>>newHashSet(Service.class, SubService.class),
- InterfacesHelper.getServiceInterfaces(SubClassWithService.class));
- }
-
- @Test
- public void testGetOsgiRegistrationTypes() throws Exception {
- assertEquals(Collections.<Class<?>>emptySet(), InterfacesHelper.getOsgiRegistrationTypes(SubClass.class));
- assertEquals(Sets.<Class<?>>newHashSet(SuperA.class, SuperC.class),
- InterfacesHelper.getOsgiRegistrationTypes(SubClassWithService.class));
- }
-
- @Test
- public void testGetMXInterfaces() {
- Set<Class<?>> expected = Sets.<Class<?>>newHashSet(SuperBMXBean.class, SubA.class);
- assertEquals(expected, InterfacesHelper.getMXInterfaces(SubClass.class));
- }
-
- @Test
- public void testGetAllAbstractServiceInterfaceClasses() {
- Class<? extends AbstractServiceInterface> clazz = TestingScheduledThreadPoolServiceInterface.class;
- Set<Class<? extends AbstractServiceInterface>> input = new HashSet<>();
- input.add(clazz);
- Set<Class<? extends AbstractServiceInterface>> result = InterfacesHelper
- .getAllAbstractServiceInterfaceClasses(input);
-
- Set<Class<?>> expected = ImmutableSet.of((Class<?>) TestingScheduledThreadPoolServiceInterface.class,
- TestingThreadPoolServiceInterface.class);
- assertEquals(expected, result);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.impl.util;
-
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-import org.junit.Test;
-import org.mockito.InOrder;
-import org.mockito.Mockito;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.BundleTracker;
-import org.osgi.util.tracker.ServiceTracker;
-
-public class OsgiRegistrationUtilTest {
-
- @Test
- public void testRegisterService() throws Exception {
- final BundleContext bundleContext = mock(BundleContext.class);
- ServiceRegistration<?> registration = mockServiceRegistration();
- doReturn(registration).when(bundleContext).registerService(String.class, "string", null);
- ServiceRegistration<?> registration2 = mockServiceRegistration();
- doReturn(registration2).when(bundleContext).registerService(Object.class, "string", null);
-
- AutoCloseable aggregatedRegister = OsgiRegistrationUtil.registerService(bundleContext, "string", String.class,
- Object.class);
- aggregatedRegister.close();
-
- InOrder inOrder = Mockito.inOrder(registration, registration2);
- inOrder.verify(registration2).unregister();
- inOrder.verify(registration).unregister();
- }
-
- @Test
- public void testWrap() throws Exception {
- final ServiceRegistration<?> serviceReg = mockServiceRegistration();
- OsgiRegistrationUtil.wrap(serviceReg).close();
- verify(serviceReg).unregister();
-
- final BundleTracker<?> tracker = mock(BundleTracker.class);
- doNothing().when(tracker).close();
- OsgiRegistrationUtil.wrap(tracker).close();
- verify(tracker).close();
-
- final ServiceTracker<?, ?> sTracker = mock(ServiceTracker.class);
- doNothing().when(sTracker).close();
- OsgiRegistrationUtil.wrap(sTracker).close();
- verify(sTracker).close();
- }
-
- private static ServiceRegistration<?> mockServiceRegistration() {
- ServiceRegistration<?> mock = mock(ServiceRegistration.class);
- doNothing().when(mock).unregister();
- return mock;
- }
-
- @Test
- public void testAggregate() throws Exception {
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.parallelapsp;
-
-public interface TestingAPSP {
-
- int getMaxNumberOfThreads();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.parallelapsp;
-
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-
-@ServiceInterfaceAnnotation(value = TestingParallelAPSPConfigMXBean.NAME,
- osgiRegistrationType = TestingAPSP.class, namespace = "namespace",
- revision = "rev", localName = TestingParallelAPSPConfigMXBean.NAME)
-public interface TestingParallelAPSPConfigMXBean {
-
- String NAME = "apsp";
-
- ObjectName getThreadPool();
-
- void setThreadPool(ObjectName threadPoolName);
-
- String getSomeParam();
-
- void setSomeParam(String string);
-
- // for reporting. this should be moved to runtime jmx bean
- Integer getMaxNumberOfThreads();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.parallelapsp;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import com.google.common.base.Strings;
-import java.io.Closeable;
-import java.io.IOException;
-import javax.annotation.concurrent.NotThreadSafe;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
-
-@NotThreadSafe
-public class TestingParallelAPSPImpl implements TestingAPSP, Closeable {
- public static final int MINIMAL_NUMBER_OF_THREADS = 10;
- private final TestingThreadPoolIfc threadPool;
- private String someParam;
-
- public TestingParallelAPSPImpl(final TestingThreadPoolIfc threadPool,
- final String someParam) {
- checkArgument(
- threadPool.getMaxNumberOfThreads() >= MINIMAL_NUMBER_OF_THREADS,
- "Parameter 'threadPool' has not enough threads");
- checkArgument(Strings.isNullOrEmpty(someParam) == false,
- "Parameter 'someParam' is blank");
- this.threadPool = threadPool;
- this.someParam = someParam;
- }
-
- @Override
- public int getMaxNumberOfThreads() {
- return threadPool.getMaxNumberOfThreads();
- }
-
- @Override
- public void close() throws IOException {
-
- }
-
- TestingThreadPoolIfc getThreadPool() {
- return threadPool;
- }
-
- void setSomeParam(final String string) {
- checkArgument(Strings.isNullOrEmpty(someParam) == false,
- "Parameter 'someParam' is blank");
- this.someParam = string;
- }
-
- public String getSomeParam() {
- return someParam;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.parallelapsp;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Preconditions.checkState;
-
-import com.google.common.base.Strings;
-import java.io.Closeable;
-import javax.annotation.Nullable;
-import javax.annotation.concurrent.NotThreadSafe;
-import javax.management.AttributeNotFoundException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-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.config.api.annotations.RequireInterface;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.TestingThreadPoolServiceInterface;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolConfigMXBean;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
-import org.opendaylight.controller.config.spi.Module;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Represents service that has dependency to thread pool.
- */
-@NotThreadSafe
-public class TestingParallelAPSPModule implements Module, TestingParallelAPSPConfigMXBean {
- private static final Logger LOG = LoggerFactory.getLogger(TestingParallelAPSPModule.class);
-
- private final DependencyResolver dependencyResolver;
- private final AutoCloseable oldCloseable;
- private final TestingParallelAPSPImpl oldInstance;
- private final ModuleIdentifier identifier;
- private ObjectName threadPoolON;
- private TestingParallelAPSPImpl instance;
- private String someParam;
-
- public TestingParallelAPSPModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver,
- @Nullable final AutoCloseable oldCloseable, @Nullable final TestingParallelAPSPImpl oldInstance) {
- this.identifier = identifier;
- this.dependencyResolver = dependencyResolver;
- this.oldCloseable = oldCloseable;
- this.oldInstance = oldInstance;
- }
-
- @Override
- public ObjectName getThreadPool() {
- return threadPoolON;
- }
-
- @RequireInterface(TestingThreadPoolServiceInterface.class)
- @Override
- public void setThreadPool(final ObjectName threadPoolName) {
- this.threadPoolON = threadPoolName;
- }
-
- @Override
- public String getSomeParam() {
- return someParam;
- }
-
- @Override
- public void setSomeParam(final String someParam) {
- this.someParam = someParam;
- }
-
- @Override
- public Integer getMaxNumberOfThreads() {
- if (instance == null) {
- return null;
- }
- return instance.getMaxNumberOfThreads();
- }
-
- // this would be generated:
- private final JmxAttribute threadPoolOnJMXAttribute = new JmxAttribute("threadPoolON");
-
- @Override
- public void validate() {
- checkNotNull(threadPoolON, "Parameter 'threadPool' must be set");
- dependencyResolver.validateDependency(TestingThreadPoolServiceInterface.class, threadPoolON,
- threadPoolOnJMXAttribute);
-
- checkState(Strings.isNullOrEmpty(someParam) == false, "Parameter 'SomeParam' is blank");
- // check that calling resolveInstance fails
- try {
- dependencyResolver.resolveInstance(TestingThreadPoolIfc.class, threadPoolON, threadPoolOnJMXAttribute);
- throw new RuntimeException("fail");
- } catch (final IllegalStateException e) {
- checkState("Commit was not triggered".equals(e.getMessage()), e.getMessage());
- }
-
- // test retrieving dependent module's attribute
- int threadCount;
- try {
- threadCount = (Integer) dependencyResolver.getAttribute(threadPoolON, "ThreadCount");
- } catch (final ReflectionException | InstanceNotFoundException | AttributeNotFoundException
- | MBeanException e) {
- throw new IllegalStateException(e);
- }
- checkState(threadCount > 0);
- TestingThreadPoolConfigMXBean proxy = dependencyResolver.newMXBeanProxy(threadPoolON,
- TestingThreadPoolConfigMXBean.class);
- checkState(threadCount == proxy.getThreadCount());
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- public Closeable getInstance() {
- if (instance == null) {
- TestingThreadPoolIfc threadPoolInstance = dependencyResolver.resolveInstance(TestingThreadPoolIfc.class,
- threadPoolON, threadPoolOnJMXAttribute);
-
- if (oldInstance != null) {
- // changing thread pool is not supported
- boolean reuse = threadPoolInstance == oldInstance.getThreadPool();
- if (reuse) {
- LOG.debug("Reusing old instance");
- instance = oldInstance;
- instance.setSomeParam(someParam);
- }
- }
- if (instance == null) {
- LOG.debug("Creating new instance");
- if (oldCloseable != null) {
- try {
- oldCloseable.close();
- } catch (final Exception e) {
- throw new RuntimeException(e);
- }
- }
- instance = new TestingParallelAPSPImpl(threadPoolInstance, someParam);
- }
- }
- return instance;
- }
-
- @Override
- public boolean canReuse(final Module oldModule) {
- return false;
- }
-
- @Override
- public ModuleIdentifier getIdentifier() {
- return identifier;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.parallelapsp;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-import javax.annotation.concurrent.ThreadSafe;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DependencyResolverFactory;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-@ThreadSafe
-public class TestingParallelAPSPModuleFactory implements ModuleFactory {
-
- public static final String NAME = "parallel";
-
- @Override
- public String getImplementationName() {
- return NAME;
- }
-
- @Override
- public TestingParallelAPSPModule createModule(final String instanceName,
- final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
- return new TestingParallelAPSPModule(new ModuleIdentifier(NAME, instanceName), dependencyResolver, null, null);
- }
-
- @Override
- public TestingParallelAPSPModule createModule(final String instanceName,
- final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old,
- final BundleContext context) throws Exception {
- TestingParallelAPSPImpl oldInstance;
- try {
- oldInstance = (TestingParallelAPSPImpl) old.getInstance();
- } catch (final ClassCastException e) {
- oldInstance = null;
- }
- TestingParallelAPSPModule result = new TestingParallelAPSPModule(new ModuleIdentifier(NAME, instanceName),
- dependencyResolver, old.getInstance(), oldInstance);
- // copy attributes
- String someParam = (String) old.getAttribute("SomeParam");
- result.setSomeParam(someParam);
- ObjectName threadPool = (ObjectName) old.getAttribute("ThreadPool");
- result.setThreadPool(threadPool);
- return result;
- }
-
- @Override
- public boolean isModuleImplementingServiceInterface(
- final Class<? extends AbstractServiceInterface> serviceInterface) {
- return false;
- }
-
- @Override
- public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
- final BundleContext context) {
- return new HashSet<>();
- }
-
- @Override
- public Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces() {
- return Collections.emptySet();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-/**
- * Creates simple bean that has dependency on
- * {@link org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc}.
- */
-package org.opendaylight.controller.config.manager.testingservices.parallelapsp;
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.parallelapsp.test;
-
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPConfigMXBean;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolConfigMXBean;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-
-public abstract class AbstractParallelAPSPTest extends AbstractConfigTest {
- protected final String fixed1 = "fixed1";
- protected final String apsp1 = "apsp-parallel";
-
- protected abstract String getThreadPoolImplementationName();
-
- protected ObjectName createParallelAPSP(
- final ConfigTransactionJMXClient transaction, final ObjectName threadPoolON)
- throws InstanceAlreadyExistsException {
- ObjectName apspName = transaction.createModule(
- TestingParallelAPSPModuleFactory.NAME, apsp1);
- TestingParallelAPSPConfigMXBean parallelAPSPConfigProxy = transaction
- .newMXBeanProxy(apspName, TestingParallelAPSPConfigMXBean.class);
- parallelAPSPConfigProxy.setSomeParam("ahoj");
- parallelAPSPConfigProxy.setThreadPool(threadPoolON);
- return apspName;
- }
-
- protected ObjectName createFixed1(final ConfigTransactionJMXClient transaction,
- final int numberOfThreads) throws InstanceAlreadyExistsException {
-
- ObjectName name = transaction.createModule(
- getThreadPoolImplementationName(), fixed1);
-
- TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction
- .newMXBeanProxy(name, TestingFixedThreadPoolConfigMXBean.class);
- fixedConfigProxy.setThreadCount(numberOfThreads);
-
- return name;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.parallelapsp.test;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.util.Map;
-import javax.management.ObjectName;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.ValidationException.ExceptionMessageWithStackTrace;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPConfigMXBean;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPImpl;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.TestingThreadPoolServiceInterface;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolConfigMXBean;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-
-public class DependentWiringTest extends AbstractParallelAPSPTest {
- private final String fixed1 = "fixed1";
-
- @Before
- public void setUp() {
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,
- new TestingFixedThreadPoolModuleFactory(), new TestingParallelAPSPModuleFactory()));
- }
-
- @After
- public void tearDown() {
- TestingFixedThreadPool.cleanUp();
- }
-
- @Override
- protected String getThreadPoolImplementationName() {
- return TestingFixedThreadPoolModuleFactory.NAME;
- }
-
- @Test
- public void testDependencies() throws Exception {
- ObjectName apspON;
- {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- // create fixed1
- ObjectName threadPoolTransactionON = createFixed1(transaction,
- TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS);
- // create apsp-parallel
- ObjectName apspNameTransactionON = createParallelAPSP(transaction, threadPoolTransactionON);
- TestingParallelAPSPConfigMXBean parallelAPSPConfigProxy = transaction.newMXBeanProxy(apspNameTransactionON,
- TestingParallelAPSPConfigMXBean.class);
- parallelAPSPConfigProxy.setSomeParam("");// trigger validation
- // failure
- try {
- transaction.validateConfig();
- fail();
- } catch (final ValidationException e) {
- for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
- .entrySet()) {
- for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
- assertThat(entry.getValue().getMessage(), containsString("Parameter 'SomeParam' is blank"));
- }
- }
- }
-
- // try committing (validation fails)
- try {
- transaction.commit();
- fail();
- } catch (final ValidationException e) {
- for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
- .entrySet()) {
- for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
- String err = entry.getValue().getMessage();
- assertTrue("Unexpected error message: " + err, err.contains("Parameter 'SomeParam' is blank"));
- }
- }
- }
-
- parallelAPSPConfigProxy.setSomeParam("abc");// fix validation
- // failure
- transaction.commit();
- apspON = ObjectNameUtil.withoutTransactionName(apspNameTransactionON);
- }
-
- // test reported apsp number of threads
- TestingParallelAPSPConfigMXBean parallelAPSPRuntimeProxy = configRegistryClient.newMXBeanProxy(apspON,
- TestingParallelAPSPConfigMXBean.class);
- assertEquals((Integer) TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS,
- parallelAPSPRuntimeProxy.getMaxNumberOfThreads());
-
- // next transaction - recreate new thread pool
- int newNumberOfThreads = TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS * 2;
- {
- // start new transaction
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- ObjectName threadPoolNamesNewTx =
- transaction.lookupConfigBean(getThreadPoolImplementationName(), fixed1);
- TestingFixedThreadPoolConfigMXBean fixedConfigTransactionProxy = transaction
- .newMXBeanProxy(threadPoolNamesNewTx, TestingFixedThreadPoolConfigMXBean.class);
- fixedConfigTransactionProxy.setThreadCount(newNumberOfThreads);
-
- transaction.commit();
- }
- // new reference should be copied to apsp-parallel
- assertEquals((Integer) newNumberOfThreads, parallelAPSPRuntimeProxy.getMaxNumberOfThreads());
- }
-
- @Test
- public void testUsingServiceReferences() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- ObjectName threadPoolON = createFixed1(transaction, 10);
- transaction.lookupConfigBean(getThreadPoolImplementationName(), fixed1);
- String refName = "ref";
- ObjectName serviceReferenceON = transaction.saveServiceReference(TestingThreadPoolServiceInterface.QNAME,
- refName, threadPoolON);
- createParallelAPSP(transaction, serviceReferenceON);
- transaction.commit();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.parallelapsp.test;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.concurrent.Executor;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.manager.impl.ClassBasedModuleFactory;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPImpl;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.TestingThreadPoolServiceInterface;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolConfigMXBean;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-
-public class MockedDependenciesTest extends AbstractParallelAPSPTest {
- private final String threadPoolImplementationName = "mockedthreadpool";
-
- @Before
- public void setUp() {
-
- ClassBasedModuleFactory mockedThreadPoolConfigFactory = new ClassBasedModuleFactory(
- threadPoolImplementationName, MockedThreadPoolModule.class);
-
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,
- new TestingParallelAPSPModuleFactory(),
- mockedThreadPoolConfigFactory));
- }
-
- public interface MockedTestingThreadPoolConfigMXBean extends
- TestingThreadPoolConfigMXBean {
- void setThreadCount(int threadCount);
- }
-
- public static class MockedThreadPoolModule implements Module,
- MockedTestingThreadPoolConfigMXBean,
- TestingThreadPoolServiceInterface {
-
- private final ModuleIdentifier moduleIdentifier;
-
- int threadCount;
-
- public MockedThreadPoolModule(
- final DynamicMBeanWithInstance dynamicMBeanWithInstance, final ModuleIdentifier moduleIdentifier) {
- // no reconfiguration / reuse is supported
- this.moduleIdentifier = moduleIdentifier;
- }
-
- @Override
- public int getThreadCount() {
- return threadCount;
- }
-
- @Override
- public void setThreadCount(final int threadCount) {
- this.threadCount = threadCount;
- }
-
- @Override
- public void validate() {
-
- }
-
- @Override
- public boolean canReuse(final Module oldModule) {
- return false;
- }
-
- @Override
- public Closeable getInstance() {
- return new MockedThreadPool(threadCount);
- }
-
- @Override
- public ModuleIdentifier getIdentifier() {
- return moduleIdentifier;
- }
- }
-
- public static class MockedThreadPool implements TestingThreadPoolIfc,
- Closeable {
- private final int threadCount;
-
- public MockedThreadPool(final int threadCount) {
- this.threadCount = threadCount;
- }
-
- @Override
- public Executor getExecutor() {
- return null;
- }
-
- @Override
- public int getMaxNumberOfThreads() {
- return threadCount;
- }
-
- @Override
- public void close() throws IOException {
-
- }
- }
-
- @Override
- protected String getThreadPoolImplementationName() {
- return threadPoolImplementationName;
- }
-
- @Test
- public void testDependencies() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient
- .createTransaction();
- // create fixed1
- ObjectName threadPoolTransactionON = createFixed1(transaction,
- TestingParallelAPSPImpl.MINIMAL_NUMBER_OF_THREADS);
- // create apsp-parallel
- createParallelAPSP(transaction, threadPoolTransactionON);
-
- transaction.commit();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool;
-
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolConfigMXBean;
-
-public interface TestingScheduledThreadPoolConfigBeanMXBean extends
- TestingThreadPoolConfigMXBean {
-
- boolean isRecreate();
-
- void setRecreate(boolean recreate);
-
- void setThreadCount(int threadCount);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool;
-
-import java.util.concurrent.ScheduledExecutorService;
-
-public interface TestingScheduledThreadPoolIfc {
-
- ScheduledExecutorService getScheduledExecutor();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool;
-
-import com.google.common.collect.Lists;
-import java.io.Closeable;
-import java.util.List;
-import java.util.concurrent.Executor;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import org.opendaylight.controller.config.api.runtime.HierarchicalRuntimeBeanRegistration;
-import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.runtimebeans.TestingScheduledRuntimeBean;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
-
-public class TestingScheduledThreadPoolImpl implements TestingThreadPoolIfc, TestingScheduledThreadPoolIfc, Closeable {
- private static volatile int numberOfCloseMethodCalls = 0;
- private final ScheduledThreadPoolExecutor executor;
- private final RootRuntimeBeanRegistrator runtimeBeanRegistrator;
-
- public static final List<ScheduledThreadPoolExecutor> ALLEXECUTORS = Lists.newLinkedList();
-
- public TestingScheduledThreadPoolImpl(final RootRuntimeBeanRegistrator runtimeBeanRegistrator,
- final int corePoolSize) {
- this.runtimeBeanRegistrator = runtimeBeanRegistrator;
- executor = new ScheduledThreadPoolExecutor(corePoolSize);
- ALLEXECUTORS.add(executor);
- HierarchicalRuntimeBeanRegistration hierarchicalRuntimeBeanRegistration = runtimeBeanRegistrator
- .registerRoot(new TestingScheduledRuntimeBean());
- hierarchicalRuntimeBeanRegistration.register("a", "b", new TestingScheduledRuntimeBean());
- }
-
- @Override
- public void close() {
- numberOfCloseMethodCalls++;
- runtimeBeanRegistrator.close();
- executor.shutdown();
- }
-
- @Override
- public ScheduledExecutorService getScheduledExecutor() {
- return executor;
- }
-
- @Override
- public Executor getExecutor() {
- return executor;
- }
-
- @Override
- public int getMaxNumberOfThreads() {
- return executor.getCorePoolSize();
- }
-
- public static void cleanUp() {
- for (ScheduledThreadPoolExecutor executor : ALLEXECUTORS) {
- executor.shutdown();
- }
- ALLEXECUTORS.clear();
- numberOfCloseMethodCalls = 0;
- }
-
- public static int getNumberOfCloseMethodCalls() {
- return numberOfCloseMethodCalls;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool;
-
-import static com.google.common.base.Preconditions.checkState;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.io.Closeable;
-import javax.annotation.Nullable;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.RuntimeBeanRegistratorAwareModule;
-import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.TestingScheduledThreadPoolServiceInterface;
-import org.opendaylight.controller.config.spi.Module;
-
-/**
- * This class has two exported interfaces and two runtime beans. Recreation is
- * triggered by setting Recreate attribute to true.
- */
-public class TestingScheduledThreadPoolModule implements Module, TestingScheduledThreadPoolConfigBeanMXBean,
- RuntimeBeanRegistratorAwareModule, TestingScheduledThreadPoolServiceInterface {
-
- private final ModuleIdentifier identifier;
- @Nullable
- private final AutoCloseable oldCloseable;
- @Nullable
- private final TestingScheduledThreadPoolImpl oldInstance;
-
- private int threadCount = 10;
- private TestingScheduledThreadPoolImpl instance;
- private RootRuntimeBeanRegistrator runtimeBeanRegistrator;
- private boolean recreate;
-
- public TestingScheduledThreadPoolModule(final ModuleIdentifier identifier,
- @Nullable final AutoCloseable oldCloseable, @Nullable final TestingScheduledThreadPoolImpl oldInstance) {
- this.identifier = identifier;
- this.oldCloseable = oldCloseable;
- this.oldInstance = oldInstance;
- }
-
- @Override
- public void setRuntimeBeanRegistrator(final RootRuntimeBeanRegistrator runtimeBeanRegistrator) {
- this.runtimeBeanRegistrator = runtimeBeanRegistrator;
- }
-
- @Override
- public void validate() {
- assertNull(runtimeBeanRegistrator);
- // check thread count
- checkState(threadCount > 0, "Parameter 'ThreadCount' must be greater than 0");
- }
-
- @Override
- public boolean canReuse(final Module oldModule) {
- return getClass().isInstance(oldModule)
- && getThreadCount() == ((TestingScheduledThreadPoolModule) oldModule).getThreadCount();
- }
-
- @Override
- public int getThreadCount() {
- return threadCount;
- }
-
- @Override
- public void setThreadCount(final int threadCount) {
- this.threadCount = threadCount;
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- public Closeable getInstance() {
- assertNotNull(runtimeBeanRegistrator);
- if (instance == null) {
- if (oldInstance != null && recreate == false) {
- // reuse old instance
- instance = oldInstance;
- }
- if (instance == null) {
- if (oldCloseable != null) {
- try {
- oldCloseable.close();
- } catch (final Exception e) {
- throw new RuntimeException(e);
- }
- }
- // close old threadpool and esp. unregister runtime beans
- instance = new TestingScheduledThreadPoolImpl(runtimeBeanRegistrator, threadCount);
- }
- }
- return instance;
- }
-
- // getters and setters
- @Override
- public boolean isRecreate() {
- return recreate;
- }
-
- @Override
- public void setRecreate(final boolean recreate) {
- this.recreate = recreate;
- }
-
- @Override
- public ModuleIdentifier getIdentifier() {
- return identifier;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool;
-
-import com.google.common.collect.ImmutableSet;
-import java.util.HashSet;
-import java.util.Set;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DependencyResolverFactory;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.TestingScheduledThreadPoolServiceInterface;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.TestingThreadPoolServiceInterface;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-public class TestingScheduledThreadPoolModuleFactory implements ModuleFactory {
- public static final String NAME = "scheduled";
-
- private static Set<Class<? extends AbstractServiceInterface>> ifc = ImmutableSet.of(
- (Class<? extends AbstractServiceInterface>) TestingScheduledThreadPoolServiceInterface.class,
- TestingThreadPoolServiceInterface.class);
-
- @Override
- public boolean isModuleImplementingServiceInterface(
- final Class<? extends AbstractServiceInterface> serviceInterface) {
- return ifc.contains(serviceInterface);
- }
-
- @Override
- public String getImplementationName() {
- return NAME;
- }
-
- @Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
- final BundleContext bundleContext) {
- return new TestingScheduledThreadPoolModule(new ModuleIdentifier(NAME, instanceName), null, null);
- }
-
- @Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
- final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
- TestingScheduledThreadPoolImpl oldInstance;
- try {
- oldInstance = (TestingScheduledThreadPoolImpl) old.getInstance();
- } catch (final ClassCastException e) {
- // happens after OSGi update
- oldInstance = null;
- }
-
- TestingScheduledThreadPoolModule configBean = new TestingScheduledThreadPoolModule(
- new ModuleIdentifier(NAME, instanceName), old.getInstance(), oldInstance);
- // copy attributes
- configBean.setRecreate((Boolean) old.getAttribute("Recreate"));
- return configBean;
- }
-
- @Override
- public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
- final BundleContext bundleContext) {
- return new HashSet<>();
- }
-
- @Override
- public Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces() {
- return ifc;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-/**
- * Tests config bean that exports two independent interfaces -
- * {@link org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolIfc}
- * and
- * {@link org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc}.
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool;
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.runtimebeans;
-
-public class TestingScheduledRuntimeBean implements
- TestingScheduledRuntimeMXBean {
-
- public TestingScheduledRuntimeBean() {
- }
-
- @Override
- public int getActualNumberOfThreads() {
- return 0;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.runtimebeans;
-
-import org.opendaylight.controller.config.api.runtime.RuntimeBean;
-
-public interface TestingScheduledRuntimeMXBean extends RuntimeBean {
-
- int getActualNumberOfThreads();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.test;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.After;
-import org.junit.Before;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
-
-public abstract class AbstractScheduledTest extends AbstractConfigTest {
- protected static final String SCHEDULED1 = "scheduled1";
-
- @Before
- public final void setUp() {
- assertEquals(0,
- TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls());
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,
- new TestingScheduledThreadPoolModuleFactory(),
- new TestingFixedThreadPoolModuleFactory(),
- new TestingParallelAPSPModuleFactory()));
- }
-
- @After
- public final void cleanUp() throws Exception {
- destroyAllConfigBeans();
- TestingScheduledThreadPoolImpl.cleanUp();
- assertEquals(0,
- TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.test;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import java.util.Collections;
-import java.util.List;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolConfigBeanMXBean;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-
-/**
- * TestingScheduledThreadPool exports 2 interfaces: <br>
- * {@link org.opendaylight.controller.config.manager.testingservices
- * .scheduledthreadpool.TestingScheduledThreadPoolModuleFactory#NAME}
- * ,<br>
- * {@link org.opendaylight.controller.config.manager
- * .testingservices.threadpool.TestingFixedThreadPoolModuleFactory#NAME}
- * <br>
- * <br>
- * It also exports 2 runtime beans, one default and one with additional
- * properties of {'a':'b'}.
- */
-public class RuntimeBeanTest extends AbstractScheduledTest {
-
- ObjectName ifc1runtimeON1 = ObjectNameUtil.createRuntimeBeanName(TestingScheduledThreadPoolModuleFactory.NAME,
- SCHEDULED1, Maps.<String, String>newHashMap());
- // additional runtime bean
- ObjectName ifc1runtimeON2 = ObjectNameUtil.createRuntimeBeanName(TestingScheduledThreadPoolModuleFactory.NAME,
- SCHEDULED1, ImmutableMap.of("a", "b"));
-
- List<ObjectName> allObjectNames = Lists.newArrayList(ifc1runtimeON1, ifc1runtimeON2);
-
- private ObjectName createScheduled()
- throws InstanceAlreadyExistsException, ConflictingVersionException, ValidationException {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
-
- // create using TestingThreadPoolIfc:
- ObjectName createdConfigBean = transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME,
- SCHEDULED1);
- // commit
- transaction.commit();
- return createdConfigBean;
- }
-
- @Test
- public void testCreateScheduled() throws Exception {
- createScheduled();
- checkRuntimeBeans();
- }
-
- private void checkRuntimeBeans() throws Exception {
- // check runtime bean - on 2 places
- for (ObjectName on : allObjectNames) {
- checkRuntimeBean(on);
- }
- }
-
- private static void checkRuntimeBean(final ObjectName on) throws Exception {
- assertEquals(0, platformMBeanServer.getAttribute(on, "ActualNumberOfThreads"));
- }
-
- private static void checkRuntimeBeanDoesNotExist(final ObjectName on) throws Exception {
- try {
- checkRuntimeBean(on);
- fail();
- } catch (final InstanceNotFoundException e) {
- // No-op
- }
- }
-
- @Test
- public void testLookup() throws Exception {
- createScheduled();
- assertEquals(Sets.newHashSet(ifc1runtimeON1, ifc1runtimeON2), configRegistryClient.lookupRuntimeBeans());
- }
-
- @Test
- public void testReuse() throws Exception {
- ObjectName createdConfigBean = createScheduled();
- // empty transaction
- CommitStatus commitInfo = configRegistryClient.createTransaction().commit();
-
- // check that it was reused
- ObjectName readableConfigBean = ObjectNameUtil.withoutTransactionName(createdConfigBean);
- List<ObjectName> newInstances = Collections.<ObjectName>emptyList();
- List<ObjectName> reusedInstances = Lists.newArrayList(readableConfigBean);
- List<ObjectName> recreatedInstaces = Collections.<ObjectName>emptyList();
- assertEquals(new CommitStatus(newInstances, reusedInstances, recreatedInstaces), commitInfo);
- checkRuntimeBeans();
- }
-
- @Test
- public void testRecreate() throws Exception {
- ObjectName createdConfigBean = createScheduled();
- // empty transaction
- ConfigTransactionJMXClient configTransaction = configRegistryClient.createTransaction();
- ObjectName scheduledWritableON = configTransaction
- .lookupConfigBean(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
- TestingScheduledThreadPoolConfigBeanMXBean scheduledWritableProxy = configTransaction
- .newMXBeanProxy(scheduledWritableON, TestingScheduledThreadPoolConfigBeanMXBean.class);
- scheduledWritableProxy.setRecreate(true);
- CommitStatus commitInfo = configTransaction.commit();
- // check that it was recreated
- ObjectName readableConfigBean = ObjectNameUtil.withoutTransactionName(createdConfigBean);
- List<ObjectName> newInstances = Collections.<ObjectName>emptyList();
- List<ObjectName> reusedInstances = Collections.<ObjectName>emptyList();
- List<ObjectName> recreatedInstaces = Lists.newArrayList(readableConfigBean);
- assertEquals(new CommitStatus(newInstances, reusedInstances, recreatedInstaces), commitInfo);
- checkRuntimeBeans();
- }
-
- @Test
- public void testDestroy_shouldUnregisterRuntimeBeans() throws Exception {
- ObjectName createdConfigBean = createScheduled();
- ConfigTransactionJMXClient configTransaction = configRegistryClient.createTransaction();
- configTransaction.destroyModule(
- ObjectNameUtil.createTransactionModuleON(configTransaction.getTransactionName(), createdConfigBean));
- configTransaction.commit();
- for (ObjectName on : allObjectNames) {
- checkRuntimeBeanDoesNotExist(on);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.test;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import javax.annotation.Nullable;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.IntrospectionException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPConfigMXBean;
-import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-
-public class TwoInterfacesExportTest extends AbstractScheduledTest {
-
- private void assertExists(final String moduleName, final String instanceName) throws Exception {
- assertExists(null, moduleName, instanceName);
- }
-
- private void assertExists(@Nullable final ConfigTransactionJMXClient transaction, final String moduleName,
- final String instanceName) throws InstanceNotFoundException, IntrospectionException, ReflectionException {
- if (transaction != null) {
- transaction.lookupConfigBean(moduleName, instanceName);
- // make a dummy call
- platformMBeanServer.getMBeanInfo(ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(),
- moduleName, instanceName));
- } else {
- configRegistryClient.lookupConfigBean(moduleName, instanceName);
- // make a dummy call
- platformMBeanServer.getMBeanInfo(ObjectNameUtil.createReadOnlyModuleON(moduleName, instanceName));
- }
- }
-
- private void assertNotExists(final String moduleName, final String instanceName) {
- assertNotExists(null, moduleName, instanceName);
- }
-
- private void assertNotExists(@Nullable final ConfigTransactionJMXClient transaction, final String moduleName,
- final String instanceName) {
-
- if (transaction != null) {
- try {
- transaction.lookupConfigBean(moduleName, instanceName);
- fail();
- } catch (final InstanceNotFoundException e) {
- // FIXME: should be empty?
- }
- } else {
- try {
- configRegistryClient.lookupConfigBean(moduleName, instanceName);
- fail();
- } catch (final InstanceNotFoundException e) {
- // FIXME: should be empty?
- }
- }
- }
-
- @Test
- public void twoInterfaceNamesAfterCreatingConfigBean() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
-
- // create using TestingThreadPoolIfc:
- ObjectName scheduled1name = transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
-
- ObjectName retrievedName = transaction.lookupConfigBean(TestingScheduledThreadPoolModuleFactory.NAME,
- SCHEDULED1);
- assertEquals(scheduled1name, retrievedName);
-
- // getExistingConfigBean should resolve moduleName
- String moduleName = TestingScheduledThreadPoolModuleFactory.NAME;
- retrievedName = transaction.lookupConfigBean(moduleName, SCHEDULED1);
- ObjectName expected = ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(), moduleName,
- SCHEDULED1);
- assertEquals(expected, retrievedName);
-
- // commit
- transaction.commit();
- assertEquals(1, TestingScheduledThreadPoolImpl.ALLEXECUTORS.size());
- assertFalse(TestingScheduledThreadPoolImpl.ALLEXECUTORS.get(0).isTerminated());
- assertEquals(0, TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls());
-
- assertExists(moduleName, SCHEDULED1);
-
- // destroy using ThreadPool ifc
- transaction = configRegistryClient.createTransaction();
- transaction.destroyModule(
- ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(), moduleName, SCHEDULED1));
- transaction.commit();
- assertEquals(1, TestingScheduledThreadPoolImpl.ALLEXECUTORS.size());
- assertTrue(TestingScheduledThreadPoolImpl.ALLEXECUTORS.get(0).isTerminated());
- assertEquals(1, TestingScheduledThreadPoolImpl.getNumberOfCloseMethodCalls());
-
- // should not be in platform:
-
- assertNotExists(moduleName, SCHEDULED1);
-
- transaction = configRegistryClient.createTransaction();
- // should not be in transaction
- assertNotExists(transaction, moduleName, SCHEDULED1);
- }
-
- @Test
- public void tryToRegisterThreadPoolWithSameName() throws InstanceAlreadyExistsException {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
-
- transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
- try {
- transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
- fail();
- } catch (final InstanceAlreadyExistsException e) {
- assertThat(e.getMessage(), containsString(
- "There is an instance registered with name "
- + "ModuleIdentifier{factoryName='scheduled', instanceName='scheduled1'}"));
- }
- }
-
- // --
- @Test
- public void testRegisteringAllIfcNames() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
- transaction.commit();
- assertExists(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
- // another transaction
- transaction = configRegistryClient.createTransaction();
- assertExists(transaction, TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
- }
-
- @Test
- public void testWithAPSP_useScheduledNames() throws InstanceAlreadyExistsException, ValidationException {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- ObjectName scheduledName = transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
-
- ObjectName apspName = transaction.createModule(TestingParallelAPSPModuleFactory.NAME, "apsp1");
- TestingParallelAPSPConfigMXBean apspProxy = transaction.newMXBeanProxy(apspName,
- TestingParallelAPSPConfigMXBean.class);
- apspProxy.setThreadPool(scheduledName);
- apspProxy.setSomeParam("someParam");
- transaction.validateConfig();
-
- }
-
- @Test
- public void testWithAPSP_useIfcNameMismatch() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- transaction.createModule(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1);
-
- ObjectName apspName = transaction.createModule(TestingParallelAPSPModuleFactory.NAME, "apsp1");
- TestingParallelAPSPConfigMXBean apspProxy = transaction.newMXBeanProxy(apspName,
- TestingParallelAPSPConfigMXBean.class);
- apspProxy.setThreadPool(
- ObjectNameUtil.createReadOnlyModuleON(TestingScheduledThreadPoolModuleFactory.NAME, SCHEDULED1));
- apspProxy.setSomeParam("someParam");
- transaction.validateConfig();
- transaction.commit();
-
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.seviceinterface;
-
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingModifiableThreadPoolIfc;
-
-@ServiceInterfaceAnnotation(value = "fqn:modifiable-threadpool",
- osgiRegistrationType = TestingModifiableThreadPoolIfc.class,
- namespace = "foo", revision = "bar", localName = "modifiable-threadpool")
-public interface ModifiableThreadPoolServiceInterface extends TestingThreadPoolServiceInterface {
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.seviceinterface;
-
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolIfc;
-
-@ServiceInterfaceAnnotation(value = "threadpool-scheduled", osgiRegistrationType = TestingScheduledThreadPoolIfc.class,
- namespace = "ns", revision = "rev", localName = "threadpool-scheduled")
-public interface TestingScheduledThreadPoolServiceInterface extends
- TestingThreadPoolServiceInterface {
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.seviceinterface;
-
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
-
-@ServiceInterfaceAnnotation(value = TestingThreadPoolServiceInterface.QNAME,
- osgiRegistrationType = TestingThreadPoolIfc.class,
- namespace = "ns", revision = "foo", localName = "testing-threadpool")
-public interface TestingThreadPoolServiceInterface extends AbstractServiceInterface {
- String QNAME = "(ns?revision=foo)testing-threadpool";
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.threadpool;
-
-import org.opendaylight.yangtools.yang.binding.annotations.ModuleQName;
-
-@ModuleQName(namespace = "namespace", revision = "2012-12-12", name = "name")
-public abstract class AbstractTestingFixedThreadPoolModuleFactory {
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.threadpool;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import com.google.common.collect.Lists;
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.Executor;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadPoolExecutor;
-
-public class TestingFixedThreadPool implements TestingThreadPoolIfc, Closeable,
- TestingModifiableThreadPoolIfc {
- private final ThreadPoolExecutor executorService;
- private final String uniqueName;
-
- public static void cleanUp() {
- for (ExecutorService executorService : ALL_EXECUTORS) {
- executorService.shutdown();
- }
- ALL_EXECUTORS.clear();
- }
-
- // for verification purposes:
- public static final List<ThreadPoolExecutor> ALL_EXECUTORS = Collections
- .synchronizedList(Lists.<ThreadPoolExecutor>newLinkedList());
-
- public TestingFixedThreadPool(final int threadCount, final String uniqueName) {
- checkNotNull(uniqueName);
- this.uniqueName = uniqueName;
- executorService = (ThreadPoolExecutor) Executors
- .newFixedThreadPool(threadCount);
- ALL_EXECUTORS.add(executorService);
- }
-
- @Override
- public Executor getExecutor() {
- return executorService;
- }
-
- @Override
- public void close() throws IOException {
- executorService.shutdown();
- ALL_EXECUTORS.remove(executorService);
-
- }
-
- @Override
- public int getMaxNumberOfThreads() {
- return executorService.getMaximumPoolSize();
- }
-
- public String getUniqueName() {
- return uniqueName;
- }
-
- @Override
- public void setMaximumNumberOfThreads(final int activeCount) {
- checkArgument(activeCount > 0);
- executorService.setMaximumPoolSize(activeCount);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.threadpool;
-
-public interface TestingFixedThreadPoolConfigMXBean extends
- TestingThreadPoolConfigMXBean {
-
- void setThreadCount(int threadCount);
-
- boolean isTriggerNewInstanceCreation();
-
- void setTriggerNewInstanceCreation(boolean boolTest);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.threadpool;
-
-import static com.google.common.base.Preconditions.checkState;
-
-import java.io.Closeable;
-import javax.annotation.Nullable;
-import javax.annotation.concurrent.NotThreadSafe;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.ModifiableThreadPoolServiceInterface;
-import org.opendaylight.controller.config.spi.Module;
-
-@NotThreadSafe
-public class TestingFixedThreadPoolModule implements
- TestingFixedThreadPoolConfigMXBean, Module,
- TestingThreadPoolConfigMXBean, ModifiableThreadPoolServiceInterface {
- private final AutoCloseable oldCloseable;
- private final TestingFixedThreadPool oldInstance;
- private final ModuleIdentifier name;
- private TestingFixedThreadPool instance;
- private int threadCount = 0;
- private boolean triggerNewInstanceCreation;
-
- TestingFixedThreadPoolModule(final ModuleIdentifier name,
- @Nullable final AutoCloseable oldCloseable,
- @Nullable final TestingFixedThreadPool oldInstance) {
- this.name = name;
- this.oldCloseable = oldCloseable;
- this.oldInstance = oldInstance;
- }
-
- // attributes
- @Override
- public void setThreadCount(final int threadCount) {
- this.threadCount = threadCount;
- }
-
- @Override
- public int getThreadCount() {
- return threadCount;
- }
-
- @Override
- public boolean isTriggerNewInstanceCreation() {
- return triggerNewInstanceCreation;
- }
-
- @Override
- public void setTriggerNewInstanceCreation(final boolean triggerNewInstanceCreation) {
- this.triggerNewInstanceCreation = triggerNewInstanceCreation;
- }
-
- // operations
-
- private boolean isReusable() {
- return oldInstance != null;
- }
-
- @Override
- public void validate() {
- checkState(threadCount > 0,
- "Parameter 'threadCount' must be greater than 0");
- }
-
- @Override
- public boolean canReuse(final Module oldModule) {
- return isReusable() && triggerNewInstanceCreation == false;
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- public Closeable getInstance() {
- if (instance == null) {
- if (isReusable() && triggerNewInstanceCreation == false) { // simulate
- // big
- // change
- // using
- // triggerNewInstanceCreation
- oldInstance.setMaximumNumberOfThreads(threadCount);
- instance = oldInstance;
- } else {
- if (oldCloseable != null) {
- try {
- oldCloseable.close();
- } catch (final Exception e) {
- throw new RuntimeException(e);
- }
- }
- instance = new TestingFixedThreadPool(threadCount,
- name.toString());
- }
- }
- return instance;
- }
-
- @Override
- public ModuleIdentifier getIdentifier() {
- return name;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.threadpool;
-
-import com.google.common.collect.ImmutableSet;
-import java.util.HashSet;
-import java.util.Set;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DependencyResolverFactory;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.ModifiableThreadPoolServiceInterface;
-import org.opendaylight.controller.config.manager.testingservices.seviceinterface.TestingThreadPoolServiceInterface;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.osgi.framework.BundleContext;
-
-public class TestingFixedThreadPoolModuleFactory extends AbstractTestingFixedThreadPoolModuleFactory
- implements ModuleFactory {
- public static final String NAME = "fixed";
-
- private static final Set<Class<? extends AbstractServiceInterface>> IFC = ImmutableSet.of(
- (Class<? extends AbstractServiceInterface>) ModifiableThreadPoolServiceInterface.class,
- TestingThreadPoolServiceInterface.class);
-
- @Override
- public String getImplementationName() {
- return NAME;
- }
-
- @Override
- public TestingFixedThreadPoolModule createModule(final String instanceName,
- final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
- return new TestingFixedThreadPoolModule(new ModuleIdentifier(NAME, instanceName), null, null);
- }
-
- @Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
- final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
- int threadCount = (Integer) old.getAttribute("ThreadCount");
- // is the instance compatible?
- TestingFixedThreadPool oldInstance;
- try {
- // reconfigure existing instance
- oldInstance = (TestingFixedThreadPool) old.getInstance();
- } catch (final ClassCastException e) {
- // old instance will be closed, new needs to be created
- oldInstance = null;
- }
- TestingFixedThreadPoolModule result = new TestingFixedThreadPoolModule(new ModuleIdentifier(NAME, instanceName),
- old.getInstance(), oldInstance);
- result.setThreadCount(threadCount);
- return result;
- }
-
- @Override
- public boolean isModuleImplementingServiceInterface(
- final Class<? extends AbstractServiceInterface> serviceInterface) {
- return IFC.contains(serviceInterface);
- }
-
- @Override
- public Set<Module> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory,
- final BundleContext bundleContext) {
- return new HashSet<>();
- }
-
- @Override
- public Set<Class<? extends AbstractServiceInterface>> getImplementedServiceIntefaces() {
- return IFC;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.threadpool;
-
-public interface TestingModifiableThreadPoolIfc extends TestingThreadPoolIfc {
- void setMaximumNumberOfThreads(int activeCount);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.threadpool;
-
-public interface TestingThreadPoolConfigMXBean {
-
- int getThreadCount();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.threadpool;
-
-import java.util.concurrent.Executor;
-
-public interface TestingThreadPoolIfc {
-
- Executor getExecutor();
-
- int getMaxNumberOfThreads();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-/**
- * Represents simple service that has getters and setters, but no dependencies.
- * Creates fixed thread pool wrapped in {@link org.opendaylight
- * .controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc}.
- * Supports changing the number of threads on 'live' executor.
- */
-package org.opendaylight.controller.config.manager.testingservices.threadpool;
+++ /dev/null
-/*
- * Copyright (c) 2014, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.manager.testingservices.threadpool.test;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.doReturn;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Maps;
-import java.util.Collections;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import org.osgi.framework.BundleContext;
-
-public class ShutdownTest extends AbstractConfigTest {
- private final TestingFixedThreadPoolModuleFactory testingFixedThreadPoolModuleFactory =
- new TestingFixedThreadPoolModuleFactory();
-
- @Mock
- ModuleFactoriesResolver mockedResolver;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- Map<String, Entry<ModuleFactory, BundleContext>> allFactories = ImmutableMap.of(
- testingFixedThreadPoolModuleFactory.getImplementationName(),
- Maps.<ModuleFactory, BundleContext>immutableEntry(testingFixedThreadPoolModuleFactory, mockedContext));
- doReturn(allFactories).when(mockedResolver).getAllFactories();
- super.initConfigTransactionManagerImpl(mockedResolver);
- }
-
- @Test
- public void testCreateAndDestroyBeanInSameTransaction() throws Exception {
- {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- SimpleConfigurationTest.createFixedThreadPool(transaction);
- transaction.commit();
- }
- assertEquals(1, TestingFixedThreadPool.ALL_EXECUTORS.size());
- doReturn(Collections.emptyMap()).when(mockedResolver).getAllFactories();
- {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- transaction.commit();
- }
- assertEquals(1, TestingFixedThreadPool.ALL_EXECUTORS.size());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.manager.testingservices.threadpool.test;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import com.google.common.collect.Sets;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ThreadPoolExecutor;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.IntrospectionException;
-import javax.management.MBeanException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.ValidationException.ExceptionMessageWithStackTrace;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolConfigMXBean;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPoolModuleFactory;
-import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingThreadPoolIfc;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-
-/**
- * Tests basic functionality of configuration registry:
- * <ol>
- * <li>Creation of instance</li>
- * <li>Destruction of instance</li>
- * <li>Reconfiguration of live object</li>
- * <li>Reconfiguration that triggers new object creation</li>
- * <li>Replacement of running instance with different one with same name</li>
- * </ol>
- * Only one bean is being configured - {@link TestingThreadPoolIfc} which has no
- * dependencies.
- */
-public class SimpleConfigurationTest extends AbstractConfigTest {
- private static final int NUMBER_OF_THREADS = 5;
- private static final int NUMBER_OF_THREADS2 = 10;
- private static final String FIXED1 = "fixed1";
- private static final List<ObjectName> EMPTYO_NS = Collections.<ObjectName>emptyList();
- private static final ObjectName PLATFORM_FIXED1ON = ObjectNameUtil
- .createReadOnlyModuleON(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
- private static final List<ObjectName> FIXED1_LIST = Arrays.asList(PLATFORM_FIXED1ON);
-
- @Before
- public void setUp() {
- super.initConfigTransactionManagerImpl(
- new HardcodedModuleFactoriesResolver(mockedContext, new TestingFixedThreadPoolModuleFactory()));
- }
-
- @After
- public void tearDown() {
- TestingFixedThreadPool.cleanUp();
- }
-
- private ObjectName firstCommit() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
-
- ObjectName fixed1names = createFixedThreadPool(transaction);
-
- // commit
- assertEquals(1, configRegistryClient.getOpenConfigs().size());
- CommitStatus commitStatus = transaction.commit();
- assertEquals(0, configRegistryClient.getOpenConfigs().size());
- CommitStatus expected = new CommitStatus(Arrays.asList(ObjectNameUtil.withoutTransactionName(fixed1names)),
- EMPTYO_NS, EMPTYO_NS);
- assertEquals(expected, commitStatus);
-
- assertEquals(1, TestingFixedThreadPool.ALL_EXECUTORS.size());
- assertFalse(TestingFixedThreadPool.ALL_EXECUTORS.get(0).isShutdown());
- return fixed1names;
- }
-
- static ObjectName createFixedThreadPool(final ConfigTransactionJMXClient transaction)
- throws InstanceAlreadyExistsException, InstanceNotFoundException {
- transaction.assertVersion(0, 1);
-
- ObjectName fixed1names = transaction.createModule(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
- TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(fixed1names,
- TestingFixedThreadPoolConfigMXBean.class);
- fixedConfigProxy.setThreadCount(NUMBER_OF_THREADS);
-
- ObjectName retrievedNames = transaction.lookupConfigBean(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
- assertEquals(fixed1names, retrievedNames);
- return fixed1names;
- }
-
- @Test
- public void testCreateAndDestroyBeanInSameTransaction() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- ObjectName fixed1names = createFixedThreadPool(transaction);
- transaction.destroyModule(fixed1names);
- CommitStatus commitStatus = transaction.commit();
- assertStatus(commitStatus, 0, 0, 0);
-
- }
-
- @Test
- public void testValidationUsingJMXClient() throws Exception {
- ConfigTransactionClient transaction = configRegistryClient.createTransaction();
- testValidation(transaction);
- }
-
- private static void testValidation(final ConfigTransactionClient transaction) throws InstanceAlreadyExistsException,
- ReflectionException, InstanceNotFoundException, MBeanException, ConflictingVersionException {
- ObjectName fixed1names = transaction.createModule(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
- // call validate on config bean
- try {
- platformMBeanServer.invoke(fixed1names, "validate", new Object[0], new String[0]);
- fail();
- } catch (final MBeanException e) {
- Exception targetException = e.getTargetException();
- assertNotNull(targetException);
- assertEquals(ValidationException.class, targetException.getClass());
- }
-
- // validate config bean
- try {
- transaction.validateBean(fixed1names);
- fail();
- } catch (final ValidationException e) {
- for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
- .entrySet()) {
- for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
- assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage());
- }
- }
- }
- // validate transaction
- try {
- transaction.validateConfig();
- fail();
- } catch (final ValidationException e) {
- for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
- .entrySet()) {
- for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
- assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage());
- }
- }
- }
- try {
- transaction.commit();
- } catch (final ValidationException e) {
- for (Map.Entry<String, Map<String, ExceptionMessageWithStackTrace>> exception : e.getFailedValidations()
- .entrySet()) {
- for (Map.Entry<String, ExceptionMessageWithStackTrace> entry : exception.getValue().entrySet()) {
- assertEquals("Parameter 'threadCount' must be greater than 0", entry.getValue().getMessage());
- }
- }
- }
- }
-
- @Test
- public void test_createThreadPool_changeNumberOfThreads() throws Exception {
- firstCommit();
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- TestingFixedThreadPoolConfigMXBean fixedConfigProxy = startReconfiguringFixed1ThreadPool(transaction);
- assertEquals(NUMBER_OF_THREADS, fixedConfigProxy.getThreadCount());
- fixedConfigProxy.setThreadCount(NUMBER_OF_THREADS2);
- CommitStatus commitStatus = transaction.commit();
- checkThreadPools(1, NUMBER_OF_THREADS2);
- CommitStatus expected = new CommitStatus(EMPTYO_NS, FIXED1_LIST, EMPTYO_NS);
- assertEquals(expected, commitStatus);
- }
-
- @Test
- public void test_createFixedThreadPool_destroyIt() throws Exception {
- // 1, start transaction, create new fixed thread pool
- ObjectName fixed1name = firstCommit();
-
- // 2, check that configuration was copied to platform
- ObjectName on = ObjectNameUtil.withoutTransactionName(fixed1name);
- platformMBeanServer.getMBeanInfo(on);
- assertEquals(NUMBER_OF_THREADS, platformMBeanServer.getAttribute(on, "ThreadCount"));
-
- // 3, shutdown fixed1 in new transaction
- assertFalse(TestingFixedThreadPool.ALL_EXECUTORS.get(0).isShutdown());
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
-
- // check versions
- transaction.assertVersion(1, 2);
-
- // test that it was copied to new transaction
- ObjectName retrievedName = transaction.lookupConfigBean(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
- assertNotNull(retrievedName);
-
- // check that number of threads was copied from dynamic
-
- TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(retrievedName,
- TestingFixedThreadPoolConfigMXBean.class);
- assertEquals(NUMBER_OF_THREADS, fixedConfigProxy.getThreadCount());
-
- // destroy
- transaction.destroyModule(ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(),
- TestingFixedThreadPoolModuleFactory.NAME, FIXED1));
- transaction.commit();
-
- // 4, check
- assertEquals(2, configRegistryClient.getVersion());
- assertEquals(0, TestingFixedThreadPool.ALL_EXECUTORS.size());
-
- // dynamic config should be removed from platform
- try {
- platformMBeanServer.getMBeanInfo(on);
- fail();
- } catch (final ReflectionException | InstanceNotFoundException | IntrospectionException e) {
- assertTrue(e instanceof InstanceNotFoundException);
- }
- }
-
- @Test
- public void testReplaceFixed1() throws Exception {
- // 1, start transaction, create new fixed thread pool
- firstCommit();
- // destroy and recreate with different # of threads
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
-
- transaction.destroyModule(ObjectNameUtil.createTransactionModuleON(transaction.getTransactionName(),
- TestingFixedThreadPoolModuleFactory.NAME, FIXED1));
-
- ObjectName fixed1name = transaction.createModule(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
- TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(fixed1name,
- TestingFixedThreadPoolConfigMXBean.class);
- fixedConfigProxy.setThreadCount(NUMBER_OF_THREADS2);
- // commit
- transaction.commit();
- // check that first threadpool is closed
- checkThreadPools(1, NUMBER_OF_THREADS2);
- }
-
- private static void checkThreadPools(final int expectedTotalNumberOfExecutors,
- final int expectedNumberOfThreadsInLastExecutor) {
- assertEquals(expectedTotalNumberOfExecutors, TestingFixedThreadPool.ALL_EXECUTORS.size());
- for (int i = 0; i < expectedTotalNumberOfExecutors - 1; i++) {
- assertTrue(TestingFixedThreadPool.ALL_EXECUTORS.get(i).isShutdown());
- }
- ThreadPoolExecutor lastExecutor = TestingFixedThreadPool.ALL_EXECUTORS.get(expectedTotalNumberOfExecutors - 1);
- assertFalse(lastExecutor.isShutdown());
- assertEquals(expectedNumberOfThreadsInLastExecutor, lastExecutor.getMaximumPoolSize());
- }
-
- @Test
- public void testTriggerRecreatingInstance() throws Exception {
- // 1, start transaction, create new fixed thread pool
- firstCommit();
- // switch boolean to create new instance
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- TestingFixedThreadPoolConfigMXBean fixedConfigProxy = startReconfiguringFixed1ThreadPool(transaction);
-
- fixedConfigProxy.setTriggerNewInstanceCreation(true);
- // commit
- CommitStatus commitStatus = transaction.commit();
- // check that new threadpool is created and old one is closed
- checkThreadPools(1, NUMBER_OF_THREADS);
- CommitStatus expected = new CommitStatus(EMPTYO_NS, EMPTYO_NS, FIXED1_LIST);
- assertEquals(expected, commitStatus);
- }
-
- // return MBeanProxy for 'fixed1' and current transaction
- private static TestingFixedThreadPoolConfigMXBean startReconfiguringFixed1ThreadPool(
- final ConfigTransactionJMXClient transaction) throws InstanceNotFoundException {
- ObjectName fixed1name = transaction.lookupConfigBean(TestingFixedThreadPoolModuleFactory.NAME, FIXED1);
-
- TestingFixedThreadPoolConfigMXBean fixedConfigProxy = transaction.newMXBeanProxy(fixed1name,
- TestingFixedThreadPoolConfigMXBean.class);
- return fixedConfigProxy;
- }
-
- @Test
- public void testAbort() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- assertEquals(1, configRegistryClient.getOpenConfigs().size());
-
- transaction.abortConfig();
- assertEquals(0, configRegistryClient.getOpenConfigs().size());
- try {
- platformMBeanServer.getMBeanInfo(transaction.getObjectName());
- fail();
- } catch (final InstanceNotFoundException e) {
- assertEquals("org.opendaylight.controller:TransactionName=ConfigTransaction-0-1,type=ConfigTransaction",
- e.getMessage());
- }
- }
-
- @Test
- public void testOptimisticLock_ConfigTransactionClient() throws Exception {
- ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction();
- ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction();
- transaction2.assertVersion(0, 2);
- transaction2.commit();
- try {
- transaction1.commit();
- fail();
- } catch (final ConflictingVersionException e) {
- assertEquals("Optimistic lock failed. Expected parent version 2, was 0", e.getMessage());
- }
- }
-
- @Test
- public void testOptimisticLock_ConfigRegistry() throws Exception {
- ConfigTransactionJMXClient transaction1 = configRegistryClient.createTransaction();
- ConfigTransactionJMXClient transaction2 = configRegistryClient.createTransaction();
- transaction2.assertVersion(0, 2);
- transaction2.commit();
- try {
- configRegistryClient.commitConfig(transaction1.getObjectName());
- fail();
- } catch (final ConflictingVersionException e) {
- assertEquals("Optimistic lock failed. Expected parent version 2, was 0", e.getMessage());
- }
- }
-
- @Test
- public void testQNames() {
- Set<String> availableModuleFactoryQNames = configRegistryClient.getAvailableModuleFactoryQNames();
- String expected = "(namespace?revision=2012-12-12)name";
-
- assertEquals(Sets.newHashSet(expected), availableModuleFactoryQNames);
- }
-}
+++ /dev/null
-org.opendaylight.controller.config.manager.impl.osgi.ModuleFactoryBundleTrackerTest$NotExtendingTestingFactory
\ No newline at end of file
+++ /dev/null
-org.opendaylight.controller.config.manager.impl.osgi.ModuleFactoryBundleTrackerTest$TestingFactory
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
- Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<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.odlparent</groupId>
- <artifactId>bundle-parent</artifactId>
- <version>3.1.0</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-netty-config</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <description>Configuration files for sal-rest-connector</description>
- <packaging>bundle</packaging>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-artifacts</id>
- <goals>
- <goal>attach-artifact</goal>
- </goals>
- <phase>package</phase>
- <configuration>
- <artifacts>
- <artifact>
- <file>src/main/config/default-config.xml</file>
- <type>xml</type>
- <classifier>config</classifier>
- </artifact>
- </artifacts>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
- Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
-
- NOTE: This file is deprecated as wiring is now done via blueprint. This file is kept for
- backwards compatibility. Runtime modifications are not honored.
--->
-<snapshot>
- <required-capabilities>
- <capability>urn:opendaylight:params:xml:ns:yang:controller:netty?module=netty&revision=2013-11-19</capability>
- <capability>urn:opendaylight:params:xml:ns:yang:controller:netty:eventexecutor?module=netty-event-executor&revision=2013-11-12</capability>
- <capability>urn:opendaylight:params:xml:ns:yang:controller:netty:threadgroup?module=threadgroup&revision=2013-11-07</capability>
- <capability>urn:opendaylight:params:xml:ns:yang:controller:netty:timer?module=netty-timer&revision=2013-11-19</capability>
- </required-capabilities>
- <configuration>
-
- <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
- <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
- <module>
- <type xmlns:netty="urn:opendaylight:params:xml:ns:yang:controller:netty:threadgroup">netty:netty-threadgroup-fixed</type>
- <name>global-boss-group</name>
- </module>
- <module>
- <type xmlns:netty="urn:opendaylight:params:xml:ns:yang:controller:netty:threadgroup">netty:netty-threadgroup-fixed</type>
- <name>global-worker-group</name>
- </module>
- <module>
- <type xmlns:netty="urn:opendaylight:params:xml:ns:yang:controller:netty:timer">netty:netty-hashed-wheel-timer</type>
- <name>global-timer</name>
- </module>
- <module>
- <type xmlns:netty="urn:opendaylight:params:xml:ns:yang:controller:netty:eventexecutor">netty:netty-global-event-executor</type>
- <name>singleton</name>
- </module>
- </modules>
-
- <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
- <service>
- <type xmlns:netty="urn:opendaylight:params:xml:ns:yang:controller:netty">netty:netty-threadgroup</type>
- <instance>
- <name>global-boss-group</name>
- <provider>/modules/module[type='netty-threadgroup-fixed'][name='global-boss-group']</provider>
- </instance>
- <instance>
- <name>global-worker-group</name>
- <provider>/modules/module[type='netty-threadgroup-fixed'][name='global-worker-group']</provider>
- </instance>
- </service>
- <service>
- <type xmlns:netty="urn:opendaylight:params:xml:ns:yang:controller:netty">netty:netty-event-executor</type>
- <instance>
- <name>global-event-executor</name>
- <provider>/modules/module[type='netty-global-event-executor'][name='singleton']</provider>
- </instance>
- </service>
- <service>
- <type xmlns:netty="urn:opendaylight:params:xml:ns:yang:controller:netty">netty:netty-timer</type>
- <instance>
- <name>global-timer</name>
- <provider>/modules/module[type='netty-hashed-wheel-timer'][name='global-timer']</provider>
- </instance>
- </service>
- </services>
- </data>
-
- </configuration>
-</snapshot>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-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
--->
-<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">
- <parent>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>binding-parent</artifactId>
- <version>0.13.0-SNAPSHOT</version>
- <relativePath/>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-parent</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <packaging>pom</packaging>
-
- <properties>
- <config.version>0.9.0-SNAPSHOT</config.version>
- <mdsal.version>1.8.0-SNAPSHOT</mdsal.version>
- <yangtools.version>2.0.5</yangtools.version>
- <jmxGeneratorPath>${project.build.directory}/generated-sources/config-binding</jmxGeneratorPath>
- <config.file>src/main/config/default-config.xml</config.file>
- </properties>
-
- <dependencyManagement>
- <dependencies>
- <!-- project specific dependencies -->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-artifacts</artifactId>
- <version>${config.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>mdsal-artifacts</artifactId>
- <version>${mdsal.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yangtools-artifacts</artifactId>
- <version>2.0.5</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-artifacts</artifactId>
- <version>2.5.0-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-common</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-api</artifactId>
- </dependency>
- </dependencies>
- <build>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-maven-plugin</artifactId>
- <version>2.0.5</version>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator-plugin</artifactId>
- <version>${config.version}</version>
- </dependency>
- </dependencies>
- <executions>
- <execution>
- <id>config</id>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
- <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
- <additionalConfiguration>
- <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
- </additionalConfiguration>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <artifactId>maven-clean-plugin</artifactId>
- <configuration>
- <filesets>
- <fileset>
- <directory>${jmxGeneratorPath}</directory>
- <includes>
- <include>**</include>
- </includes>
- </fileset>
- <fileset>
- <directory>${salGeneratorPath}</directory>
- <includes>
- <include>**</include>
- </includes>
- </fileset>
- </filesets>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>add-yang-sources</id>
- <phase>generate-sources</phase>
- <goals>
- <goal>add-source</goal>
- </goals>
- <configuration>
- <sources>
- <source>${jmxGeneratorPath}</source>
- <source>${salGeneratorPath}</source>
- </sources>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- <!-- This has to match the definition in odlparent and exists only
- because for some reason PMD does not understand wildcards. -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-pmd-plugin</artifactId>
- <executions>
- <execution>
- <id>cpd</id>
- <phase>process-sources</phase>
- <goals>
- <goal>cpd-check</goal>
- </goals>
- <configuration>
- <excludeRoots>
- <excludeRoot>${jmxGeneratorPath}</excludeRoot>
- <excludeRoot>${salGeneratorPath}</excludeRoot>
- </excludeRoots>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
- <profiles>
- <profile>
- <id>attach-config-without-filtering</id>
- <activation>
- <file>
- <exists>${config.file}</exists>
- </file>
- </activation>
- <build>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-artifacts</id>
- <goals>
- <goal>attach-artifact</goal>
- </goals>
- <phase>package</phase>
- <configuration>
- <artifacts>
- <artifact>
- <file>${config.file}</file>
- <type>xml</type>
- <classifier>config</classifier>
- </artifact>
- </artifacts>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
+++ /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>config-subsystem</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>config-persister-api</artifactId>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-util</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- </plugin>
- <!-- test jar -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- <phase>package</phase>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.api;
-
-import java.util.List;
-
-/*
- * The config pusher service pushes configs into the config subsystem
- */
-public interface ConfigPusher {
-
- /*
- * Pushes configs into the config subsystem
- */
-
- void pushConfigs(List<? extends ConfigSnapshotHolder> configs) throws InterruptedException;
-}
+++ /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.config.persist.api;
-
-import java.util.SortedSet;
-
-public interface ConfigSnapshotHolder {
-
- /**
- * Get XML node that should be pushed to netconf's edit-config.
- */
- String getConfigSnapshot();
-
-
- /**
- * Get only required capabilities referenced by the snapshot.
- * If no value is specified, return empty set instead of null
- */
- SortedSet<String> getCapabilities();
-}
+++ /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.config.persist.api;
-
-import java.util.SortedSet;
-
-public class ConfigSnapshotHolderImpl implements ConfigSnapshotHolder {
-
- private final String snapshot;
- private final SortedSet<String> caps;
- private final String fileName;
-
- public ConfigSnapshotHolderImpl(final String configSnapshot,
- final SortedSet<String> capabilities,
- final String fileName) {
- this.snapshot = configSnapshot;
- this.caps = capabilities;
- this.fileName = fileName;
- }
-
- @Override
- public String getConfigSnapshot() {
- return snapshot;
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return caps;
- }
-
- public String getFileName() {
- return fileName;
- }
-
- @Override
- public String toString() {
- return "snapshot='" + "ConfigSnapshotHolderImpl{"
- + snapshot + '\'' + ", caps="
- + caps + ", fileName='"
- + fileName + '\'' + '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.api;
-
-import java.io.IOException;
-import java.util.List;
-
-/**
- * Base interface for persister implementation.
- */
-public interface Persister extends AutoCloseable {
-
- void persistConfig(ConfigSnapshotHolder configSnapshotHolder) throws IOException;
-
- List<ConfigSnapshotHolder> loadLastConfigs() throws IOException;
-
- @Override
- void close();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.api;
-
-public interface PropertiesProvider {
- /**
- * Get property value for given key. Implementation of this interface is allowed to prefix
- * the key with a namespace.
- */
- String getProperty(String key);
-
- /**
- * Get full key reporting.
- *
- * @return prefix + key as used in getProperty method.
- */
- String getFullKeyForReporting(String key);
-
- String getPrefix();
-
- String getPropertyWithoutPrefix(String fullKey);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.api;
-
-/**
- * Plugins for {@link org.opendaylight.controller.config.persist.api.Persister}
- * must implement this interface.
- */
-public interface StorageAdapter {
-
- Persister instantiate(PropertiesProvider propertiesProvider);
-
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.test;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-
-public class PropertiesProviderTest implements PropertiesProvider {
- private final Map<String, String> properties = new HashMap<>();
-
- public void addProperty(final String key, final String value) {
- properties.put(key, value);
- }
-
- @Override
- public String getProperty(final String key) {
- return properties.get(key);
- }
-
- @Override
- public String getFullKeyForReporting(final String key) {
- return null;
- }
-
- @Override
- public String getPrefix() {
- return null;
- }
-
- @Override
- public String getPropertyWithoutPrefix(final String fullKey) {
- return null;
- }
-}
+++ /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>config-subsystem</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>config-persister-directory-xml-adapter</artifactId>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
-
- <dependencies>
- <!-- compile dependencies -->
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-api</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.validation</groupId>
- <artifactId>validation-api</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.eclipse.persistence</groupId>
- <artifactId>org.eclipse.persistence.core</artifactId>
- </dependency>
- <!-- Persistence core has optional dependencies on JTA, javax.mail and antlr -->
- <dependency>
- <groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-jta_1.1_spec</artifactId>
- <!-- TODO Add this to odlparent dependency management -->
- <version>1.1.1</version>
- </dependency>
- <dependency>
- <groupId>javax.mail</groupId>
- <artifactId>mail</artifactId>
- <!-- TODO Add this to odlparent dependency management -->
- <version>1.4.4</version>
- </dependency>
- <dependency>
- <groupId>org.eclipse.persistence</groupId>
- <artifactId>org.eclipse.persistence.antlr</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.eclipse.persistence</groupId>
- <artifactId>org.eclipse.persistence.moxy</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-file-xml-adapter</artifactId>
- </dependency>
-
- <!-- test dependencies -->
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>xmlunit</groupId>
- <artifactId>xmlunit</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-api</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
-
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Fragment-Host>${project.groupId}.config-persister-impl</Fragment-Host>
- <Provide-Capability>org.opendaylight.controller.config.persister.storage.adapter</Provide-Capability>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.storage.directory.xml;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import com.google.common.base.Optional;
-import com.google.common.io.Files;
-
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.SortedSet;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.transform.stream.StreamSource;
-
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class XmlDirectoryPersister implements Persister {
- private static final Logger LOG = LoggerFactory.getLogger(XmlDirectoryPersister.class);
-
- private final File storage;
- private final Optional<FilenameFilter> extensionsFilter;
-
- /**
- * Creates XmlDirectoryPersister that picks up all files in specified folder.
- */
- public XmlDirectoryPersister(final File storage) {
- this(storage, Optional.<FilenameFilter>absent());
- }
-
- /**
- * Creates XmlDirectoryPersister that picks up files only with specified file extension.
- */
- public XmlDirectoryPersister(final File storage, final Set<String> fileExtensions) {
- this(storage, Optional.of(getFilter(fileExtensions)));
- }
-
- private XmlDirectoryPersister(final File storage, final Optional<FilenameFilter> extensionsFilter) {
- checkArgument(storage.exists() && storage.isDirectory(), "Storage directory does not exist: " + storage);
- this.storage = storage;
- this.extensionsFilter = extensionsFilter;
- }
-
- @Override
- public void persistConfig(final ConfigSnapshotHolder holder) throws IOException {
- throw new UnsupportedOperationException("This adapter is read only. Please set readonly=true on " + getClass());
- }
-
- @Override
- public List<ConfigSnapshotHolder> loadLastConfigs() throws IOException {
- File[] filesArray =
- extensionsFilter.isPresent() ? storage.listFiles(extensionsFilter.get()) : storage.listFiles();
- if (filesArray == null || filesArray.length == 0) {
- return Collections.emptyList();
- }
- List<File> sortedFiles = new ArrayList<>(Arrays.asList(filesArray));
- Collections.sort(sortedFiles);
- // combine all found files
- LOG.debug("Reading files in following order: {}", sortedFiles);
-
- List<ConfigSnapshotHolder> result = new ArrayList<>();
- for (File file : sortedFiles) {
- LOG.trace("Adding file '{}' to combined result", file);
- Optional<ConfigSnapshotHolder> configSnapshotHolderOptional = fromXmlSnapshot(file);
- // Ignore non valid snapshot
- if (!configSnapshotHolderOptional.isPresent()) {
- continue;
- }
-
- result.add(configSnapshotHolderOptional.get());
- }
- return result;
- }
-
- private Optional<ConfigSnapshotHolder> fromXmlSnapshot(final File file) {
- try {
- return Optional.of(loadLastConfig(file));
- } catch (final JAXBException e) {
- // In case of parse error, issue a warning, ignore and continue
- LOG.warn(
- "Unable to parse configuration snapshot from {}. "
- + "Initial config from {} will be IGNORED in this run. ",
- file, file);
- LOG.warn(
- "Note that subsequent config files may fail due to this problem. ",
- "Xml markup in this file needs to be fixed, for detailed information see enclosed exception.",
- e);
- }
-
- return Optional.absent();
- }
-
- public static ConfigSnapshotHolder loadLastConfig(final File file) throws JAXBException {
- JAXBContext jaxbContext = JAXBContext.newInstance(ConfigSnapshot.class);
- Unmarshaller um = jaxbContext.createUnmarshaller();
- XMLInputFactory xif = XMLInputFactory.newFactory();
- xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
- xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
- try {
- XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(file));
- return asHolder((ConfigSnapshot) um.unmarshal(xsr));
- } catch (final XMLStreamException e) {
- throw new JAXBException(e);
- }
- }
-
- private static ConfigSnapshotHolder asHolder(final ConfigSnapshot unmarshalled) {
- return new ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- return unmarshalled.getConfigSnapshot();
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return unmarshalled.getCapabilities();
- }
-
- @Override
- public String toString() {
- return unmarshalled.toString();
- }
- };
- }
-
- private static FilenameFilter getFilter(final Set<String> fileExtensions) {
- checkArgument(!fileExtensions.isEmpty(), "No file extension provided", fileExtensions);
-
- return (dir, name) -> {
- String ext = Files.getFileExtension(name);
- return fileExtensions.contains(ext);
- };
- }
-
- @Override
- public void close() {
- }
-
- @Override
- public String toString() {
- return "XmlDirectoryPersister{storage=" + storage + "}";
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.storage.directory.xml;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Splitter;
-import com.google.common.collect.Sets;
-
-import java.io.File;
-import java.util.Set;
-
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-import org.opendaylight.controller.config.persist.api.StorageAdapter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * StorageAdapter that retrieves initial configuration from a directory. If multiple files are present, snapshot and
- * required capabilities will be merged together. Writing to this persister is not supported.
- */
-public class XmlDirectoryStorageAdapter implements StorageAdapter {
- private static final Logger LOG = LoggerFactory.getLogger(XmlDirectoryStorageAdapter.class);
-
- public static final String DIRECTORY_STORAGE_PROP = "directoryStorage";
- public static final String INCLUDE_EXT_PROP = "includeExtensions";
- private static final char EXTENSIONS_SEPARATOR = ',';
-
- @Override
- public Persister instantiate(final PropertiesProvider propertiesProvider) {
- String fileStorageProperty = propertiesProvider.getProperty(DIRECTORY_STORAGE_PROP);
- Preconditions.checkNotNull(fileStorageProperty,
- "Unable to find " + propertiesProvider.getFullKeyForReporting(DIRECTORY_STORAGE_PROP));
- File storage = new File(fileStorageProperty);
- String fileExtensions = propertiesProvider.getProperty(INCLUDE_EXT_PROP);
-
- LOG.debug("Using storage: {}", storage);
-
- if (fileExtensions != null) {
- LOG.debug("Using extensions: {}", fileExtensions);
- return new XmlDirectoryPersister(storage, splitExtensions(fileExtensions));
- } else {
- return new XmlDirectoryPersister(storage);
- }
- }
-
- private Set<String> splitExtensions(final String fileExtensions) {
- return Sets.newHashSet(Splitter.on(EXTENSIONS_SEPARATOR).trimResults().omitEmptyStrings()
- .split(fileExtensions));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.storage.directory.xml;
-
-import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import com.google.common.base.Optional;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.SortedSet;
-
-import org.junit.Test;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.test.PropertiesProviderTest;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.xml.sax.SAXException;
-
-public class DirectoryStorageAdapterTest {
- private static final Logger LOG = LoggerFactory.getLogger(DirectoryStorageAdapterTest.class);
- Persister tested;
-
- private Persister instantiatePersisterFromAdapter(final File file, final Optional<String> extensions) {
- PropertiesProviderTest pp = new PropertiesProviderTest();
- pp.addProperty(XmlDirectoryStorageAdapter.DIRECTORY_STORAGE_PROP, file.getPath());
- if (extensions.isPresent()) {
- pp.addProperty(XmlDirectoryStorageAdapter.INCLUDE_EXT_PROP, extensions.get());
- }
-
- XmlDirectoryStorageAdapter dsa = new XmlDirectoryStorageAdapter();
- return dsa.instantiate(pp);
- }
-
- private Persister instantiatePersisterFromAdapter(final File file) {
- return instantiatePersisterFromAdapter(file, Optional.<String>absent());
- }
-
- @Test
- public void testEmptyDirectory() throws Exception {
- File folder = new File("target/emptyFolder");
- folder.mkdir();
-
- tested = instantiatePersisterFromAdapter(folder);
- assertEquals(Collections.<ConfigSnapshotHolder>emptyList(), tested.loadLastConfigs());
-
- try {
- tested.persistConfig(new ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- throw new RuntimeException();
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- throw new RuntimeException();
- }
- });
- fail();
- } catch (final UnsupportedOperationException e) {
- // TODO: empty catch block
- }
- }
-
- private File getFolder(final String folderName) {
- File result = new File(("src/test/resources/" + folderName).replace("/", File.separator));
- assertTrue(result + " is not a directory", result.isDirectory());
- return result;
- }
-
- @Test
- public void testOneFile() throws Exception {
- File folder = getFolder("oneFile");
- tested = instantiatePersisterFromAdapter(folder, Optional.of("xml"));
-
- LOG.info("Testing : {}", tested);
- List<ConfigSnapshotHolder> results = tested.loadLastConfigs();
- assertEquals(1, results.size());
- ConfigSnapshotHolder result = results.get(0);
- assertResult(result, "<config>1</config>", "cap1&rev", "cap2", "capa a");
- }
-
- @Test
- public void testOneFileWrongExtension() throws Exception {
- File folder = getFolder("oneFile");
- tested = instantiatePersisterFromAdapter(folder, Optional.of("aa, bb"));
- LOG.info("Testing : {}", tested);
- }
-
- private void assertResult(final ConfigSnapshotHolder result,
- final String string,
- final String... caps) throws SAXException, IOException {
- assertXMLEqual(string, result.getConfigSnapshot());
- int index = 0;
- for (String capFromSnapshot : result.getCapabilities()) {
- assertEquals(capFromSnapshot, caps[index++]);
- }
- }
-
- @Test
- public void testTwoFilesAllExtensions() throws Exception {
- File folder = getFolder("twoFiles");
- tested = instantiatePersisterFromAdapter(folder);
- LOG.info("Testing : {}", tested);
- List<ConfigSnapshotHolder> results = tested.loadLastConfigs();
- assertEquals(2, results.size());
-
- assertResult(results.get(0), "<config>1</config>", "cap1-a", "cap2-a", "capa a-a");
- assertResult(results.get(1), "<config>2</config>", "cap1-b", "cap2-b", "capa a-b");
- }
-
- @Test
- public void testTwoFilesTwoExtensions() throws Exception {
- File folder = getFolder("twoFiles");
- tested = instantiatePersisterFromAdapter(folder, Optional.of("xml, xml2"));
- LOG.info("Testing : {}", tested);
- assertEquals(2, tested.loadLastConfigs().size());
- }
-
- @Test
- public void testTwoFilesOnlyOneExtension() throws Exception {
- File folder = getFolder("twoFiles");
- tested = instantiatePersisterFromAdapter(folder, Optional.of("xml"));
- LOG.info("Testing : ", tested);
- List<ConfigSnapshotHolder> results = tested.loadLastConfigs();
- assertEquals(1, results.size());
-
- assertResult(results.get(0), "<config>1</config>", "cap1-a", "cap2-a", "capa a-a");
- }
-
- @Test
- public void testTwoFilesOneInvalid() throws Exception {
- File folder = getFolder("twoFiles_corrupt");
- tested = instantiatePersisterFromAdapter(folder, Optional.of("xml"));
- LOG.info("Testing : {}", tested);
- List<ConfigSnapshotHolder> results = tested.loadLastConfigs();
- assertEquals(1, results.size());
-
- assertResult(results.get(0), "<config>1</config>", "cap1-a", "cap2-a", "capa a-a");
- }
-
-}
+++ /dev/null
-<snapshot>
- <required-capabilities>
- <capability>cap1&rev</capability>
- <capability>cap2</capability>
- <capability>capa a</capability>
- </required-capabilities>
- <configuration>
- <config>1</config>
- </configuration>
-</snapshot>
\ No newline at end of file
+++ /dev/null
-<snapshot>
- <required-capabilities>
- <capability>cap1-a</capability>
- <capability>cap2-a</capability>
- <capability>capa a-a</capability>
- </required-capabilities>
- <configuration>
- <config>1</config>
- </configuration>
-</snapshot>
\ No newline at end of file
+++ /dev/null
-<snapshot>
- <required-capabilities>
- <capability>cap1-b</capability>
- <capability>cap2-b</capability>
- <capability>capa a-b</capability>
- </required-capabilities>
- <configuration>
- <config>2</config>
- </configuration>
-</snapshot>
\ No newline at end of file
+++ /dev/null
-<snapshot>
- <required-capabilities>
- <capability>cap1-a</capability>
- <capability>cap2-a</capability>
- <capability>capa a-a</capability>
- </required-capabilities>
- <configuration>
- <config>1</config>
- </configuration>
-</snapshot>
\ No newline at end of file
+++ /dev/null
-<snapshotInvalid>
- <required-capabilities>
- <capability>cap1-b</capability>
- <capability>cap2-b</capability>
- <capability>capa a-b</capability>
- </required-capabilities>
- <configuration>
- <config>2</config>
- </configuration>
-</snapshotInvalid>
\ No newline at end of file
+++ /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>config-subsystem</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
-
- <artifactId>config-persister-feature-adapter</artifactId>
- <packaging>bundle</packaging>
-
- <dependencies>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.karaf.features</groupId>
- <artifactId>org.apache.karaf.features.core</artifactId>
- <version>${karaf.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-directory-xml-adapter</artifactId>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <configuration>
- <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
- <Bundle-Version>${project.version}</Bundle-Version>
- <Bundle-Activator>org.opendaylight.controller.configpusherfeature.ConfigPusherFeatureActivator</Bundle-Activator>
- <Private-Package>
- org.apache.felix.utils.version,
- org.opendaylight.controller.configpusherfeature.internal
- </Private-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-</project>
+++ /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.configpusherfeature;
-
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.opendaylight.controller.configpusherfeature.internal.ConfigPusherCustomizer;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.osgi.util.tracker.ServiceTracker;
-
-public class ConfigPusherFeatureActivator implements BundleActivator {
- private BundleContext bc = null;
- private ConfigPusherCustomizer cpc = null;
- private ServiceTracker<ConfigPusher, ConfigPusher> cpst = null;
-
- public void start(final BundleContext context) throws Exception {
- bc = context;
- cpc = new ConfigPusherCustomizer();
- cpst = new ServiceTracker<>(bc, ConfigPusher.class.getName(), cpc);
- cpst.open();
- }
-
- public void stop(final BundleContext context) throws Exception {
- if (cpst != null) {
- cpst.close();
- cpst = null;
- }
- if (cpc != null) {
- cpc.close();
- cpc = null;
- }
- bc = 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.configpusherfeature.internal;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.io.Files;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-
-import javax.xml.bind.JAXBException;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.stream.XMLStreamException;
-
-import org.apache.karaf.features.BundleInfo;
-import org.apache.karaf.features.Capability;
-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.apache.karaf.features.Library;
-import org.apache.karaf.features.Requirement;
-import org.apache.karaf.features.Scoping;
-import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Element;
-import org.xml.sax.SAXException;
-
-/*
- * Wrap a Feature for the purposes of extracting the FeatureConfigSnapshotHolders from
- * its underlying ConfigFileInfo's
- *
- * Delegates the the contained feature and provides additional methods.
- */
-public class AbstractFeatureWrapper implements Feature {
- private static final Logger LOG = LoggerFactory.getLogger(AbstractFeatureWrapper.class);
-
- protected static final String CONFIG_FILE_SUFFIX = "xml";
-
- protected Feature feature = null;
-
- protected AbstractFeatureWrapper() {
- // prevent instantiation without Feature
- }
-
- /*
- * @param f Feature to wrap
- */
- public AbstractFeatureWrapper(final Feature feature) {
- Preconditions.checkNotNull(feature, "FeatureWrapper requires non-null Feature in constructor");
- this.feature = feature;
- }
-
- /*
- * Get FeatureConfigSnapshotHolders appropriate to feed to the config subsystem
- * from the underlying Feature Config files
- */
- public Set<FeatureConfigSnapshotHolder> getFeatureConfigSnapshotHolders() throws Exception {
- final Set<FeatureConfigSnapshotHolder> snapShotHolders = new LinkedHashSet<>();
- for (final ConfigFileInfo c : getConfigurationFiles()) {
- // Skip non config snapshot XML files
- if (isConfigSnapshot(c.getFinalname())) {
- final Optional<FeatureConfigSnapshotHolder> featureConfigSnapshotHolder =
- getFeatureConfigSnapshotHolder(c);
- if (featureConfigSnapshotHolder.isPresent()) {
- snapShotHolders.add(featureConfigSnapshotHolder.get());
- }
- }
- }
- return snapShotHolders;
- }
-
- protected Optional<FeatureConfigSnapshotHolder>
- getFeatureConfigSnapshotHolder(final ConfigFileInfo configFileInfo) {
- try {
- return Optional.of(new FeatureConfigSnapshotHolder(configFileInfo, this));
- } catch (final JAXBException e) {
- LOG.warn("Unable to parse configuration snapshot. Config from '{}' will be IGNORED. "
- + "Note that subsequent config files may fail due to this problem. "
- + "Xml markup in this file needs to be fixed, for detailed information see enclosed exception.",
- configFileInfo.getFinalname(), e);
- } catch (final XMLStreamException e) {
- // Files that cannot be loaded are ignored as non config subsystem files e.g. jetty.xml
- LOG.debug("Unable to read configuration file '{}'. Not a configuration snapshot",
- configFileInfo.getFinalname(), e);
- }
- return Optional.absent();
- }
-
- private static boolean isConfigSnapshot(final String fileName) {
- if (!Files.getFileExtension(fileName).equals(CONFIG_FILE_SUFFIX)) {
- return false;
- }
-
- if (fileName.endsWith("jetty.xml")) {
- // Special case - ignore the jetty.xml file as it contains a DTD and causes a "Connection refused"
- // error when it tries to go out to the network to retrieve it. We don't want it trying to go out
- // to the network nor do we want an error logged trying to parse it.
- return false;
- }
-
- File file = new File(System.getProperty("karaf.home"), fileName);
- try (FileInputStream fis = new FileInputStream(file)) {
- DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
- builderFactory.setNamespaceAware(true);
- builderFactory.setCoalescing(true);
- builderFactory.setIgnoringElementContentWhitespace(true);
- builderFactory.setIgnoringComments(true);
-
- Element root = builderFactory.newDocumentBuilder().parse(fis).getDocumentElement();
- return ConfigSnapshot.SNAPSHOT_ROOT_ELEMENT_NAME.equals(root.getLocalName());
- } catch (final ParserConfigurationException | IOException | SAXException e) {
- LOG.error("Could not parse XML file {}", file, e);
- return false;
- }
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (feature == null ? 0 : feature.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- final AbstractFeatureWrapper other = (AbstractFeatureWrapper) obj;
- if (feature == null) {
- if (other.feature != null) {
- return false;
- }
- } else if (!feature.equals(other.feature)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- return feature.getName();
- }
-
- @Override
- public String getId() {
- return feature.getId();
- }
-
- @Override
- public String getName() {
- return feature.getName();
- }
-
- @Override
- public String getDescription() {
- return feature.getDescription();
- }
-
- @Override
- public String getDetails() {
- return feature.getDetails();
- }
-
- @Override
- public String getVersion() {
- return feature.getVersion();
- }
-
- @Override
- public boolean hasVersion() {
- return feature.hasVersion();
- }
-
- @Override
- public String getResolver() {
- return feature.getResolver();
- }
-
- @Override
- public String getInstall() {
- return feature.getInstall();
- }
-
- @Override
- public List<Dependency> getDependencies() {
- return feature.getDependencies();
- }
-
- @Override
- public List<BundleInfo> getBundles() {
- return feature.getBundles();
- }
-
- @Override
- public List<ConfigInfo> getConfigurations() {
- return feature.getConfigurations();
- }
-
- @Override
- public List<ConfigFileInfo> getConfigurationFiles() {
- return feature.getConfigurationFiles();
- }
-
- @Override
- public List<? extends Conditional> getConditional() {
- return feature.getConditional();
- }
-
- @Override
- public int getStartLevel() {
- return feature.getStartLevel();
- }
-
- @Override
- public List<? extends Capability> getCapabilities() {
- return feature.getCapabilities();
- }
-
- @Override
- public List<? extends Library> getLibraries() {
- return feature.getLibraries();
- }
-
- @Override
- public String getNamespace() {
- return feature.getNamespace();
- }
-
- @Override
- public String getRepositoryUrl() {
- return feature.getRepositoryUrl();
- }
-
- @Override
- public List<? extends Requirement> getRequirements() {
- return feature.getRequirements();
- }
-
- @Override
- public List<String> getResourceRepositories() {
- return feature.getResourceRepositories();
- }
-
- @Override
- public Scoping getScoping() {
- return feature.getScoping();
- }
-
- @Override
- public boolean isHidden() {
- return feature.isHidden();
- }
-
-}
+++ /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.configpusherfeature.internal;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import org.apache.felix.utils.version.VersionRange;
-import org.apache.felix.utils.version.VersionTable;
-import org.apache.karaf.features.Dependency;
-import org.apache.karaf.features.Feature;
-import org.apache.karaf.features.FeaturesService;
-import org.osgi.framework.Version;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/*
- * Wrap a Feature for the purposes of extracting the FeatureConfigSnapshotHolders from
- * its underlying ConfigFileInfo's and those of its children recursively
- *
- * Delegates the the contained feature and provides additional methods.
- */
-public class ChildAwareFeatureWrapper extends AbstractFeatureWrapper implements Feature {
- private static final Logger LOG = LoggerFactory.getLogger(ChildAwareFeatureWrapper.class);
- private FeaturesService featuresService = null;
-
- protected ChildAwareFeatureWrapper(final Feature feature) {
- // Don't use without a feature service
- }
-
- /* Constructor.
-
- * @param feature Feature to wrap
- * @param featuresService FeaturesService to look up dependencies
- */
- ChildAwareFeatureWrapper(final Feature feature, final FeaturesService featuresService) throws Exception {
- super(featuresService.getFeature(feature.getName(), feature.getVersion()));
- Preconditions.checkNotNull(featuresService, "FeatureWrapper requires non-null FeatureService in constructor");
- this.featuresService = featuresService;
- }
-
- protected FeaturesService getFeaturesService() {
- return featuresService;
- }
-
- /*
- * Get FeatureConfigSnapshotHolders appropriate to feed to the config subsystem
- * from the underlying Feature Config files and those of its children recursively
- */
- public Set<? extends ChildAwareFeatureWrapper> getChildFeatures() throws Exception {
- List<Dependency> dependencies = feature.getDependencies();
- Set<ChildAwareFeatureWrapper> childFeatures = new LinkedHashSet<>();
- if (dependencies != null) {
- for (Dependency dependency : dependencies) {
- Feature fi = extractFeatureFromDependency(dependency);
- if (fi != null) {
- if (featuresService.getFeature(fi.getName(), fi.getVersion()) == null) {
- LOG.warn("Feature: {}, {} is missing from features service. Skipping", fi.getName(), fi
- .getVersion());
- } else {
- ChildAwareFeatureWrapper wrappedFeature = new ChildAwareFeatureWrapper(fi, featuresService);
- childFeatures.add(wrappedFeature);
- }
- }
- }
- }
- return childFeatures;
- }
-
- @Override
- public Set<FeatureConfigSnapshotHolder> getFeatureConfigSnapshotHolders() throws Exception {
- Set<FeatureConfigSnapshotHolder> snapShotHolders = new LinkedHashSet<>();
- for (ChildAwareFeatureWrapper c : getChildFeatures()) {
- for (FeatureConfigSnapshotHolder h : c.getFeatureConfigSnapshotHolders()) {
- final Optional<FeatureConfigSnapshotHolder> featureConfigSnapshotHolder =
- getFeatureConfigSnapshotHolder(h.getFileInfo());
- if (featureConfigSnapshotHolder.isPresent()) {
- snapShotHolders.add(featureConfigSnapshotHolder.get());
- }
- }
- }
- snapShotHolders.addAll(super.getFeatureConfigSnapshotHolders());
- return snapShotHolders;
- }
-
- protected Feature extractFeatureFromDependency(final Dependency dependency) throws Exception {
- Feature[] features = featuresService.listFeatures();
- VersionRange range = dependency.hasVersion() ? new VersionRange(dependency.getVersion(), true, true)
- : VersionRange.ANY_VERSION;
- Feature fi = null;
- for (Feature f : features) {
- if (f.getName().equals(dependency.getName())) {
- Version version = VersionTable.getVersion(f.getVersion());
- if (range.contains(version) && (fi == null || VersionTable.getVersion(fi.getVersion())
- .compareTo(version) < 0)) {
- fi = f;
- break;
- }
- }
- }
- return fi;
- }
-}
+++ /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.configpusherfeature.internal;
-
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-
-import org.apache.karaf.features.FeatureEvent;
-import org.apache.karaf.features.FeaturesListener;
-import org.apache.karaf.features.FeaturesService;
-import org.apache.karaf.features.RepositoryEvent;
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConfigFeaturesListener implements FeaturesListener, AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigFeaturesListener.class);
- private static final int QUEUE_SIZE = 1000;
- private BlockingQueue<FeatureEvent> queue = new LinkedBlockingQueue<>(QUEUE_SIZE);
- Thread pushingThread = null;
-
- public ConfigFeaturesListener(final ConfigPusher configPusher, final FeaturesService featuresService) {
- pushingThread = new Thread(new ConfigPushingRunnable(configPusher, featuresService, queue),
- "ConfigFeatureListener - ConfigPusher");
- pushingThread.start();
- }
-
- @Override
- public void featureEvent(final FeatureEvent event) {
- queue.offer(event);
- }
-
- @Override
- public void repositoryEvent(final RepositoryEvent event) {
- LOG.debug("Repository: {} {}", event.getType(), event.getRepository());
- }
-
- @Override
- public void close() {
- if (pushingThread != null) {
- pushingThread.interrupt();
- pushingThread = 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.configpusherfeature.internal;
-
-import org.apache.karaf.features.FeaturesService;
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.util.tracker.ServiceTracker;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConfigPusherCustomizer implements ServiceTrackerCustomizer<ConfigPusher, ConfigPusher>, AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherCustomizer.class);
- private ConfigFeaturesListener configFeaturesListener = null;
- private FeatureServiceCustomizer featureServiceCustomizer = null;
- private ServiceTracker<FeaturesService, FeaturesService> fsst = null;
-
- @Override
- public ConfigPusher addingService(final ServiceReference<ConfigPusher> configPusherServiceReference) {
- LOG.trace("Got ConfigPusherCustomizer.addingService {}", configPusherServiceReference);
- BundleContext bc = configPusherServiceReference.getBundle().getBundleContext();
- ConfigPusher cpService = bc.getService(configPusherServiceReference);
- featureServiceCustomizer = new FeatureServiceCustomizer(cpService);
- fsst = new ServiceTracker<>(bc, FeaturesService.class.getName(), featureServiceCustomizer);
- fsst.open();
- return cpService;
- }
-
- @Override
- public void modifiedService(final ServiceReference<ConfigPusher> configPusherServiceReference,
- final ConfigPusher configPusher) {
- // we don't care if the properties change
- }
-
- @Override
- public void removedService(final ServiceReference<ConfigPusher> configPusherServiceReference,
- final ConfigPusher configPusher) {
- this.close();
- }
-
- @Override
- public void close() {
- if (fsst != null) {
- fsst.close();
- fsst = null;
- }
- if (configFeaturesListener != null) {
- configFeaturesListener.close();
- configFeaturesListener = null;
- }
- if (featureServiceCustomizer != null) {
- featureServiceCustomizer.close();
- featureServiceCustomizer = null;
- }
- }
-}
\ No newline at end of file
+++ /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.configpusherfeature.internal;
-
-import com.google.common.collect.LinkedHashMultimap;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.karaf.features.Feature;
-import org.apache.karaf.features.FeatureEvent;
-import org.apache.karaf.features.FeatureEvent.EventType;
-import org.apache.karaf.features.FeaturesService;
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConfigPushingRunnable implements Runnable {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigPushingRunnable.class);
- private static final int POLL_TIME = 1;
- private BlockingQueue<FeatureEvent> queue;
- private FeatureConfigPusher configPusher;
-
- public ConfigPushingRunnable(final ConfigPusher configPusher, final FeaturesService featuresService,
- final BlockingQueue<FeatureEvent> featureEvents) {
- queue = featureEvents;
- this.configPusher = new FeatureConfigPusher(configPusher, featuresService);
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- public void run() {
- List<Feature> toInstall = new ArrayList<>();
- FeatureEvent event = null;
- boolean interrupted = false;
- while (true) {
- try {
- if (!interrupted) {
- if (toInstall.isEmpty()) {
- event = queue.take();
- } else {
- event = queue.poll(POLL_TIME, TimeUnit.MILLISECONDS);
- }
- if (event != null && event.getFeature() != null) {
- processFeatureEvent(event, toInstall);
- }
- } else if (toInstall.isEmpty()) {
- LOG.error("ConfigPushingRunnable - exiting");
- return;
- }
- } catch (final InterruptedException e) {
- LOG.error("ConfigPushingRunnable - interrupted");
- interrupted = true;
- } catch (final Exception e) {
- LOG.error("Exception while processing features {} event {}", toInstall, event, e);
- }
- }
- }
-
- protected void processFeatureEvent(final FeatureEvent event, final List<Feature> toInstall) throws Exception {
- if (event.getType() == EventType.FeatureInstalled) {
- toInstall.add(event.getFeature());
- LinkedHashMultimap<Feature, FeatureConfigSnapshotHolder> result = configPusher.pushConfigs(toInstall);
- toInstall.removeAll(result.keySet());
- } else if (event.getType() == EventType.FeatureUninstalled) {
- toInstall.remove(event.getFeature());
- }
- }
-
- protected void logPushResult(final LinkedHashMultimap<Feature, FeatureConfigSnapshotHolder> results) {
- for (Feature f : results.keySet()) {
- LOG.info("Pushed configs for feature {} {}", f, results.get(f));
- }
- }
-}
+++ /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.configpusherfeature.internal;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.LinkedHashMultimap;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import org.apache.karaf.features.Feature;
-import org.apache.karaf.features.FeaturesService;
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/*
- * Simple class to push configs to the config subsystem from Feature's configfiles
- */
-public class FeatureConfigPusher {
- private static final Logger LOG = LoggerFactory.getLogger(FeatureConfigPusher.class);
- private static final int MAX_RETRIES = 100;
- private static final int RETRY_PAUSE_MILLIS = 1;
-
- private FeaturesService featuresService = null;
- private ConfigPusher pusher = null;
-
- /*
- * A LinkedHashSet (to preserve order and insure uniqueness) of the pushedConfigs
- * This is used to prevent pushing duplicate configs if a Feature is in multiple dependency
- * chains. Also, preserves the *original* Feature chain for which we pushed the config.
- * (which is handy for logging).
- */
- private final Set<FeatureConfigSnapshotHolder> pushedConfigs = new LinkedHashSet<>();
-
- /*
- * LinkedHashMultimap to track which configs we pushed for each Feature installation
- * For future use
- */
- private final LinkedHashMultimap<Feature, FeatureConfigSnapshotHolder> feature2configs = LinkedHashMultimap
- .create();
-
- public FeatureConfigPusher(final ConfigPusher configPusher, final FeaturesService featuresService) {
- pusher = configPusher;
- this.featuresService = featuresService;
- }
-
- /*
- * Push config files from Features to config subsystem
- * @param features - list of Features to extract config files from recursively and push
- * to the config subsystem
- *
- * @return A LinkedHashMultimap of Features to the FeatureConfigSnapshotHolder actually pushed
- * If a Feature is not in the returned LinkedHashMultimap then we couldn't push its configs
- * (Ususally because it was not yet installed)
- */
- public LinkedHashMultimap<Feature, FeatureConfigSnapshotHolder> pushConfigs(
- final List<Feature> features) throws Exception {
- LinkedHashMultimap<Feature, FeatureConfigSnapshotHolder> pushedFeatures = LinkedHashMultimap.create();
- for (Feature feature : features) {
- Set<FeatureConfigSnapshotHolder> configSnapShots = pushConfig(feature);
- if (!configSnapShots.isEmpty()) {
- pushedFeatures.putAll(feature, configSnapShots);
- }
- }
- return pushedFeatures;
- }
-
- private Set<FeatureConfigSnapshotHolder> pushConfig(final Feature feature) throws Exception {
- // Ignore feature conditions — these encode conditions on other features and shouldn't be processed here
- if (feature.getName().contains("-condition-")) {
- LOG.debug("Ignoring conditional feature {}", feature);
- return Collections.emptySet();
- }
- // pax-exam's Karaf container generates a wrapper feature holding the test dependencies. Ignore it.
- if ("test-dependencies".equals(feature.getName())) {
- LOG.debug("Ignoring pax-exam wrapper feature {}", feature);
- return Collections.emptySet();
- }
-
- if (!isInstalled(feature)) {
- return Collections.emptySet();
- }
- // FIXME Workaround for BUG-2836, features service returns null for feature:
- // standard-condition-webconsole_0_0_0, 3.0.1
- if (featuresService.getFeature(feature.getName(), feature.getVersion()) == null) {
- LOG.debug("Feature: {}, {} is missing from features service. Skipping", feature.getName(), feature
- .getVersion());
- return Collections.emptySet();
- }
-
- ChildAwareFeatureWrapper wrappedFeature = new ChildAwareFeatureWrapper(feature, featuresService);
- Set<FeatureConfigSnapshotHolder> configs = wrappedFeature.getFeatureConfigSnapshotHolders();
- if (!configs.isEmpty()) {
- configs = pushConfig(configs, feature);
- feature2configs.putAll(feature, configs);
- }
- return configs;
- }
-
- private Set<FeatureConfigSnapshotHolder> pushConfig(final Set<FeatureConfigSnapshotHolder> configs,
- final Feature feature) throws InterruptedException {
- Set<FeatureConfigSnapshotHolder> configsToPush = new LinkedHashSet<>(configs);
- configsToPush.removeAll(pushedConfigs);
- if (!configsToPush.isEmpty()) {
-
- // Ignore features that are present in persisted current config
- final Optional<XmlFileStorageAdapter> currentCfgPusher = XmlFileStorageAdapter.getInstance();
- if (currentCfgPusher.isPresent() && currentCfgPusher.get().getPersistedFeatures()
- .contains(feature.getId())) {
- LOG.warn("Ignoring default configuration {} for feature {}, the configuration is present in {}",
- configsToPush, feature.getId(), currentCfgPusher.get());
- } else {
- pusher.pushConfigs(new ArrayList<>(configsToPush));
- }
- pushedConfigs.addAll(configsToPush);
- }
- Set<FeatureConfigSnapshotHolder> configsPushed = new LinkedHashSet<>(pushedConfigs);
- configsPushed.retainAll(configs);
- return configsPushed;
- }
-
- @SuppressWarnings("IllegalCatch")
- private boolean isInstalled(final Feature feature) throws InterruptedException {
- for (int retries = 0; retries < MAX_RETRIES; retries++) {
- try {
- // We process the installed features manually to handle the special "0.0.0" version
- // which is the representation for null
- for (Feature installedFeature : featuresService.listInstalledFeatures()) {
- if (feature.equals(installedFeature)) {
- return true;
- }
- if ("0.0.0".equals(feature.getVersion()) && feature.getName().equals(installedFeature.getName())
- && !installedFeature.hasVersion()) {
- return true;
- }
- }
-
- LOG.debug("Karaf Feature Service has not yet finished installing feature {}/{} (retry {})", feature
- .getName(), feature.getVersion(), retries);
- } catch (final Exception e) {
- LOG.warn("Karaf featuresService.listInstalledFeatures() has thrown an exception, retry {}", retries, e);
- }
-
- TimeUnit.MILLISECONDS.sleep(RETRY_PAUSE_MILLIS);
- }
-
- LOG.error("Giving up (after {} retries) on Karaf featuresService.listInstalledFeatures() which has not yet "
- + "finished installing feature {} {}", MAX_RETRIES, feature.getName(), feature.getVersion());
- 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.configpusherfeature.internal;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-import java.io.File;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.SortedSet;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.transform.stream.StreamSource;
-
-import org.apache.karaf.features.ConfigFileInfo;
-import org.apache.karaf.features.Feature;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot;
-
-/*
- * A ConfigSnapshotHolder that can track all the additional information
- * relavent to the fact we are getting these from a Feature.
- *
- * Includes tracking the 'featureChain' - an reverse ordered list of the dependency
- * graph of features that caused us to push this FeatureConfigSnapshotHolder.
- * So if A -> B -> C, then the feature chain would be C -> B -> A
- */
-public class FeatureConfigSnapshotHolder implements ConfigSnapshotHolder {
- private ConfigSnapshot unmarshalled = null;
- private ConfigFileInfo fileInfo = null;
- private List<Feature> featureChain = new ArrayList<>();
-
- /*
- * @param holder - FeatureConfigSnapshotHolder that we
- * @param feature - new
- */
- public FeatureConfigSnapshotHolder(final FeatureConfigSnapshotHolder holder,
- final Feature feature) throws JAXBException, XMLStreamException {
- this(holder.fileInfo, holder.getFeature());
- this.featureChain.add(feature);
- }
-
- /*
- * Create a FeatureConfigSnapshotHolder for a given ConfigFileInfo and record the associated
- * feature we are creating it from.
- * @param fileInfo - ConfigFileInfo to read into the ConfigSnapshot
- * @param feature - Feature the ConfigFileInfo was attached to
- */
- public FeatureConfigSnapshotHolder(final ConfigFileInfo fileInfo,
- final Feature feature) throws JAXBException, XMLStreamException {
- Preconditions.checkNotNull(fileInfo);
- Preconditions.checkNotNull(fileInfo.getFinalname());
- Preconditions.checkNotNull(feature);
- this.fileInfo = fileInfo;
- this.featureChain.add(feature);
- // TODO extract utility method for umarshalling config snapshots
- JAXBContext jaxbContext = JAXBContext.newInstance(ConfigSnapshot.class);
- Unmarshaller um = jaxbContext.createUnmarshaller();
- XMLInputFactory xif = XMLInputFactory.newFactory();
- xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
- xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
-
- XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(new File(fileInfo.getFinalname())));
- unmarshalled = (ConfigSnapshot) um.unmarshal(xsr);
- }
-
- /*
- * (non-Javadoc)
- * @see java.lang.Object#hashCode()
- *
- * We really care most about the underlying ConfigShapshot, so compute hashcode on that
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((unmarshalled != null && unmarshalled.getConfigSnapshot() == null) ? 0 :
- unmarshalled.getConfigSnapshot().hashCode());
- return result;
- }
-
- /*
- * (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- * *
- * We really care most about the underlying ConfigShapshot, so compute equality on that
- */
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- FeatureConfigSnapshotHolder fcsh = (FeatureConfigSnapshotHolder) obj;
- if (this.unmarshalled.getConfigSnapshot().equals(fcsh.unmarshalled.getConfigSnapshot())) {
- return true;
- }
- return false;
- }
-
- @Override
- public String toString() {
- StringBuilder stringBuilder = new StringBuilder();
- Path path = Paths.get(fileInfo.getFinalname());
- stringBuilder.append(path.getFileName()).append("(").append(getCauseFeature()).append(",").append(getFeature())
- .append(")");
- return stringBuilder.toString();
- }
-
- @Override
- public String getConfigSnapshot() {
- return unmarshalled.getConfigSnapshot();
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return unmarshalled.getCapabilities();
- }
-
- public ConfigFileInfo getFileInfo() {
- return fileInfo;
- }
-
- /*
- * @returns The original feature to which the ConfigFileInfo was attached
- * Example:
- * A -> B -> C, ConfigFileInfo Foo is attached to C.
- * feature:install A
- * thus C is the 'Feature' Foo was attached.
- */
- public Feature getFeature() {
- return featureChain.get(0);
- }
-
- /*
- * @return The dependency chain of the features that caused the ConfigFileInfo to be pushed in reverse order.
- * Example:
- * A -> B -> C, ConfigFileInfo Foo is attached to C.
- * The returned list is
- * [C,B,A]
- */
- public ImmutableList<Feature> getFeatureChain() {
- return ImmutableList.copyOf(Lists.reverse(featureChain));
- }
-
- /*
- * @return The feature the installation of which was the root cause
- * of this pushing of the ConfigFileInfo.
- * Example:
- * A -> B -> C, ConfigFileInfo Foo is attached to C.
- * feature:install A
- * this A is the 'Cause' of the installation of Foo.
- */
- public Feature getCauseFeature() {
- return Iterables.getLast(featureChain);
- }
-}
+++ /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.configpusherfeature.internal;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Sets;
-
-import java.util.Set;
-
-import org.apache.karaf.features.Feature;
-import org.apache.karaf.features.FeaturesListener;
-import org.apache.karaf.features.FeaturesService;
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class FeatureServiceCustomizer implements ServiceTrackerCustomizer<FeaturesService, FeaturesService>,
- AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(FeatureServiceCustomizer.class);
- private ConfigPusher configPusher = null;
- private ServiceRegistration<?> registration;
-
- FeatureServiceCustomizer(final ConfigPusher configPusher) {
- this.configPusher = configPusher;
- }
-
- @Override
- @SuppressWarnings("IllegalCatch")
- public FeaturesService addingService(final ServiceReference<FeaturesService> reference) {
- BundleContext bc = reference.getBundle().getBundleContext();
- final FeaturesService featureService = bc.getService(reference);
- final Optional<XmlFileStorageAdapter> currentPersister = XmlFileStorageAdapter.getInstance();
-
- if (XmlFileStorageAdapter.getInstance().isPresent()) {
- final Set<String> installedFeatureIds = Sets.newHashSet();
- try {
- for (final Feature installedFeature : featureService.listInstalledFeatures()) {
- installedFeatureIds.add(installedFeature.getId());
- }
- } catch (final Exception e) {
- LOG.error("Error listing installed features", e);
- }
-
- currentPersister.get().setFeaturesService(() -> installedFeatureIds);
- }
- ConfigFeaturesListener configFeaturesListener = new ConfigFeaturesListener(configPusher, featureService);
- registration = bc.registerService(FeaturesListener.class.getCanonicalName(), configFeaturesListener, null);
- return featureService;
- }
-
- @Override
- public void modifiedService(final ServiceReference<FeaturesService> reference, final FeaturesService service) {
- // we don't care if the properties change
- }
-
- @Override
- public void removedService(final ServiceReference<FeaturesService> reference, final FeaturesService service) {
- close();
- }
-
- @Override
- public void close() {
- if (registration != null) {
- registration.unregister();
- registration = null;
- }
- }
-}
+++ /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>config-subsystem</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>config-persister-file-xml-adapter</artifactId>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
-
- <dependencies>
- <!-- compile dependencies -->
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-api</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.validation</groupId>
- <artifactId>validation-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.eclipse.persistence</groupId>
- <artifactId>org.eclipse.persistence.core</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.eclipse.persistence</groupId>
- <artifactId>org.eclipse.persistence.moxy</artifactId>
- </dependency>
-
- <!-- test dependencies -->
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>xmlunit</groupId>
- <artifactId>xmlunit</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-persister-api</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Fragment-Host>${project.groupId}.config-persister-impl</Fragment-Host>
- <Provide-Capability>org.opendaylight.controller.config.persister.storage.adapter</Provide-Capability>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.storage.file.xml;
-
-import java.util.Set;
-
-/**
- * Wrapper for services providing list of features to be stored along with the config snapshot
- */
-public interface FeatureListProvider {
-
- Set<String> listFeatures();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.storage.file.xml;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import java.io.File;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.SortedSet;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-import org.opendaylight.controller.config.persist.api.StorageAdapter;
-import org.opendaylight.controller.config.persist.storage.file.xml.model.Config;
-import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * StorageAdapter that stores configuration in an xml file.
- */
-public class XmlFileStorageAdapter implements StorageAdapter, Persister {
- private static final Logger LOG = LoggerFactory.getLogger(XmlFileStorageAdapter.class);
-
- public static final String FILE_STORAGE_PROP = "fileStorage";
- public static final String NUMBER_OF_BACKUPS = "numberOfBackups";
-
- private static Integer numberOfStoredBackups;
- private File storage;
-
- private static volatile XmlFileStorageAdapter instance;
- private volatile ConfigSnapshot lastCfgSnapshotCache;
- private volatile Optional<FeatureListProvider> featuresService = Optional.absent();
-
- @VisibleForTesting
- public void reset() {
- instance = null;
- lastCfgSnapshotCache = null;
- featuresService = null;
- }
-
- @Override
- public Persister instantiate(final PropertiesProvider propertiesProvider) {
- if(instance != null) {
- return instance;
- }
-
- File localStorage = extractStorageFileFromProperties(propertiesProvider);
- LOG.debug("Using file {}", localStorage.getAbsolutePath());
- // Create file if it does not exist
- File parentFile = localStorage.getAbsoluteFile().getParentFile();
- if (!parentFile.exists()) {
- LOG.debug("Creating parent folders {}", parentFile);
- parentFile.mkdirs();
- }
- if (!localStorage.exists()) {
- LOG.debug("Storage file does not exist, creating empty file");
- try {
- boolean result = localStorage.createNewFile();
- if (!result) {
- throw new RuntimeException("Unable to create storage file " + localStorage);
- }
- } catch (final IOException e) {
- throw new RuntimeException("Unable to create storage file " + localStorage, e);
- }
- }
- if (numberOfStoredBackups == 0) {
- throw new RuntimeException(NUMBER_OF_BACKUPS
- + " property should be either set to positive value, or ommited. Can not be set to 0.");
- }
- setFileStorage(localStorage);
-
- instance = this;
- return this;
- }
-
- public static Optional<XmlFileStorageAdapter> getInstance() {
- return Optional.fromNullable(instance);
- }
-
- public Set<String> getPersistedFeatures() {
- return lastCfgSnapshotCache == null ? Collections.<String>emptySet() : lastCfgSnapshotCache.getFeatures();
- }
-
- public void setFeaturesService(final FeatureListProvider featuresService) {
- this.featuresService = Optional.of(featuresService);
- }
-
- @VisibleForTesting
- public void setFileStorage(final File storage) {
- this.storage = storage;
- }
-
- @VisibleForTesting
- public void setNumberOfBackups(final Integer numberOfBackups) {
- numberOfStoredBackups = numberOfBackups;
- }
-
- private static File extractStorageFileFromProperties(final PropertiesProvider propertiesProvider) {
- String fileStorageProperty = propertiesProvider.getProperty(FILE_STORAGE_PROP);
- Preconditions.checkNotNull(fileStorageProperty, "Unable to find " + propertiesProvider.getFullKeyForReporting(FILE_STORAGE_PROP));
- File result = new File(fileStorageProperty);
- String numberOfBackupsAsString = propertiesProvider.getProperty(NUMBER_OF_BACKUPS);
- if (numberOfBackupsAsString != null) {
- numberOfStoredBackups = Integer.valueOf(numberOfBackupsAsString);
- } else {
- numberOfStoredBackups = Integer.MAX_VALUE;
- }
- LOG.trace("Property {} set to {}", NUMBER_OF_BACKUPS, numberOfStoredBackups);
- return result;
- }
-
- @Override
- public void persistConfig(final ConfigSnapshotHolder holder) throws IOException {
- Preconditions.checkNotNull(storage, "Storage file is null");
-
- Set<String> installedFeatureIds = Collections.emptySet();
- if(featuresService.isPresent()) {
- installedFeatureIds = featuresService.get().listFeatures();
- }
-
- Config cfg = Config.fromXml(storage);
- cfg.addConfigSnapshot(ConfigSnapshot.fromConfigSnapshot(holder, installedFeatureIds), numberOfStoredBackups);
- cfg.toXml(storage);
- }
-
- @Override
- public List<ConfigSnapshotHolder> loadLastConfigs() throws IOException {
- Preconditions.checkNotNull(storage, "Storage file is null");
-
- if (!storage.exists()) {
- return Collections.emptyList();
- }
-
- Optional<ConfigSnapshot> lastSnapshot = Config.fromXml(storage).getLastSnapshot();
-
- if (lastSnapshot.isPresent()) {
- lastCfgSnapshotCache = lastSnapshot.get();
- return Lists.newArrayList(toConfigSnapshot(lastCfgSnapshotCache));
- } else {
- return Collections.emptyList();
- }
- }
-
-
- public ConfigSnapshotHolder toConfigSnapshot(final ConfigSnapshot configSnapshot) {
- return new ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- return configSnapshot.getConfigSnapshot();
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return configSnapshot.getCapabilities();
- }
-
- @Override
- public String toString() {
- return configSnapshot.toString();
- }
- };
- }
-
- @Override
- public void close() {
-
- }
-
- @Override
- public String toString() {
- return "XmlFileStorageAdapter [storage=" + storage + "]";
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.storage.file.xml.model;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.io.Files;
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.util.List;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.transform.stream.StreamSource;
-import org.apache.commons.lang3.StringUtils;
-
-@XmlRootElement(name = "persisted-snapshots")
-public final class Config {
-
- private List<ConfigSnapshot> snapshots;
-
- Config(final List<ConfigSnapshot> snapshots) {
- this.snapshots = snapshots;
- }
-
- public Config() {
- this.snapshots = Lists.newArrayList();
- }
-
- @XmlElement(name = "snapshot")
- @XmlElementWrapper(name = "snapshots")
- public List<ConfigSnapshot> getSnapshots() {
- return snapshots;
- }
-
- public void setSnapshots(final List<ConfigSnapshot> snapshots) {
- this.snapshots = snapshots;
- }
-
- public void toXml(final File to) {
- try {
-
- // TODO Moxy has to be used instead of default jaxb impl due to a bug
- // default implementation has a bug that prevents from serializing xml in a string
- JAXBContext jaxbContext = org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(new Class[]{Config.class}, null);
-
- Marshaller marshaller = jaxbContext.createMarshaller();
-
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
-
- marshaller.marshal(this, to);
- } catch (final JAXBException e) {
- throw new PersistException("Unable to persist configuration", e);
- }
- }
-
- public static Config fromXml(final File from) {
- if(isEmpty(from)) {
- return new Config();
- }
-
- try {
- JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);
- Unmarshaller um = jaxbContext.createUnmarshaller();
- XMLInputFactory xif = XMLInputFactory.newFactory();
- xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
- xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
- XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(from));
- return (Config) um.unmarshal(xsr);
- } catch (JAXBException | XMLStreamException e) {
- throw new PersistException("Unable to restore configuration", e);
- }
- }
-
- private static boolean isEmpty(final File from) {
- return from.length() == 0 || isBlank(from);
- }
-
- private static boolean isBlank(final File from) {
- try {
- return StringUtils.isBlank(Files.toString(from, StandardCharsets.UTF_8));
- } catch (final IOException e) {
- throw new IllegalStateException("Unexpected error reading file" + from, e);
- }
- }
-
- public Optional<ConfigSnapshot> getLastSnapshot() {
- ConfigSnapshot last = Iterables.getLast(snapshots, null);
- return last == null ? Optional.<ConfigSnapshot>absent() : Optional.of(last);
- }
-
- public void addConfigSnapshot(final ConfigSnapshot snap, final int numberOfStoredBackups) {
- if (shouldReplaceLast(numberOfStoredBackups) && !snapshots.isEmpty()) {
- snapshots.remove(0);
- }
- snapshots.add(snap);
- }
-
- private boolean shouldReplaceLast(final int numberOfStoredBackups) {
- return numberOfStoredBackups == snapshots.size();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.storage.file.xml.model;
-
-import java.util.HashSet;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import javax.xml.bind.annotation.XmlAnyElement;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-
-@XmlRootElement(name = ConfigSnapshot.SNAPSHOT_ROOT_ELEMENT_NAME)
-public class ConfigSnapshot {
-
- public static final String SNAPSHOT_ROOT_ELEMENT_NAME = "snapshot";
-
- private String configXml;
- private SortedSet<String> capabilities = new TreeSet<>();
- private Set<String> features = new HashSet<>();
-
- ConfigSnapshot(final String configXml, final SortedSet<String> capabilities) {
- this.configXml = configXml;
- this.capabilities = capabilities;
- }
-
- ConfigSnapshot(final String configXml, final SortedSet<String> capabilities, final Set<String> features) {
- this.configXml = configXml;
- this.capabilities = capabilities;
- this.features = features;
- }
-
- ConfigSnapshot() {
- }
-
- public static ConfigSnapshot fromConfigSnapshot(final ConfigSnapshotHolder cfg) {
- return new ConfigSnapshot(cfg.getConfigSnapshot(), cfg.getCapabilities());
- }
-
- public static ConfigSnapshot fromConfigSnapshot(final ConfigSnapshotHolder cfg, final Set<String> features) {
- return new ConfigSnapshot(cfg.getConfigSnapshot(), cfg.getCapabilities(), features);
- }
-
- @XmlAnyElement(SnapshotHandler.class)
- public String getConfigSnapshot() {
- return configXml;
- }
-
- public void setConfigSnapshot(final String configSnapshot) {
- this.configXml = configSnapshot;
- }
-
- @XmlElement(name = "capability")
- @XmlElementWrapper(name = "required-capabilities")
- @XmlJavaTypeAdapter(value=StringTrimAdapter.class)
- public SortedSet<String> getCapabilities() {
- return capabilities;
- }
-
- public void setCapabilities(final SortedSet<String> capabilities) {
- this.capabilities = capabilities;
- }
-
- @XmlElement(name = "feature")
- @XmlElementWrapper(name = "features")
- @XmlJavaTypeAdapter(value=StringTrimAdapter.class)
- public Set<String> getFeatures() {
- return features;
- }
-
- public void setFeatures(final Set<String> features) {
- this.features = features;
- }
-
- @Override
- public String toString() {
- return "ConfigSnapshot{"
- + "configSnapshot='" + configXml + '\''
- + ", capabilities=" + capabilities
- + ", features=" + features +
- '}';
- }
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.storage.file.xml.model;
-
-final class PersistException extends RuntimeException {
- private static final long serialVersionUID = 1L;
-
- public PersistException(final String s, final Exception e) {
- super(s, e);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.storage.file.xml.model;
-
-import com.google.common.base.Preconditions;
-import java.io.StringReader;
-import java.io.StringWriter;
-import javax.xml.bind.ValidationEventHandler;
-import javax.xml.bind.annotation.DomHandler;
-import javax.xml.transform.Source;
-import javax.xml.transform.stream.StreamResult;
-import javax.xml.transform.stream.StreamSource;
-
-class SnapshotHandler implements DomHandler<String, StreamResult> {
-
- private static final String START_TAG = "<configuration>";
- private static final String END_TAG = "</configuration>";
-
- private StringWriter xmlWriter = new StringWriter();
-
- @Override
- public StreamResult createUnmarshaller(final ValidationEventHandler errorHandler) {
- xmlWriter.getBuffer().setLength(0);
- return new StreamResult(xmlWriter);
- }
-
- @Override
- public String getElement(final StreamResult rt) {
- String xml = rt.getWriter().toString();
- int beginIndex = xml.indexOf(START_TAG) + START_TAG.length();
- int endIndex = xml.indexOf(END_TAG);
- Preconditions.checkArgument(beginIndex != -1 && endIndex != -1,
- "Unknown element present in config snapshot(expected only configuration): %s", xml);
- return xml.substring(beginIndex, endIndex);
- }
-
- @Override
- public Source marshal(final String n, final ValidationEventHandler errorHandler) {
- try {
- String xml = START_TAG + n.trim() + END_TAG;
- StringReader xmlReader = new StringReader(xml);
- return new StreamSource(xmlReader);
- } catch(final Exception e) {
- throw new RuntimeException(e);
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.storage.file.xml.model;
-
-import javax.xml.bind.annotation.adapters.XmlAdapter;
-
-final class StringTrimAdapter extends XmlAdapter<String, String> {
- @Override
- public String unmarshal(final String v) throws Exception {
- if (v == null) {
- return null;
- }
- return v.trim();
- }
-
- @Override
- public String marshal(final String v) throws Exception {
- if (v == null) {
- return null;
- }
- return v.trim();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.storage.file.xml;
-
-import static junit.framework.Assert.assertTrue;
-import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import com.google.common.collect.Sets;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.charset.StandardCharsets;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.test.PropertiesProviderTest;
-
-public class FileStorageAdapterTest {
-
- private static int i;
- private File file;
- private static final String NON_EXISTENT_DIRECTORY = "./nonExistentDir/";
- private static final String NON_EXISTENT_FILE = "nonExistent.txt";
- private XmlFileStorageAdapter storage;
-
- @Before
- public void setUp() throws Exception {
- file = Files.createTempFile("testFilePersist", ".txt").toFile();
- file.deleteOnExit();
- if (!file.exists()) {
- return;
- }
- com.google.common.io.Files.write("", file, StandardCharsets.UTF_8);
- i = 1;
- storage = new XmlFileStorageAdapter();
- }
-
- @After
- public void tearDown() throws Exception {
- storage.reset();
- }
-
- @Test
- public void testNewFile() throws Exception {
- PropertiesProviderTest pp = new PropertiesProviderTest();
- pp.addProperty("fileStorage",NON_EXISTENT_DIRECTORY+NON_EXISTENT_FILE);
- pp.addProperty("numberOfBackups",Integer.toString(Integer.MAX_VALUE));
- storage.instantiate(pp);
-
- final ConfigSnapshotHolder holder = new ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- return createConfig();
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return createCaps();
- }
- };
- storage.persistConfig(holder);
-
- storage.persistConfig(holder);
-
- assertEquals(storage.toString().replace("\\","/"),"XmlFileStorageAdapter [storage="+NON_EXISTENT_DIRECTORY+NON_EXISTENT_FILE+"]");
- delete(new File(NON_EXISTENT_DIRECTORY));
- }
-
- @Test
- public void testFileAdapter() throws Exception {
- PropertiesProviderTest pp = new PropertiesProviderTest();
- pp.addProperty("fileStorage",file.getPath());
- pp.addProperty("numberOfBackups",Integer.toString(Integer.MAX_VALUE));
- storage.instantiate(pp);
-
- final ConfigSnapshotHolder holder = new ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- return createConfig();
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return createCaps();
- }
- };
- storage.persistConfig(holder);
-
- storage.persistConfig(holder);
-
- assertEquals(29, com.google.common.io.Files.readLines(file, StandardCharsets.UTF_8).size());
- List<ConfigSnapshotHolder> lastConf = storage.loadLastConfigs();
- assertEquals(1, lastConf.size());
- ConfigSnapshotHolder configSnapshotHolder = lastConf.get(0);
- assertXMLEqual("<config>2</config>", configSnapshotHolder.getConfigSnapshot());
- assertEquals(createCaps(), configSnapshotHolder.getCapabilities());
-
- storage = new XmlFileStorageAdapter();
- storage.setFileStorage(file);
- storage.setNumberOfBackups(Integer.MAX_VALUE);
-
- List<ConfigSnapshotHolder> last = storage.loadLastConfigs();
- assertEquals(createCaps(), last.get(0).getCapabilities());
- }
-
- private SortedSet<String> createCaps() {
- SortedSet<String> caps = new TreeSet<>();
-
- caps.add("cap1" + i);
- caps.add("cap2" + i);
- caps.add("urn:opendaylight:params:xml:ns:yang:controller:netty?module=netty&revision=2013-11-19" + i);
- caps.add("capaaaa as dasfasdf s2" + i);
- return caps;
- }
-
- @Test
- public void testFileAdapterOneBackup() throws Exception {
- PropertiesProviderTest pp = new PropertiesProviderTest();
- pp.addProperty("fileStorage",file.getPath());
- pp.addProperty("numberOfBackups",Integer.toString(Integer.MAX_VALUE));
- storage.instantiate(pp);
-
- final ConfigSnapshotHolder holder = new ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- return createConfig();
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return createCaps();
- }
- };
- storage.persistConfig(holder);
-
- storage.persistConfig(holder);
-
- assertEquals(29, com.google.common.io.Files.readLines(file, StandardCharsets.UTF_8).size());
-
- List<ConfigSnapshotHolder> lastConf = storage.loadLastConfigs();
- assertEquals(1, lastConf.size());
- ConfigSnapshotHolder configSnapshotHolder = lastConf.get(0);
- assertXMLEqual("<config>2</config>", configSnapshotHolder.getConfigSnapshot());
- }
-
- @Test
- public void testWithFeatures() throws Exception {
- PropertiesProviderTest pp = new PropertiesProviderTest();
- pp.addProperty("fileStorage",file.getPath());
- pp.addProperty("numberOfBackups",Integer.toString(Integer.MAX_VALUE));
- storage.instantiate(pp);
-
- final ConfigSnapshotHolder holder = new ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- return createConfig();
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return createCaps();
- }
- };
- final FeatureListProvider mock = mock(FeatureListProvider.class);
-
- doReturn(Sets.newHashSet("f1-11", "f2-22")).when(mock).listFeatures();
- storage.setFeaturesService(mock);
- storage.persistConfig(holder);
-
- assertEquals(20, com.google.common.io.Files.readLines(file, StandardCharsets.UTF_8).size());
-
- List<ConfigSnapshotHolder> lastConf = storage.loadLastConfigs();
- assertEquals(1, lastConf.size());
- ConfigSnapshotHolder configSnapshotHolder = lastConf.get(0);
- assertXMLEqual("<config>1</config>", configSnapshotHolder.getConfigSnapshot());
- assertEquals(Sets.newHashSet("f1-11", "f2-22"), storage.getPersistedFeatures());
- }
-
- @Test
- public void testNoFeaturesStored() throws Exception {
- PropertiesProviderTest pp = new PropertiesProviderTest();
- pp.addProperty("fileStorage",file.getPath());
- pp.addProperty("numberOfBackups",Integer.toString(Integer.MAX_VALUE));
- storage.instantiate(pp);
-
- com.google.common.io.Files.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
- "<persisted-snapshots>\n" +
- " <snapshots>\n" +
- " <snapshot>\n" +
- " <required-capabilities>\n" +
- " <capability>cap12</capability>\n" +
- " </required-capabilities>\n" +
- " <configuration>\n" +
- " <config>1</config>\n" +
- " </configuration>\n" +
- " </snapshot>\n" +
- " </snapshots>\n" +
- "</persisted-snapshots>", file, StandardCharsets.UTF_8);
-
- List<ConfigSnapshotHolder> lastConf = storage.loadLastConfigs();
- assertEquals(1, lastConf.size());
- ConfigSnapshotHolder configSnapshotHolder = lastConf.get(0);
- assertXMLEqual("<config>1</config>", configSnapshotHolder.getConfigSnapshot());
- assertTrue(storage.getPersistedFeatures().isEmpty());
- }
-
- @Test
- public void testFileAdapterOnlyTwoBackups() throws Exception {
- storage.setFileStorage(file);
- storage.setNumberOfBackups(2);
- final ConfigSnapshotHolder holder = new ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- return createConfig();
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return createCaps();
- }
- };
- storage.persistConfig(holder);
-
- storage.persistConfig(holder);
- storage.persistConfig(holder);
-
- List<String> readLines = com.google.common.io.Files.readLines(file, StandardCharsets.UTF_8);
- assertEquals(29, readLines.size());
-
- List<ConfigSnapshotHolder> lastConf = storage.loadLastConfigs();
- assertEquals(1, lastConf.size());
- ConfigSnapshotHolder configSnapshotHolder = lastConf.get(0);
- assertXMLEqual("<config>3</config>", configSnapshotHolder.getConfigSnapshot());
- assertFalse(readLines.contains(holder.getConfigSnapshot()));
- assertTrue(storage.getPersistedFeatures().isEmpty());
- }
-
- @Test
- public void testNoLastConfig() throws Exception {
- File file = Files.createTempFile("testFilePersist", ".txt").toFile();
- file.deleteOnExit();
- if (!file.exists()) {
- return;
- }
- try (XmlFileStorageAdapter storage = new XmlFileStorageAdapter()) {
- storage.setFileStorage(file);
-
- List<ConfigSnapshotHolder> elementOptional = storage.loadLastConfigs();
- assertThat(elementOptional.size(), is(0));
- }
- }
-
- @Test(expected = NullPointerException.class)
- public void testNoProperties() throws Exception {
- try (XmlFileStorageAdapter storage = new XmlFileStorageAdapter()) {
- storage.loadLastConfigs();
- }
- }
-
- @Test(expected = NullPointerException.class)
- public void testNoProperties2() throws Exception {
- try (XmlFileStorageAdapter storage = new XmlFileStorageAdapter()) {
- storage.persistConfig(new ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- return mock(String.class);
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return new TreeSet<>();
- }
- });
- }
- }
-
- static String createConfig() {
- return "<config>" + i++ + "</config>";
- }
-
- private void delete(final File f) throws IOException {
- if (f.isDirectory()) {
- for (File c : f.listFiles()) {
- delete(c);
- }
- }
- if (!f.delete()) {
- throw new FileNotFoundException("Failed to delete file: " + f);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.storage.file.xml.model;
-
-import java.io.File;
-import org.junit.Test;
-
-public class ConfigTest {
-
- @Test(expected = IllegalArgumentException.class)
- public void testFromXml() throws Exception {
- Config.fromXml(new File(getClass().getResource("/illegalSnapshot.xml").getFile()));
- }
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
- Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<snapshot>
- <configuration>
- <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
- <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
- <module>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:clustering-service-provider">
- prefix:clustering-service-provider
- </type>
- <name>clustering-service-provider</name>
-
- <rpc-registry>
- <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-rpc-registry</type>
- <name>binding-rpc-broker</name>
- </rpc-registry>
-
- </module>
- </modules>
- </data>
-
- </configuration>
-
- <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
- <service>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:clustering-service-provider">prefix:clustering-service-change-registry</type>
- <instance>
- <name>openflow-role-change-registry</name>
- <provider>/modules/module[type='clustering-service-provider'][name='clustering-service-provider']</provider>
- </instance>
- </service>
- </services>
-
- <required-capabilities>
- <capability>urn:opendaylight:params:xml:ns:yang:controller:config:clustering-service-provider?module=clustering-service-provider&revision=2014-11-19</capability>
-
- </required-capabilities>
-
-</snapshot>
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- ~
- ~ This program and the accompanying materials are made available under the
- ~ terms of the Eclipse Public License v1.0 which accompanies this distribution,
- ~ and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <artifactId>config-subsystem</artifactId>
- <groupId>org.opendaylight.controller</groupId>
- <version>0.9.0-SNAPSHOT</version>
- </parent>
- <artifactId>config-persister-impl</artifactId>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
-
- <dependencies>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <!-- compile dependencies -->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager-facade-xml</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-directory-xml-adapter</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-file-xml-adapter</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Bundle-Activator>org.opendaylight.controller.config.persist.impl.osgi.ConfigPersisterActivator</Bundle-Activator>
- <Require-Capability>org.opendaylight.controller.config.persister.storage.adapter</Require-Capability>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.impl;
-
-import com.google.common.annotations.VisibleForTesting;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-
-/**
- * Inspects snapshot xml to be stored, remove all capabilities that are not referenced by it.
- * Useful when persisting current configuration.
- */
-public class CapabilityStrippingConfigSnapshotHolder implements ConfigSnapshotHolder {
- private static final Logger LOG = LoggerFactory.getLogger(CapabilityStrippingConfigSnapshotHolder.class);
-
- private final String configSnapshot;
- private final StripCapabilitiesResult stripCapabilitiesResult;
-
- public CapabilityStrippingConfigSnapshotHolder(final Element snapshot, final Set<String> capabilities) {
- final XmlElement configElement = XmlElement.fromDomElement(snapshot);
- configSnapshot = XmlUtil.toString(configElement.getDomElement());
- stripCapabilitiesResult = stripCapabilities(configElement, capabilities);
- }
-
- private static class StripCapabilitiesResult {
- private final SortedSet<String> requiredCapabilities;
- private final SortedSet<String> obsoleteCapabilities;
-
- private StripCapabilitiesResult(final SortedSet<String> requiredCapabilities, final SortedSet<String> obsoleteCapabilities) {
- this.requiredCapabilities = Collections.unmodifiableSortedSet(requiredCapabilities);
- this.obsoleteCapabilities = Collections.unmodifiableSortedSet(obsoleteCapabilities);
- }
- }
-
-
- @VisibleForTesting
- static StripCapabilitiesResult stripCapabilities(final XmlElement configElement, final Set<String> allCapabilitiesFromHello) {
- // collect all namespaces
- Set<String> foundNamespacesInXML = getNamespaces(configElement);
- LOG.trace("All capabilities {}\nFound namespaces in XML {}", allCapabilitiesFromHello, foundNamespacesInXML);
- // required are referenced both in xml and hello
- SortedSet<String> requiredCapabilities = new TreeSet<>();
- // can be removed
- SortedSet<String> obsoleteCapabilities = new TreeSet<>();
- for (String capability : allCapabilitiesFromHello) {
- String namespace = capability.replaceAll("\\?.*","");
- if (foundNamespacesInXML.contains(namespace)) {
- requiredCapabilities.add(capability);
- } else {
- obsoleteCapabilities.add(capability);
- }
- }
-
- LOG.trace("Required capabilities {}, \nObsolete capabilities {}",
- requiredCapabilities, obsoleteCapabilities);
-
- return new StripCapabilitiesResult(requiredCapabilities, obsoleteCapabilities);
- }
-
- static Set<String> getNamespaces(final XmlElement element){
- Set<String> result = new HashSet<>();
- for (Entry<String,Attr> attribute : element.getAttributes().entrySet()) {
- if (attribute.getKey().startsWith("xmlns")){
- result.add(attribute.getValue().getValue());
- }
- }
- for(XmlElement child: element.getChildElements()) {
- result.addAll(getNamespaces(child));
- }
- return result;
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- return stripCapabilitiesResult.requiredCapabilities;
- }
-
- @VisibleForTesting
- Set<String> getObsoleteCapabilities(){
- return stripCapabilitiesResult.obsoleteCapabilities;
- }
-
- @Override
- public String getConfigSnapshot() {
- return configSnapshot;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.impl;
-
-import com.google.common.base.Optional;
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.Set;
-import javax.annotation.concurrent.ThreadSafe;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServerConnection;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.notifications.CommitJMXNotification;
-import org.opendaylight.controller.config.api.jmx.notifications.ConfigJMXNotification;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
-import org.opendaylight.controller.config.facade.xml.Datastore;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Element;
-
-/**
- * Responsible for listening for notifications from netconf (via JMX) containing latest
- * committed configuration that should be persisted, and also for loading last
- * configuration.
- */
-@ThreadSafe
-public class ConfigPersisterNotificationHandler implements Closeable {
-
- private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
- private final MBeanServerConnection mBeanServerConnection;
- private final NotificationListener listener;
-
-
- public ConfigPersisterNotificationHandler(final MBeanServerConnection mBeanServerConnection, final Persister persisterAggregator, final ConfigSubsystemFacadeFactory facade) {
- this(mBeanServerConnection, new ConfigPersisterNotificationListener(persisterAggregator, facade));
- }
-
- public ConfigPersisterNotificationHandler(final MBeanServerConnection mBeanServerConnection, final NotificationListener notificationListener) {
- this.mBeanServerConnection = mBeanServerConnection;
- this.listener = notificationListener;
- registerAsJMXListener(mBeanServerConnection, listener);
- }
-
- private static void registerAsJMXListener(final MBeanServerConnection mBeanServerConnection, final NotificationListener listener) {
- LOG.trace("Called registerAsJMXListener");
- try {
- mBeanServerConnection.addNotificationListener(ConfigJMXNotification.OBJECT_NAME, listener, null, null);
- } catch (InstanceNotFoundException | IOException e) {
- throw new IllegalStateException("Cannot register as JMX listener to netconf", e);
- }
- }
-
- @Override
- public synchronized void close() {
- // unregister from JMX
- final ObjectName on = ConfigJMXNotification.OBJECT_NAME;
- try {
- if (mBeanServerConnection.isRegistered(on)) {
- mBeanServerConnection.removeNotificationListener(on, listener);
- }
- } catch (final Exception e) {
- LOG.warn("Unable to unregister {} as listener for {}", listener, on, e);
- }
- }
-}
-
-class ConfigPersisterNotificationListener implements NotificationListener {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterNotificationListener.class);
-
- private final Persister persisterAggregator;
- private final ConfigSubsystemFacadeFactory facade;
-
- ConfigPersisterNotificationListener(final Persister persisterAggregator, final ConfigSubsystemFacadeFactory facade) {
- this.persisterAggregator = persisterAggregator;
- this.facade = facade;
- }
-
- @Override
- public void handleNotification(final Notification notification, final Object handback) {
- if (!(notification instanceof ConfigJMXNotification)) {
- return;
- }
-
- // Socket should not be closed at this point
- // Activator unregisters this as JMX listener before close is called
-
- LOG.trace("Received notification {}", notification);
- if (notification instanceof CommitJMXNotification) {
- try {
- handleAfterCommitNotification();
- } catch (final Exception e) {
- // log exceptions from notification Handler here since
- // notificationBroadcastSupport logs only DEBUG level
- LOG.warn("Failed to handle notification {}", notification, e);
- throw e;
- }
- } else {
- throw new IllegalStateException("Unknown config registry notification type " + notification);
- }
- }
-
- private void handleAfterCommitNotification() {
- try {
- final Set<Capability> currentCapabilities = facade.getCurrentCapabilities();
- final Element configSnapshot = facade.createFacade("config-persister").getConfiguration(XmlUtil.newDocument(), Datastore.running, Optional.<String>absent());
- persisterAggregator.persistConfig(new CapabilityStrippingConfigSnapshotHolder(configSnapshot,
- ConfigPusherImpl.transformCapabilities(currentCapabilities)));
- LOG.trace("Configuration persisted successfully");
- } catch (final IOException e) {
- throw new RuntimeException("Unable to persist configuration snapshot", e);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.impl;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import com.google.common.base.Stopwatch;
-import com.google.common.collect.Collections2;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import javax.annotation.concurrent.Immutable;
-import javax.management.MBeanServerConnection;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ModuleFactoryNotFoundException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.facade.xml.ConfigExecution;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Element;
-import org.xml.sax.SAXException;
-
-@Immutable
-public class ConfigPusherImpl implements ConfigPusher {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherImpl.class);
-
- private static final Date NO_REVISION = new Date(0);
- private static final int QUEUE_SIZE = 100;
-
- private final long maxWaitForCapabilitiesMillis;
- private final long conflictingVersionTimeoutMillis;
- private final BlockingQueue<List<? extends ConfigSnapshotHolder>> queue = new LinkedBlockingQueue<>(QUEUE_SIZE);
-
- private final ConfigSubsystemFacadeFactory facade;
- private ConfigPersisterNotificationHandler jmxNotificationHandler;
-
- public ConfigPusherImpl(final ConfigSubsystemFacadeFactory facade, final long maxWaitForCapabilitiesMillis,
- final long conflictingVersionTimeoutMillis) {
- this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
- this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
- this.facade = facade;
- }
-
- public void process(final List<AutoCloseable> autoCloseables, final MBeanServerConnection platformMBeanServer,
- final Persister persisterAggregator, final boolean propagateExceptions) throws InterruptedException {
- while(processSingle(autoCloseables, platformMBeanServer, persisterAggregator, propagateExceptions)) {
- }
- }
-
- boolean processSingle(final List<AutoCloseable> autoCloseables, final MBeanServerConnection platformMBeanServer,
- final Persister persisterAggregator, final boolean propagateExceptions) throws InterruptedException {
- final List<? extends ConfigSnapshotHolder> configs = queue.take();
- try {
- internalPushConfigs(configs);
-
- // Do not register multiple notification handlers
- if(jmxNotificationHandler == null) {
- jmxNotificationHandler =
- new ConfigPersisterNotificationHandler(platformMBeanServer, persisterAggregator, facade);
- synchronized (autoCloseables) {
- autoCloseables.add(jmxNotificationHandler);
- }
- }
-
- LOG.debug("ConfigPusher has pushed configs {}", configs);
- } catch (final Exception e) {
- // Exceptions are logged to error downstream
- LOG.debug("Failed to push some of configs: {}", configs, e);
-
- if(propagateExceptions) {
- if(e instanceof RuntimeException) {
- throw (RuntimeException)e;
- } else {
- throw new IllegalStateException(e);
- }
- } else {
- return false;
- }
- }
-
- return true;
- }
-
- @Override
- public void pushConfigs(final List<? extends ConfigSnapshotHolder> configs) throws InterruptedException {
- LOG.debug("Requested to push configs {}", configs);
- this.queue.put(configs);
- }
-
- private LinkedHashMap<? extends ConfigSnapshotHolder, Boolean> internalPushConfigs(final List<? extends ConfigSnapshotHolder> configs)
- throws DocumentedException {
- LOG.debug("Last config snapshots to be pushed to netconf: {}", configs);
- LinkedHashMap<ConfigSnapshotHolder, Boolean> result = new LinkedHashMap<>();
- // start pushing snapshots
- for (ConfigSnapshotHolder configSnapshotHolder : configs) {
- if (configSnapshotHolder != null) {
- LOG.info("Pushing configuration snapshot {}", configSnapshotHolder);
- boolean pushResult = false;
- try {
- pushResult = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
- } catch (final ConfigSnapshotFailureException e) {
- LOG.error("Failed to apply configuration snapshot: {}. Config snapshot is not semantically correct and will be IGNORED. " +
- "for detailed information see enclosed exception.", e.getConfigIdForReporting(), e);
- throw new IllegalStateException("Failed to apply configuration snapshot " + e.getConfigIdForReporting(), e);
- } catch (final Exception e) {
- String msg = String.format("Failed to apply configuration snapshot: %s", configSnapshotHolder);
- LOG.error(msg, e);
- throw new IllegalStateException(msg, e);
- }
-
- LOG.info("Successfully pushed configuration snapshot {}", configSnapshotHolder);
- result.put(configSnapshotHolder, pushResult);
- }
- }
- LOG.info("All configuration snapshots have been pushed successfully.");
- return result;
- }
-
- private synchronized boolean pushConfigWithConflictingVersionRetries(final ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException {
- ConflictingVersionException lastException;
- Stopwatch stopwatch = Stopwatch.createUnstarted();
- do {
- //TODO wait untill all expected modules are in yangStoreService, do we even need to with yangStoreService instead on netconfOperationService?
- String idForReporting = configSnapshotHolder.toString();
- SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
- "Expected capabilities must not be null - %s, check %s", idForReporting,
- configSnapshotHolder.getClass().getName());
-
- // wait max time for required capabilities to appear
- waitForCapabilities(expectedCapabilities, idForReporting);
- try {
- if(!stopwatch.isRunning()) {
- stopwatch.start();
- }
- return pushConfig(configSnapshotHolder);
- } catch (final ConflictingVersionException e) {
- lastException = e;
- LOG.info("Conflicting version detected, will retry after timeout");
- sleep();
- }
- } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
- throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
- lastException);
- }
-
- private void waitForCapabilities(final Set<String> expectedCapabilities, final String idForReporting) {
- Stopwatch stopwatch = Stopwatch.createStarted();
- ConfigPusherException lastException;
- do {
- try {
- final Set<Capability> currentCaps = facade.getCurrentCapabilities();
- final Set<String> notFoundCapabilities = computeNotFoundCapabilities(expectedCapabilities, currentCaps);
- if (notFoundCapabilities.isEmpty()) {
- return;
- } else {
- LOG.debug("Netconf server did not provide required capabilities for {} ", idForReporting,
- "Expected but not found: {}, all expected {}, current {}",
- notFoundCapabilities, expectedCapabilities, currentCaps
- );
- throw new NotEnoughCapabilitiesException(
- "Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundCapabilities, notFoundCapabilities);
- }
- } catch (final ConfigPusherException e) {
- LOG.debug("Not enough capabilities: {}", e.toString());
- lastException = e;
- sleep();
- }
- } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
-
- LOG.error("Unable to push configuration due to missing yang models." +
- " Yang models that are missing, but required by the configuration: {}." +
- " For each mentioned model check: " +
- " 1. that the mentioned yang model namespace/name/revision is identical to those in the yang model itself" +
- " 2. the yang file is present in the system" +
- " 3. the bundle with that yang file is present in the system and active" +
- " 4. the yang parser did not fail while attempting to parse that model",
- ((NotEnoughCapabilitiesException) lastException).getMissingCaps());
- throw new IllegalStateException("Unable to push configuration due to missing yang models." +
- " Required yang models that are missing: "
- + ((NotEnoughCapabilitiesException) lastException).getMissingCaps(), lastException);
- }
-
- private static Set<String> computeNotFoundCapabilities(final Set<String> expectedCapabilities, final Set<Capability> currentCapabilities) {
- Collection<String> actual = transformCapabilities(currentCapabilities);
- Set<String> allNotFound = new HashSet<>(expectedCapabilities);
- allNotFound.removeAll(actual);
- return allNotFound;
- }
-
- static Set<String> transformCapabilities(final Set<Capability> currentCapabilities) {
- return new HashSet<>(Collections2.transform(currentCapabilities, Capability::getCapabilityUri));
- }
-
- static class ConfigPusherException extends Exception {
-
- public ConfigPusherException(final String message) {
- super(message);
- }
-
- public ConfigPusherException(final String message, final Throwable cause) {
- super(message, cause);
- }
- }
-
- static class NotEnoughCapabilitiesException extends ConfigPusherException {
- private static final long serialVersionUID = 1L;
- private final Set<String> missingCaps;
-
- NotEnoughCapabilitiesException(final String message, final Set<String> missingCaps) {
- super(message);
- this.missingCaps = missingCaps;
- }
-
- public Set<String> getMissingCaps() {
- return missingCaps;
- }
- }
-
- private static final class ConfigSnapshotFailureException extends ConfigPusherException {
-
- private final String configIdForReporting;
-
- public ConfigSnapshotFailureException(final String configIdForReporting, final String operationNameForReporting, final Exception e) {
- super(String.format("Failed to apply config snapshot: %s during phase: %s", configIdForReporting, operationNameForReporting), e);
- this.configIdForReporting = configIdForReporting;
- }
-
- public String getConfigIdForReporting() {
- return configIdForReporting;
- }
- }
-
- private void sleep() {
- try {
- Thread.sleep(100);
- } catch (final InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new IllegalStateException(e);
- }
- }
-
- private synchronized boolean pushConfig(final ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException, ConflictingVersionException {
- Element xmlToBePersisted;
- try {
- xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
- } catch (SAXException | IOException e) {
- throw new IllegalStateException("Cannot parse " + configSnapshotHolder, e);
- }
- LOG.trace("Pushing last configuration to config mapping: {}", configSnapshotHolder);
-
- Stopwatch stopwatch = Stopwatch.createStarted();
- final ConfigSubsystemFacade currentFacade = this.facade.createFacade("config-push");
- try {
- ConfigExecution configExecution = createConfigExecution(xmlToBePersisted, currentFacade);
- executeWithMissingModuleFactoryRetries(currentFacade, configExecution);
- } catch (ValidationException | DocumentedException | ModuleFactoryNotFoundException e) {
- LOG.trace("Validation for config: {} failed", configSnapshotHolder, e);
- throw new ConfigSnapshotFailureException(configSnapshotHolder.toString(), "edit", e);
- }
-
- try {
- currentFacade.commitSilentTransaction();
- } catch (ValidationException | DocumentedException e) {
- throw new ConfigSnapshotFailureException(configSnapshotHolder.toString(), "commit", e);
- }
-
- LOG.trace("Last configuration loaded successfully");
- LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
-
- return true;
- }
-
- private void executeWithMissingModuleFactoryRetries(final ConfigSubsystemFacade facade, final ConfigExecution configExecution)
- throws DocumentedException, ValidationException, ModuleFactoryNotFoundException {
- Stopwatch stopwatch = Stopwatch.createStarted();
- ModuleFactoryNotFoundException lastException = null;
- do {
- try {
- facade.executeConfigExecution(configExecution);
- return;
- } catch (final ModuleFactoryNotFoundException e) {
- LOG.debug("{} - will retry after timeout", e.toString());
- lastException = e;
- sleep();
- }
- } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
-
- throw lastException;
- }
-
- private ConfigExecution createConfigExecution(final Element xmlToBePersisted, final ConfigSubsystemFacade currentFacade) throws DocumentedException {
- final Config configMapping = currentFacade.getConfigMapping();
- return currentFacade.getConfigExecution(configMapping, xmlToBePersisted);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.impl;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-import org.opendaylight.controller.config.persist.api.StorageAdapter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NoOpStorageAdapter implements StorageAdapter, Persister {
- private static final Logger LOG = LoggerFactory.getLogger(NoOpStorageAdapter.class);
-
- @Override
- public Persister instantiate(final PropertiesProvider propertiesProvider) {
- LOG.debug("instantiate called with {}", propertiesProvider);
- return this;
- }
-
- @Override
- public void persistConfig(final ConfigSnapshotHolder holder) throws IOException {
- LOG.debug("persistConfig called with {}", holder);
- }
-
- @Override
- public List<ConfigSnapshotHolder> loadLastConfigs() throws IOException {
- LOG.debug("loadLastConfig called");
- return Collections.emptyList();
- }
-
- @Override
- public void close() {
- LOG.debug("close called");
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.impl;
-
-import com.google.common.annotations.VisibleForTesting;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.ListIterator;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-import org.opendaylight.controller.config.persist.api.StorageAdapter;
-import org.opendaylight.controller.config.persist.impl.osgi.ConfigPersisterActivator;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * {@link Persister} implementation that delegates persisting functionality to
- * underlying {@link Persister} storages. Each storage has unique id, class, readonly value.
- *
- * Storage adapters are low level persisters that do the heavy lifting for this
- * class. Instances of storage adapters can be injected directly via constructor
- * or instantiated from a full name of its class provided in a properties file.
- *
- * Example configuration:<pre>
- netconf.config.persister.active=2,3
- # read startup configuration
- netconf.config.persister.1.storageAdapterClass=org.opendaylight.controller.config.persist.storage.directory.xml.XmlDirectoryStorageAdapter
- netconf.config.persister.1.properties.fileStorage=configuration/initial/
-
- netconf.config.persister.2.storageAdapterClass=org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter
- netconf.config.persister.2.readonly=true
- netconf.config.persister.2.properties.fileStorage=configuration/current/controller.config.1.xml
-
- netconf.config.persister.3.storageAdapterClass=org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter
- netconf.config.persister.3.properties.fileStorage=configuration/current/controller.config.2.xml
- netconf.config.persister.3.properties.numberOfBackups=3
-
- </pre>
- * During server startup {@link ConfigPersisterNotificationHandler} requests last snapshot from underlying storages.
- * Each storage can respond by giving snapshot or absent response.
- * The {@link #loadLastConfigs()} will search for first non-absent response from storages ordered backwards as user
- * specified (first '3', then '2').
- *
- * When a commit notification is received, '2' will be omitted because readonly flag is set to true, so
- * only '3' will have a chance to persist new configuration. If readonly was false or not specified, both storage adapters
- * would be called in order specified by 'netconf.config.persister' property.
- *
- */
-public final class PersisterAggregator implements Persister {
- private static final Logger LOG = LoggerFactory.getLogger(PersisterAggregator.class);
-
- public static class PersisterWithConfiguration {
-
- private final Persister storage;
- private final boolean readOnly;
-
- public PersisterWithConfiguration(final Persister storage, final boolean readOnly) {
- this.storage = storage;
- this.readOnly = readOnly;
- }
-
- @VisibleForTesting
- public Persister getStorage() {
- return storage;
- }
-
- @VisibleForTesting
- public boolean isReadOnly() {
- return readOnly;
- }
-
- @Override
- public String toString() {
- return "PersisterWithConfiguration{" +
- "storage=" + storage +
- ", readOnly=" + readOnly +
- '}';
- }
- }
-
- /**
- * Persisters ordered by 'netconf.config.persister' property.
- */
- private final List<PersisterWithConfiguration> persisterWithConfigurations;
-
- public PersisterAggregator(final List<PersisterWithConfiguration> persisterWithConfigurations) {
- this.persisterWithConfigurations = persisterWithConfigurations;
- }
-
- private static PersisterWithConfiguration loadConfiguration(final String index, final PropertiesProvider propertiesProvider) {
-
- String classKey = index + "." + ConfigPersisterActivator.STORAGE_ADAPTER_CLASS_PROP_SUFFIX;
- String storageAdapterClass = propertiesProvider.getProperty(classKey);
- StorageAdapter storageAdapter;
- if (storageAdapterClass == null || storageAdapterClass.isEmpty()) {
- throw new IllegalStateException("No persister is defined in " +
- propertiesProvider.getFullKeyForReporting(classKey)
- + " property. Persister is not operational");
- }
-
- try {
- Class<?> clazz = Class.forName(storageAdapterClass);
- boolean implementsCorrectIfc = StorageAdapter.class.isAssignableFrom(clazz);
- if (!implementsCorrectIfc) {
- throw new IllegalArgumentException("Storage adapter " + clazz + " does not implement " + StorageAdapter.class);
- }
- storageAdapter = StorageAdapter.class.cast(clazz.newInstance());
-
- String readOnlyProperty = propertiesProvider.getProperty(index + "." + "readonly");
- boolean readOnly = Boolean.parseBoolean(readOnlyProperty);
-
- PropertiesProviderAdapterImpl innerProvider = new PropertiesProviderAdapterImpl(propertiesProvider, index);
- Persister storage = storageAdapter.instantiate(innerProvider);
- return new PersisterWithConfiguration(storage, readOnly);
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
- throw new IllegalArgumentException("Unable to instantiate storage adapter from " + storageAdapterClass, e);
- }
- }
-
- public static PersisterAggregator createFromProperties(final PropertiesProvider propertiesProvider) {
- List<PersisterWithConfiguration> persisterWithConfigurations = new ArrayList<>();
- String prefixes = propertiesProvider.getProperty("active");
- if (prefixes!=null && !prefixes.isEmpty()) {
- String [] keys = prefixes.split(",");
- for (String index: keys) {
- persisterWithConfigurations.add(PersisterAggregator.loadConfiguration(index, propertiesProvider));
- }
- }
- LOG.debug("Initialized persister with following adapters {}", persisterWithConfigurations);
- return new PersisterAggregator(persisterWithConfigurations);
- }
-
- @Override
- public void persistConfig(final ConfigSnapshotHolder holder) throws IOException {
- for (PersisterWithConfiguration persisterWithConfiguration: persisterWithConfigurations){
- if (!persisterWithConfiguration.readOnly){
- LOG.debug("Calling {}.persistConfig", persisterWithConfiguration.getStorage());
- persisterWithConfiguration.getStorage().persistConfig(holder);
- }
- }
- }
-
- /**
- * @return last non-empty result from input persisters
- */
- @Override
- public List<ConfigSnapshotHolder> loadLastConfigs() {
- // iterate in reverse order
- ListIterator<PersisterWithConfiguration> li = persisterWithConfigurations.listIterator(persisterWithConfigurations.size());
- while(li.hasPrevious()) {
- PersisterWithConfiguration persisterWithConfiguration = li.previous();
- List<ConfigSnapshotHolder> configs = null;
- try {
- configs = persisterWithConfiguration.storage.loadLastConfigs();
- } catch (final IOException e) {
- throw new RuntimeException("Error while calling loadLastConfig on " + persisterWithConfiguration, e);
- }
- if (!configs.isEmpty()) {
- LOG.debug("Found non empty configs using {}:{}", persisterWithConfiguration, configs);
- return configs;
- }
- }
- // no storage had an answer
- LOG.debug("No non-empty list of configuration snapshots found");
- return Collections.emptyList();
- }
-
- @VisibleForTesting
- List<PersisterWithConfiguration> getPersisterWithConfigurations() {
- return persisterWithConfigurations;
- }
-
- @Override
- public void close() {
- RuntimeException lastException = null;
- for (PersisterWithConfiguration persisterWithConfiguration: persisterWithConfigurations){
- try{
- persisterWithConfiguration.storage.close();
- }catch(final RuntimeException e) {
- LOG.error("Error while closing {}", persisterWithConfiguration.storage, e);
- if (lastException == null){
- lastException = e;
- } else {
- lastException.addSuppressed(e);
- }
- }
- }
- if (lastException != null){
- throw lastException;
- }
- }
-
- @Override
- public String toString() {
- return "PersisterAggregator{" +
- "persisterWithConfigurations=" + persisterWithConfigurations +
- '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.impl;
-
-import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-
-public class PropertiesProviderAdapterImpl implements PropertiesProvider {
- private final PropertiesProvider inner;
- private final String index;
-
- public PropertiesProviderAdapterImpl(final PropertiesProvider inner, final String index) {
- this.inner = inner;
- this.index = index;
- }
-
- @Override
- public String getProperty(final String key) {
- String fullKey = getFullKeyForReporting(key);
- return inner.getPropertyWithoutPrefix(fullKey);
- }
-
- public String getPrefix() {
- return inner.getPrefix() + "." + index + ".properties";
- }
-
- @Override
- public String getPropertyWithoutPrefix(final String fullKey) {
- return inner.getPropertyWithoutPrefix(fullKey);
- }
-
-
- @Override
- public String getFullKeyForReporting(final String key) {
- return getPrefix() + "." + key;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.impl.osgi;
-
-import com.google.common.collect.Lists;
-import java.lang.management.ManagementFactory;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import javax.management.MBeanServer;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.impl.ConfigPusherImpl;
-import org.opendaylight.controller.config.persist.impl.PersisterAggregator;
-import org.opendaylight.controller.config.util.CloseableUtil;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.ServiceTracker;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConfigPersisterActivator implements BundleActivator {
-
- private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterActivator.class);
- private static final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
-
- public static final String MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY = "maxWaitForCapabilitiesMillis";
- private static final long MAX_WAIT_FOR_CAPABILITIES_MILLIS_DEFAULT = TimeUnit.MINUTES.toMillis(2);
- public static final String CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY = "conflictingVersionTimeoutMillis";
- private static final long CONFLICTING_VERSION_TIMEOUT_MILLIS_DEFAULT = TimeUnit.MINUTES.toMillis(1);
-
- public static final String NETCONF_CONFIG_PERSISTER = "netconf.config.persister";
-
- public static final String STORAGE_ADAPTER_CLASS_PROP_SUFFIX = "storageAdapterClass";
-
- private final List<AutoCloseable> autoCloseables = Lists.newArrayList();
- private volatile BundleContext context;
-
- ServiceRegistration<?> registration;
-
- @Override
- public void start(final BundleContext context) throws Exception {
- LOG.debug("ConfigPersister starting");
- this.context = context;
-
- PropertiesProviderBaseImpl propertiesProvider = new PropertiesProviderBaseImpl(context);
-
- final PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(propertiesProvider);
- autoCloseables.add(persisterAggregator);
- final long maxWaitForCapabilitiesMillis = getMaxWaitForCapabilitiesMillis(propertiesProvider);
- final List<ConfigSnapshotHolder> configs = persisterAggregator.loadLastConfigs();
- final long conflictingVersionTimeoutMillis = getConflictingVersionTimeoutMillis(propertiesProvider);
- LOG.debug("Following configs will be pushed: {}", configs);
-
- ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory> schemaServiceTrackerCustomizer = new ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory>() {
-
- @Override
- public ConfigSubsystemFacadeFactory addingService(final ServiceReference<ConfigSubsystemFacadeFactory> reference) {
- LOG.debug("Got addingService(SchemaContextProvider) event");
- // Yang store service should not be registered multiple times
- ConfigSubsystemFacadeFactory configSubsystemFacadeFactory = reference.getBundle().getBundleContext().getService(reference);
- startPusherThread(configs, maxWaitForCapabilitiesMillis, configSubsystemFacadeFactory, conflictingVersionTimeoutMillis, persisterAggregator);
- return configSubsystemFacadeFactory;
- }
-
- @Override
- public void modifiedService(final ServiceReference<ConfigSubsystemFacadeFactory> reference, final ConfigSubsystemFacadeFactory service) {
- LOG.warn("Config manager facade was modified unexpectedly");
- }
-
- @Override
- public void removedService(final ServiceReference<ConfigSubsystemFacadeFactory> reference, final ConfigSubsystemFacadeFactory service) {
- LOG.warn("Config manager facade was removed unexpectedly");
- }
- };
-
- ServiceTracker<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory> schemaContextProviderServiceTracker =
- new ServiceTracker<>(context, ConfigSubsystemFacadeFactory.class, schemaServiceTrackerCustomizer);
- schemaContextProviderServiceTracker.open();
- }
-
- private long getConflictingVersionTimeoutMillis(final PropertiesProviderBaseImpl propertiesProvider) {
- String timeoutProperty = propertiesProvider.getProperty(CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY);
- return timeoutProperty == null ? CONFLICTING_VERSION_TIMEOUT_MILLIS_DEFAULT : Long.valueOf(timeoutProperty);
- }
-
- private long getMaxWaitForCapabilitiesMillis(final PropertiesProviderBaseImpl propertiesProvider) {
- String timeoutProperty = propertiesProvider.getProperty(MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY);
- return timeoutProperty == null ? MAX_WAIT_FOR_CAPABILITIES_MILLIS_DEFAULT : Long.valueOf(timeoutProperty);
- }
-
- @Override
- public void stop(final BundleContext context) throws Exception {
- synchronized(autoCloseables) {
- CloseableUtil.closeAll(autoCloseables);
- autoCloseables.clear();
- if (registration != null) {
- registration.unregister();
- }
- this.context = null;
- }
- }
-
- private void startPusherThread(final List<? extends ConfigSnapshotHolder> configs, final long maxWaitForCapabilitiesMillis,
- final ConfigSubsystemFacadeFactory service, final long conflictingVersionTimeoutMillis, final Persister persisterAggregator){
- LOG.debug("Creating new job queue");
- final ConfigPusherImpl configPusher = new ConfigPusherImpl(service,
- maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis);
- LOG.debug("Configuration Persister got {}", service);
- LOG.debug("Context was {}", context);
- LOG.debug("Registration was {}", registration);
- final Thread pushingThread = new Thread(() -> {
- try {
- if(configs != null && !configs.isEmpty()) {
- configPusher.pushConfigs(configs);
- }
- if(context != null) {
- registration = context.registerService(ConfigPusher.class.getName(), configPusher, null);
- configPusher.process(autoCloseables, platformMBeanServer, persisterAggregator, false);
- } else {
- LOG.warn("Unable to process configs as BundleContext is null");
- }
- } catch (final InterruptedException e) {
- LOG.info("ConfigPusher thread stopped");
- }
- LOG.info("Configuration Persister initialization completed.");
- }, "config-pusher");
- synchronized (autoCloseables) {
- autoCloseables.add(() -> pushingThread.interrupt());
- }
- pushingThread.setDaemon(true);
- pushingThread.start();
- }
-}
-
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.impl.osgi;
-
-import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-import org.osgi.framework.BundleContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class PropertiesProviderBaseImpl implements PropertiesProvider {
-
- private static final Logger LOG = LoggerFactory.getLogger(PropertiesProviderBaseImpl.class);
- private final BundleContext bundleContext;
-
- public PropertiesProviderBaseImpl(final BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-
- @Override
- public String getProperty(final String key) {
- String fullKey = getFullKeyForReporting(key);
- return getPropertyWithoutPrefix(fullKey);
- }
-
- public String getPropertyWithoutPrefix(final String fullKey){
- LOG.trace("Full key {}", fullKey);
- return bundleContext.getProperty(fullKey);
- }
-
- public String getPrefix(){
- return ConfigPersisterActivator.NETCONF_CONFIG_PERSISTER;
- }
-
- @Override
- public String getFullKeyForReporting(final String key) {
- return getPrefix() + "." + key;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.impl;
-
-import static org.junit.Assert.assertEquals;
-
-import com.google.common.collect.Sets;
-import com.google.common.io.Resources;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.util.HashSet;
-import java.util.Set;
-import org.junit.Test;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.w3c.dom.Element;
-
-public class CapabilityStrippingConfigSnapshotHolderTest {
-
- @Test
- public void testCapabilityStripping() throws Exception {
- Set<String> allCapabilities = readLines("/capabilities-all.txt");
- Set<String> expectedCapabilities = readLines("/capabilities-stripped.txt");
- String snapshotAsString = readToString("/snapshot.xml");
- Element element = XmlUtil.readXmlToElement(snapshotAsString);
- CapabilityStrippingConfigSnapshotHolder tested = new CapabilityStrippingConfigSnapshotHolder(
- element, allCapabilities);
- assertEquals(expectedCapabilities, tested.getCapabilities());
-
- Set<String> obsoleteCapabilities = Sets.difference(allCapabilities, expectedCapabilities);
-
- assertEquals(obsoleteCapabilities, tested.getObsoleteCapabilities());
- }
-
- private Set<String> readLines(final String fileName) throws IOException {
- return new HashSet<>(Resources.readLines(getClass().getResource(fileName), StandardCharsets.UTF_8));
- }
-
- private String readToString(final String fileName) throws IOException {
- return Resources.toString(getClass().getResource(fileName), StandardCharsets.UTF_8);
- }
-
-}
+++ /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.config.persist.impl;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import javax.management.MBeanServerConnection;
-import javax.management.NotificationFilter;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-
-public class ConfigPersisterNotificationHandlerTest {
-
- @Mock
- private MBeanServerConnection mBeanServer;
- @Mock
- private Persister notificationListener;
- @Mock
- private ConfigSubsystemFacadeFactory facadeFactory;
- @Mock
- private ConfigSubsystemFacade facade;
- @Mock
- private ConfigRegistryClient configRegistryClient;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
-
- doReturn(facade).when(facadeFactory).createFacade(anyString());
-
- doNothing().when(mBeanServer).addNotificationListener(any(ObjectName.class), any(NotificationListener.class),
- any(NotificationFilter.class), anyObject());
- }
-
- @Test
- public void testNotificationHandler() throws Exception {
- doReturn(true).when(mBeanServer).isRegistered(any(ObjectName.class));
- doThrow(Exception.class).when(mBeanServer).removeNotificationListener(any(ObjectName.class), any(NotificationListener.class));
-
- final ConfigPersisterNotificationHandler testedHandler = new ConfigPersisterNotificationHandler(mBeanServer, notificationListener, facadeFactory);
- verify(mBeanServer).addNotificationListener(any(ObjectName.class), any(NotificationListener.class),
- any(NotificationFilter.class), anyObject());
-
- testedHandler.close();
- verify(mBeanServer).removeNotificationListener(any(ObjectName.class), any(NotificationListener.class));
- }
-
- @Test
- public void testNotificationHandlerCloseNotRegistered() throws Exception {
- doReturn(false).when(mBeanServer).isRegistered(any(ObjectName.class));
-
- final ConfigPersisterNotificationHandler testedHandler = new ConfigPersisterNotificationHandler(mBeanServer, notificationListener, facadeFactory);
-
- testedHandler.close();
- verify(mBeanServer, times(0)).removeNotificationListener(any(ObjectName.class), any(NotificationListener.class));
- }
-}
+++ /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.config.persist.impl;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doReturn;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-import java.util.Collections;
-import javax.management.Notification;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.api.jmx.notifications.CommitJMXNotification;
-import org.opendaylight.controller.config.api.jmx.notifications.ConfigJMXNotification;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
-import org.opendaylight.controller.config.facade.xml.Datastore;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.w3c.dom.Document;
-
-public class ConfigPersisterNotificationListenerTest {
-
- @Mock
- private Persister mockPersister;
- private PersisterAggregator persisterAggregator;
-
- @Mock
- private ConfigJMXNotification unknownNetconfNotif;
- @Mock
- private CommitJMXNotification commitNetconfNotif;
- @Mock
- private Notification unknownNotif;
- @Mock
- private ConfigSubsystemFacadeFactory facadeFactory;
- @Mock
- private ConfigSubsystemFacade facade;
- @Mock
- private ConfigRegistryClient configRegistryClient;
- @Mock
- private Capability cap;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
-
- Mockito.doNothing().when(mockPersister).persistConfig(any(ConfigSnapshotHolder.class));
- doReturn("persister").when(mockPersister).toString();
- final PersisterAggregator.PersisterWithConfiguration withCfg = new PersisterAggregator.PersisterWithConfiguration(mockPersister, false);
- persisterAggregator = new PersisterAggregator(Lists.newArrayList(withCfg));
-
- doReturn("netconfUnknownNotification").when(unknownNetconfNotif).toString();
- doReturn("netconfCommitNotification").when(commitNetconfNotif).toString();
-
- doReturn("config client").when(configRegistryClient).toString();
-
- doReturn("cap").when(cap).getCapabilityUri();
- doReturn(facade).when(facadeFactory).createFacade(anyString());
-
- doReturn(Collections.singleton(cap)).when(facadeFactory).getCurrentCapabilities();
- doReturn(XmlUtil.readXmlToElement("<snapshot/>")).when(facade)
- .getConfiguration(any(Document.class), any(Datastore.class), any(Optional.class));
- }
-
- @Test
- public void testNotificationListenerUnknownNotification() throws Exception {
- final ConfigPersisterNotificationListener testeListener = new ConfigPersisterNotificationListener(persisterAggregator, facadeFactory);
- testeListener.handleNotification(unknownNotif, null);
- Mockito.verifyZeroInteractions(mockPersister);
- }
-
- @Test
- public void testNotificationListenerUnknownNetconfNotification() throws Exception {
- final ConfigPersisterNotificationListener testeListener = new ConfigPersisterNotificationListener(persisterAggregator, facadeFactory);
- try {
- testeListener.handleNotification(unknownNetconfNotif, null);
- Assert.fail("Unknown netconf notification should fail");
- } catch (final IllegalStateException e) {
- Mockito.verifyZeroInteractions(mockPersister);
- }
- }
-
- @Test
- public void testNotificationListenerCommitNetconfNotification() throws Exception {
- final ConfigPersisterNotificationListener testeListener = new ConfigPersisterNotificationListener(persisterAggregator, facadeFactory);
- testeListener.handleNotification(commitNetconfNotif, null);
- Mockito.verify(mockPersister).persistConfig(any(ConfigSnapshotHolder.class));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import com.google.common.base.Throwables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import java.lang.management.ManagementFactory;
-import java.util.Collections;
-import java.util.Set;
-import java.util.TreeSet;
-import javax.management.MBeanServerConnection;
-import javax.management.NotificationFilter;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.facade.xml.ConfigExecution;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
-import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
-import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
-import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.capability.Capability;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.w3c.dom.Element;
-
-public class ConfigPusherImplTest {
-
- @Mock
- private YangStoreService yangStoreService;
- @Mock
- private ConfigSnapshotHolder mockedConfigSnapshot;
- @Mock
- private Persister mockedAggregator;
- @Mock
- private ConfigRegistryClient configRegistryClient;
- @Mock
- private org.opendaylight.yangtools.yang.model.api.Module module;
- @Mock
- private ConfigSubsystemFacadeFactory facadeFactory;
- @Mock
- private ConfigSubsystemFacade facade;
- @Mock
- private MBeanServerConnection mBeanServer;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- doReturn("content").when(yangStoreService).getModuleSource(any(SourceIdentifier.class));
- doReturn("mocked snapshot").when(mockedConfigSnapshot).toString();
- doReturn("<mocked-snapshot/>").when(mockedConfigSnapshot).getConfigSnapshot();
- doReturn(Collections.<Module>emptySet()).when(yangStoreService).getModules();
- final Config mock = mock(Config.class);
- doReturn("mocked config").when(mock).toString();
- doReturn(facade).when(facadeFactory).createFacade(anyString());
- doReturn(Sets.newHashSet()).when(facadeFactory).getCurrentCapabilities();
- doReturn(mock).when(facade).getConfigMapping();
- doNothing().when(mBeanServer).addNotificationListener(any(ObjectName.class), any(NotificationListener.class), any(NotificationFilter.class), anyObject());
- }
-
- @Test
- public void testPersisterNotAllCapabilitiesProvided() throws Exception {
- doReturn(new TreeSet<>(Lists.newArrayList("required-cap"))).when(mockedConfigSnapshot).getCapabilities();
-
- final ConfigPusherImpl configPusher = new ConfigPusherImpl(facadeFactory, 0, 0);
-
- configPusher.pushConfigs(Collections.singletonList(mockedConfigSnapshot));
- try {
- configPusher.process(Lists.<AutoCloseable>newArrayList(), ManagementFactory.getPlatformMBeanServer(),
- mockedAggregator, true);
- } catch(final IllegalStateException e) {
- Throwable cause = Throwables.getRootCause(e);
- assertTrue(cause instanceof ConfigPusherImpl.NotEnoughCapabilitiesException);
- final Set<String> missingCaps = ((ConfigPusherImpl.NotEnoughCapabilitiesException) cause).getMissingCaps();
- assertEquals(missingCaps.size(), 1);
- assertEquals(missingCaps.iterator().next(), "required-cap");
- return;
- }
-
- fail();
- }
-
- @Test
- public void testPersisterSuccessfulPush() throws Exception {
- doReturn(new TreeSet<>(Lists.newArrayList("namespace?module=module&revision=2012-12-12"))).when(mockedConfigSnapshot).getCapabilities();
- final Capability cap = mock(Capability.class);
- doReturn("namespace?module=module&revision=2012-12-12").when(cap).getCapabilityUri();
- doReturn(Sets.newHashSet(cap)).when(facadeFactory).getCurrentCapabilities();
- final ConfigExecution cfgExec = mock(ConfigExecution.class);
- doReturn("cfg exec").when(cfgExec).toString();
- doReturn(cfgExec).when(facade).getConfigExecution(any(Config.class), any(Element.class));
- doNothing().when(facade).executeConfigExecution(any(ConfigExecution.class));
- doReturn(mock(CommitStatus.class)).when(facade).commitSilentTransaction();
- doReturn(Sets.newHashSet(module)).when(yangStoreService).getModules();
-
- final ConfigPusherImpl configPusher = new ConfigPusherImpl(facadeFactory, 0, 0);
-
- configPusher.pushConfigs(Collections.singletonList(mockedConfigSnapshot));
- configPusher.processSingle(Lists.<AutoCloseable>newArrayList(), mBeanServer, mockedAggregator, true);
-
- verify(facade).executeConfigExecution(cfgExec);
- verify(facade).commitSilentTransaction();
- }
-
- @Test
- public void testPersisterConflictingVersionException() throws Exception {
- doReturn(new TreeSet<>(Lists.newArrayList("namespace?module=module&revision=2012-12-12"))).when(mockedConfigSnapshot).getCapabilities();
- final Capability cap = mock(Capability.class);
- doReturn("namespace?module=module&revision=2012-12-12").when(cap).getCapabilityUri();
- doReturn(Sets.newHashSet(cap)).when(facadeFactory).getCurrentCapabilities();
- final ConfigExecution cfgExec = mock(ConfigExecution.class);
- doReturn("cfg exec").when(cfgExec).toString();
- doReturn(cfgExec).when(facade).getConfigExecution(any(Config.class), any(Element.class));
- doNothing().when(facade).executeConfigExecution(any(ConfigExecution.class));
- doThrow(ConflictingVersionException.class).when(facade).commitSilentTransaction();
- doReturn(Sets.newHashSet(module)).when(yangStoreService).getModules();
-
- final ConfigPusherImpl configPusher = new ConfigPusherImpl(facadeFactory, 0, 0);
-
- configPusher.pushConfigs(Collections.singletonList(mockedConfigSnapshot));
- try {
- configPusher.processSingle(Lists.<AutoCloseable>newArrayList(), mBeanServer, mockedAggregator, true);
- } catch (final IllegalStateException e) {
- Throwable cause = Throwables.getRootCause(e);
- assertTrue(cause instanceof ConflictingVersionException);
- return;
- }
-
- fail();
- }
-
- @Test
- public void testSuccessConflictingVersionException() throws Exception {
- doReturn(new TreeSet<>(Lists.newArrayList("namespace?module=module&revision=2012-12-12"))).when(mockedConfigSnapshot).getCapabilities();
- final Capability cap = mock(Capability.class);
- doReturn("namespace?module=module&revision=2012-12-12").when(cap).getCapabilityUri();
- doReturn(Sets.newHashSet(cap)).when(facadeFactory).getCurrentCapabilities();
- final ConfigExecution cfgExec = mock(ConfigExecution.class);
- doReturn("cfg exec").when(cfgExec).toString();
- doReturn(cfgExec).when(facade).getConfigExecution(any(Config.class), any(Element.class));
- doNothing().when(facade).executeConfigExecution(any(ConfigExecution.class));
-
- doThrow(ConflictingVersionException.class)
- .doThrow(ConflictingVersionException.class)
- .doReturn(mock(CommitStatus.class)).when(facade).commitSilentTransaction();
-
- doReturn(Sets.newHashSet(module)).when(yangStoreService).getModules();
-
- final ConfigPusherImpl configPusher = new ConfigPusherImpl(facadeFactory, 5000, 5000);
-
- configPusher.pushConfigs(Collections.singletonList(mockedConfigSnapshot));
- configPusher.processSingle(Lists.<AutoCloseable>newArrayList(), mBeanServer, mockedAggregator, true);
-
- verify(facade, times(3)).executeConfigExecution(cfgExec);
- verify(facade, times(3)).commitSilentTransaction();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.persist.impl;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-import org.opendaylight.controller.config.persist.api.StorageAdapter;
-
-public class DummyAdapter implements StorageAdapter, Persister {
-
- static int persist = 0;
-
- @Override
- public void persistConfig(final ConfigSnapshotHolder holder) throws IOException {
- persist++;
- }
-
- static int load = 0;
-
- @Override
- public List<ConfigSnapshotHolder> loadLastConfigs() throws IOException {
- load++;
- return Collections.emptyList();
- }
-
- static int props = 0;
-
- @Override
- public Persister instantiate(final PropertiesProvider propertiesProvider) {
- props++;
- return this;
- }
-
- @Override
- public void close() {
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.persist.impl;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import com.google.common.collect.Lists;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Properties;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.impl.PersisterAggregator.PersisterWithConfiguration;
-import org.opendaylight.controller.config.persist.impl.osgi.ConfigPersisterActivator;
-import org.opendaylight.controller.config.persist.impl.osgi.PropertiesProviderBaseImpl;
-import org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter;
-
-public class PersisterAggregatorTest {
-
- static class TestingPropertiesProvider extends PropertiesProviderBaseImpl {
-
- private final Properties prop;
-
- public TestingPropertiesProvider(final Properties prop) {
- super(null);
- this.prop = prop;
- }
-
- public static TestingPropertiesProvider loadFile(final String fileName) {
- Properties prop = new Properties();
- try {
- prop.load(TestingPropertiesProvider.class.getClassLoader().getResourceAsStream(fileName));
- } catch (final IOException e) {
- throw new RuntimeException(e);
- }
- return new TestingPropertiesProvider(prop);
- }
-
- @Override
- public String getFullKeyForReporting(final String key) {
- return ConfigPersisterActivator.NETCONF_CONFIG_PERSISTER + "." + key;
- }
-
- @Override
- public String getProperty(final String key) {
- return prop.getProperty(getFullKeyForReporting(key));
- }
-
- @Override
- public String getPropertyWithoutPrefix(final String fullKey){
- return prop.getProperty(fullKey);
- }
- }
-
- @Before
- public void setUp() throws Exception {
- if(XmlFileStorageAdapter.getInstance().isPresent()) {
- XmlFileStorageAdapter.getInstance().get().reset();
- }
- }
-
- @Test
- public void testDummyAdapter() throws Exception {
- PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(TestingPropertiesProvider.loadFile("test1.properties"));
- List<PersisterWithConfiguration> persisters = persisterAggregator.getPersisterWithConfigurations();
- assertEquals(1, persisters.size());
- PersisterWithConfiguration persister = persisters.get(0);
- assertEquals(DummyAdapter.class.getName(), persister.getStorage().getClass().getName());
- assertFalse(persister.isReadOnly());
-
- persisterAggregator.persistConfig(null);
- persisterAggregator.loadLastConfigs();
- persisterAggregator.persistConfig(null);
- persisterAggregator.loadLastConfigs();
-
- assertEquals(2, DummyAdapter.persist);
- assertEquals(2, DummyAdapter.load);
- assertEquals(1, DummyAdapter.props);
- }
-
- @Test
- public void testNoopAdapter() throws Exception {
- final NoOpStorageAdapter noOpStorageAdapter = new NoOpStorageAdapter();
- try (final PersisterAggregator persisterAggregator = new PersisterAggregator(
- Lists.newArrayList(new PersisterWithConfiguration(noOpStorageAdapter, false)))) {
-
- noOpStorageAdapter.instantiate(null);
-
- persisterAggregator.persistConfig(null);
- persisterAggregator.loadLastConfigs();
- persisterAggregator.persistConfig(null);
- persisterAggregator.loadLastConfigs();
-
- noOpStorageAdapter.close();
- }
- }
-
- @Test
- public void testLoadFromPropertyFile() throws Exception {
- PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(TestingPropertiesProvider.loadFile("test2.properties"));
- List<PersisterWithConfiguration> persisters = persisterAggregator.getPersisterWithConfigurations();
- assertEquals(1, persisters.size());
- PersisterWithConfiguration persister = persisters.get(0);
- assertEquals(XmlFileStorageAdapter.class.getName() ,persister.getStorage().getClass().getName());
- assertFalse(persister.isReadOnly());
- }
-
- @Test
- public void testFileStorageNumberOfBackups() throws Exception {
- try {
- PersisterAggregator.createFromProperties(TestingPropertiesProvider.loadFile("test3.properties"));
- fail();
- } catch (final RuntimeException e) {
- assertThat(
- e.getMessage(),
- containsString("numberOfBackups property should be either set to positive value, or ommited. Can not be set to 0."));
- }
- }
-
- private ConfigSnapshotHolder mockHolder(final String name){
- ConfigSnapshotHolder result = mock(ConfigSnapshotHolder.class);
- doReturn("mock:" + name).when(result).toString();
- return result;
- }
-
- private Persister mockPersister(final String name){
- Persister result = mock(Persister.class);
- doReturn("mock:" + name).when(result).toString();
- doNothing().when(result).close();
- return result;
- }
-
- @Test
- public void loadLastConfig() throws Exception {
- List<PersisterWithConfiguration> persisterWithConfigurations = new ArrayList<>();
- PersisterWithConfiguration first = new PersisterWithConfiguration(mockPersister("p0"), false);
-
- ConfigSnapshotHolder ignored = mockHolder("ignored");
- doReturn(Arrays.asList(ignored)).when(first.getStorage()).loadLastConfigs(); // should be ignored
-
-
- ConfigSnapshotHolder used = mockHolder("used");
- PersisterWithConfiguration second = new PersisterWithConfiguration(mockPersister("p1"), false);
- doReturn(Arrays.asList(used)).when(second.getStorage()).loadLastConfigs(); // should be used
-
- PersisterWithConfiguration third = new PersisterWithConfiguration(mockPersister("p2"), false);
- doReturn(Arrays.asList()).when(third.getStorage()).loadLastConfigs();
-
- persisterWithConfigurations.add(first);
- persisterWithConfigurations.add(second);
- persisterWithConfigurations.add(third);
-
- try (PersisterAggregator persisterAggregator = new PersisterAggregator(persisterWithConfigurations)) {
- List<ConfigSnapshotHolder> configSnapshotHolderOptional = persisterAggregator.loadLastConfigs();
- assertEquals(1, configSnapshotHolderOptional.size());
- assertEquals(used, configSnapshotHolderOptional.get(0));
- }
- }
-}
+++ /dev/null
-urn:opendaylight:l2:types?module=opendaylight-l2-types&revision=2013-08-27
-urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding?module=opendaylight-md-sal-binding&revision=2013-10-28
-urn:opendaylight:params:xml:ns:yang:controller:threadpool?module=threadpool&revision=2013-04-09
-urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom?module=opendaylight-md-sal-dom&revision=2013-10-28
-urn:opendaylight:params:xml:ns:yang:controller:config?module=config&revision=2013-04-05
-urn:ietf:params:netconf:capability:candidate:1.0
-urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04
-urn:opendaylight:params:xml:ns:yang:controller:netty:eventexecutor?module=netty-event-executor&revision=2013-11-12
-urn:ietf:params:xml:ns:yang:rpc-context?module=rpc-context&revision=2013-06-17
-urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl?module=opendaylight-sal-binding-broker-impl&revision=2013-10-28
-urn:ietf:params:xml:ns:yang:ietf-inet-types?module=ietf-inet-types&revision=2010-09-24
-urn:ietf:params:netconf:capability:rollback-on-error:1.0
-urn:ietf:params:xml:ns:yang:ietf-yang-types?module=ietf-yang-types&revision=2010-09-24
-urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl?module=threadpool-impl&revision=2013-04-05
-urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl?module=opendaylight-sal-dom-broker-impl&revision=2013-10-28
-urn:opendaylight:yang:extension:yang-ext?module=yang-ext&revision=2013-07-09
-urn:opendaylight:params:xml:ns:yang:iana?module=iana&revision=2013-08-16
-urn:opendaylight:params:xml:ns:yang:controller:md:sal:common?module=opendaylight-md-sal-common&revision=2013-10-28
-urn:opendaylight:params:xml:ns:yang:ieee754?module=ieee754&revision=2013-08-19
+++ /dev/null
-urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding?module=opendaylight-md-sal-binding&revision=2013-10-28
-urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom?module=opendaylight-md-sal-dom&revision=2013-10-28
-urn:opendaylight:params:xml:ns:yang:controller:config?module=config&revision=2013-04-05
-urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl?module=opendaylight-sal-binding-broker-impl&revision=2013-10-28
-urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl?module=opendaylight-sal-dom-broker-impl&revision=2013-10-28
+++ /dev/null
-<data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
- <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
- <module>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">prefix:schema-service-singleton</type>
- <name>yang-schema-service</name>
- </module>
- <module>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">prefix:hash-map-data-store</type>
- <name>hash-map-data-store</name>
- </module>
- <module>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">prefix:dom-broker-impl</type>
- <name>dom-broker</name>
- <data-store xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">
- <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-data-store</type>
- <name>ref_hash-map-data-store</name>
- </data-store>
- </module>
- <module>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">prefix:binding-broker-impl</type>
- <name>binding-broker-impl</name>
- <notification-service xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
- <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-notification-service</type>
- <name>ref_binding-notification-broker</name>
- </notification-service>
- <data-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
- <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-data-broker</type>
- <name>ref_binding-data-broker</name>
- </data-broker>
- </module>
- <module>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">prefix:runtime-generated-mapping</type>
- <name>runtime-mapping-singleton</name>
- </module>
- <module>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">prefix:binding-notification-broker</type>
- <name>binding-notification-broker</name>
- </module>
- <module>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">prefix:binding-data-broker</type>
- <name>binding-data-broker</name>
- <dom-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
- <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-broker-osgi-registry</type>
- <name>ref_dom-broker</name>
- </dom-broker>
- <mapping-service xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
- <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">binding:binding-dom-mapping-service</type>
- <name>ref_runtime-mapping-singleton</name>
- </mapping-service>
- </module>
- </modules>
- <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
- <service>
- <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:schema-service</type>
- <instance>
- <name>ref_yang-schema-service</name>
- <provider>/config/modules/module[name='schema-service-singleton']/instance[name='yang-schema-service']</provider>
- </instance>
- </service>
- <service>
- <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-notification-service</type>
- <instance>
- <name>ref_binding-notification-broker</name>
- <provider>/config/modules/module[name='binding-notification-broker']/instance[name='binding-notification-broker']</provider>
- </instance>
- </service>
- <service>
- <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-data-store</type>
- <instance>
- <name>ref_hash-map-data-store</name>
- <provider>/config/modules/module[name='hash-map-data-store']/instance[name='hash-map-data-store']</provider>
- </instance>
- </service>
- <service>
- <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-broker-osgi-registry</type>
- <instance>
- <name>ref_binding-broker-impl</name>
- <provider>/config/modules/module[name='binding-broker-impl']/instance[name='binding-broker-impl']</provider>
- </instance>
- </service>
- <service>
- <type xmlns:binding-impl="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">binding-impl:binding-dom-mapping-service</type>
- <instance>
- <name>ref_runtime-mapping-singleton</name>
- <provider>/config/modules/module[name='runtime-generated-mapping']/instance[name='runtime-mapping-singleton']</provider>
- </instance>
- </service>
- <service>
- <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-broker-osgi-registry</type>
- <instance>
- <name>ref_dom-broker</name>
- <provider>/config/modules/module[name='dom-broker-impl']/instance[name='dom-broker']</provider>
- </instance>
- </service>
- <service>
- <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-data-broker</type>
- <instance>
- <name>ref_binding-data-broker</name>
- <provider>/config/modules/module[name='binding-data-broker']/instance[name='binding-data-broker']</provider>
- </instance>
- </service>
- </services>
-</data>
+++ /dev/null
-netconf.config.persister.active=1
-netconf.config.persister.1.storageAdapterClass=org.opendaylight.controller.config.persist.impl.DummyAdapter
-netconf.config.persister.1.properties.fileStorage=target/configuration/initial/
+++ /dev/null
-netconf.config.persister.active=2
-# read startup configuration
-netconf.config.persister.1.storageAdapterClass=org.opendaylight.controller.config.persist.storage.directory.xml.XmlDirectoryStorageAdapter
-netconf.config.persister.1.properties.directoryStorage=target/configuration/initial/
-netconf.config.persister.1.readonly=true
-
-netconf.config.persister.2.storageAdapterClass=org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter
-netconf.config.persister.2.properties.fileStorage=target/configuration/current/controller.config.2.txt
-netconf.config.persister.2.properties.numberOfBackups=3
+++ /dev/null
-netconf.config.persister.active=3
-netconf.config.persister.3.storageAdapterClass=org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter
-netconf.config.persister.3.properties.fileStorage=target/configuration/current/controller.config.2.txt
-netconf.config.persister.3.properties.numberOfBackups=0
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<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>config-subsystem</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>../</relativePath>
- </parent>
- <artifactId>config-plugin-parent</artifactId>
- <packaging>pom</packaging>
- <name>${project.artifactId}</name>
-
- <properties>
- <jmxGeneratorPath>${project.build.directory}/generated-sources/config-binding</jmxGeneratorPath>
- </properties>
-
- <build>
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-maven-plugin</artifactId>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator-plugin</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- </dependency>
- </dependencies>
- <executions>
- <execution>
- <id>config</id>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
- <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
- <additionalConfiguration>
- <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
- </additionalConfiguration>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
-</project>
+++ /dev/null
-target
-.classpath
-.settings
+++ /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>config-subsystem</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>config-util</artifactId>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
-
- <dependencies>
- <!-- compile dependencies -->
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-api</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-model-api</artifactId>
- </dependency>
- <!-- test dependencies -->
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
- <dependency>
- <groupId>xmlunit</groupId>
- <artifactId>xmlunit</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <!-- test jar -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- <phase>package</phase>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Export-Package>org.opendaylight.controller.config.util.*</Export-Package>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-public class AttributeEntry {
- private final String key;
- private final String description;
- private final Object value;
- private final String type;
- private final boolean rw;
-
- public AttributeEntry(final String key, final String description, final Object value,
- final String type, final boolean rw) {
- this.key = key;
- this.description = description;
- this.value = value;
- this.type = type;
- this.rw = rw;
- }
-
- public String getKey() {
- return key;
- }
-
- public String getDescription() {
- return description;
- }
-
- public Object getValue() {
- return value;
- }
-
- public String getType() {
- return type;
- }
-
- public boolean isRw() {
- return rw;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.util;
-
-import javax.management.ObjectName;
-
-public interface BeanReader {
- Object getAttributeCurrentValue(ObjectName on, String attributeName);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.util;
-
-public class CloseableUtil {
-
- private CloseableUtil() {
- }
-
- public static void closeAll(final Iterable<? extends AutoCloseable> autoCloseables) throws Exception {
- Exception lastException = null;
- for (AutoCloseable autoCloseable : autoCloseables) {
- try {
- autoCloseable.close();
- } catch (final Exception e) {
- if (lastException == null) {
- lastException = e;
- } else {
- lastException.addSuppressed(e);
- }
- }
- }
- if (lastException != null) {
- throw lastException;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
-
-public interface ConfigRegistryClient extends ConfigRegistryMXBean, BeanReader {
-
- ConfigTransactionClient createTransaction();
-
- ConfigTransactionClient getConfigTransactionClient(String transactionName);
-
- ConfigTransactionClient getConfigTransactionClient(ObjectName objectName);
-
- long getVersion();
-
- Object invokeMethod(ObjectName on, String name, Object[] params,
- String[] signature);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.management.AttributeNotFoundException;
-import javax.management.InstanceNotFoundException;
-import javax.management.JMException;
-import javax.management.JMX;
-import javax.management.MBeanException;
-import javax.management.MBeanServer;
-import javax.management.ObjectInstance;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean;
-import org.opendaylight.controller.config.api.jmx.constants.ConfigRegistryConstants;
-
-public class ConfigRegistryJMXClient implements ConfigRegistryClient {
- private final ConfigRegistryMXBean configRegistryMXBeanProxy;
- private final ObjectName configRegistryON;
- private final MBeanServer configMBeanServer;
-
- public ConfigRegistryJMXClient(final MBeanServer configMBeanServer) {
- this(configMBeanServer, OBJECT_NAME);
- }
-
- private ConfigRegistryJMXClient(final MBeanServer configMBeanServer, final ObjectName configRegistryON) {
- this.configMBeanServer = configMBeanServer;
- this.configRegistryON = configRegistryON;
- Set<ObjectInstance> searchResult = configMBeanServer.queryMBeans(configRegistryON, null);
- if (searchResult.size() != 1) {
- throw new IllegalStateException("Config registry not found");
- }
- configRegistryMXBeanProxy = JMX.newMXBeanProxy(configMBeanServer, configRegistryON, ConfigRegistryMXBean.class,
- false);
- }
-
- public static ConfigRegistryJMXClient createWithoutNotifications(final MBeanServer configMBeanServer) {
- return new ConfigRegistryJMXClient(configMBeanServer, ConfigRegistryConstants.OBJECT_NAME_NO_NOTIFICATIONS);
- }
-
- @Override
- public ConfigTransactionJMXClient createTransaction() {
- ObjectName configTransactionControllerON = beginConfig();
- return getConfigTransactionClient(configTransactionControllerON);
- }
-
- @Override
- public ConfigTransactionJMXClient getConfigTransactionClient(
- final String transactionName) {
- ObjectName objectName = ObjectNameUtil
- .createTransactionControllerON(transactionName);
- return getConfigTransactionClient(objectName);
- }
-
- @Override
- public ConfigTransactionJMXClient getConfigTransactionClient(
- final ObjectName objectName) {
- return new ConfigTransactionJMXClient(configRegistryMXBeanProxy, objectName,
- configMBeanServer);
- }
-
- /**
- * Usage of this method indicates error as config JMX uses solely MXBeans.
- * Use {@link #newMXBeanProxy(javax.management.ObjectName, Class)}
- * or {@link JMX#newMBeanProxy(javax.management.MBeanServerConnection, javax.management.ObjectName, Class)}
- * This method will be removed soon.
- */
- @Deprecated
- public <T> T newMBeanProxy(final ObjectName on, final Class<T> clazz) {
- ObjectName onObj = translateServiceRefIfPossible(on, clazz, configMBeanServer);
- return JMX.newMBeanProxy(configMBeanServer, onObj, clazz);
- }
-
- static ObjectName translateServiceRefIfPossible(final ObjectName on, final Class<?> clazz, final MBeanServer configMBeanServer) {
- ObjectName onObj = on;
- if (ObjectNameUtil.isServiceReference(onObj) && !clazz.equals(ServiceReferenceMXBean.class)) {
- ServiceReferenceMXBean proxy = JMX.newMXBeanProxy(configMBeanServer, onObj, ServiceReferenceMXBean.class);
- onObj = proxy.getCurrentImplementation();
- }
- return onObj;
- }
-
-
- public <T> T newMXBeanProxy(final ObjectName on, final Class<T> clazz) {
- return JMX.newMXBeanProxy(configMBeanServer, on, clazz);
- }
-
- @Override
- public ObjectName beginConfig() {
- return configRegistryMXBeanProxy.beginConfig();
- }
-
- @Override
- public CommitStatus commitConfig(final ObjectName transactionControllerON)
- throws ConflictingVersionException, ValidationException {
- return configRegistryMXBeanProxy.commitConfig(transactionControllerON);
- }
-
- @Override
- public List<ObjectName> getOpenConfigs() {
- return configRegistryMXBeanProxy.getOpenConfigs();
- }
-
- @Override
- public long getVersion() {
- try {
- return (Long) configMBeanServer.getAttribute(configRegistryON,
- "Version");
- } catch (final JMException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public Set<String> getAvailableModuleNames() {
- return configRegistryMXBeanProxy.getAvailableModuleNames();
- }
-
- @Override
- public boolean isHealthy() {
- return configRegistryMXBeanProxy.isHealthy();
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans() {
- return configRegistryMXBeanProxy.lookupConfigBeans();
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName) {
- return configRegistryMXBeanProxy.lookupConfigBeans(moduleName);
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName,
- final String instanceName) {
- return configRegistryMXBeanProxy.lookupConfigBeans(moduleName, instanceName);
- }
-
- @Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- return configRegistryMXBeanProxy.lookupConfigBean(moduleName, instanceName);
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans() {
- return configRegistryMXBeanProxy.lookupRuntimeBeans();
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans(final String ifcName,
- final String instanceName) {
- return configRegistryMXBeanProxy.lookupRuntimeBeans(ifcName, instanceName);
- }
-
- @Override
- public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
- configRegistryMXBeanProxy.checkConfigBeanExists(objectName);
- }
-
- @Override
- public ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
- return configRegistryMXBeanProxy.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
- }
-
- @Override
- public Map<String, Map<String, ObjectName>> getServiceMapping() {
- return configRegistryMXBeanProxy.getServiceMapping();
- }
-
- @Override
- public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
- return configRegistryMXBeanProxy.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
- }
-
- @Override
- public Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
- return configRegistryMXBeanProxy.lookupServiceInterfaceNames(objectName);
- }
-
- @Override
- public String getServiceInterfaceName(final String namespace, final String localName) {
- return configRegistryMXBeanProxy.getServiceInterfaceName(namespace, localName);
- }
-
- @Override
- public Object invokeMethod(final ObjectName on, final String name, final Object[] params,
- final String[] signature) {
- try {
- return configMBeanServer.invoke(on, name, params, signature);
- } catch (InstanceNotFoundException | ReflectionException
- | MBeanException e) {
- throw new RuntimeException("Unable to invoke operation " + name
- + " on " + on + " with attributes "
- + Arrays.toString(params) + " and signature "
- + Arrays.toString(signature), e);
- }
- }
-
- @Override
- public Object getAttributeCurrentValue(final ObjectName on, final String attributeName) {
- try {
- return configMBeanServer.getAttribute(on, attributeName);
- } catch (AttributeNotFoundException | InstanceNotFoundException
- | MBeanException | ReflectionException e) {
- throw new RuntimeException("Unable to get attribute "
- + attributeName + " for " + on + ". Available beans: " + lookupConfigBeans(), e);
- }
- }
-
- @Override
- public Set<String> getAvailableModuleFactoryQNames() {
- return configRegistryMXBeanProxy.getAvailableModuleFactoryQNames();
- }
-
- @Override
- public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
- return configRegistryMXBeanProxy.getServiceReference(serviceInterfaceQName, refName);
- }
-
- @Override
- public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
- configRegistryMXBeanProxy.checkServiceReferenceExists(objectName);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-import javax.management.Attribute;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean;
-
-public interface ConfigTransactionClient extends
- ConfigTransactionControllerMXBean, BeanReader {
-
- CommitStatus commit() throws ConflictingVersionException,
- ValidationException;
-
- void assertVersion(int expectedParentVersion, int expectedCurrentVersion);
-
- long getParentVersion();
-
- long getVersion();
-
- ObjectName getObjectName();
-
- void validateBean(ObjectName configBeanON) throws ValidationException;
-
- @Deprecated
- /**
- * Use {@link #destroyModule(String, String)}
- */
- void destroyConfigBean(String moduleName, String instanceName) throws InstanceNotFoundException;
-
- void destroyModule(String moduleName, String instanceName) throws InstanceNotFoundException;
-
- void setAttribute(ObjectName on, String jmxName, Attribute attribute);
-
- /*
- * Get the attribute named jmxName from the Object with ObjectName on
- *
- * @param on - ObjectName of the Object from which the attribute should be read
- * @param jmxName - name of the attribute to be read
- *
- * @return Object of Object on with attribute name jmxName
- */
- Attribute getAttribute(ObjectName on, String jmxName);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-import java.util.Map;
-import java.util.Set;
-import javax.management.Attribute;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.JMException;
-import javax.management.JMX;
-import javax.management.MBeanException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
-import org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-public class ConfigTransactionJMXClient implements ConfigTransactionClient {
- private final ConfigRegistryMXBean configRegistryMXBeanProxy;
- private final ObjectName configTransactionControllerON;
- private final ConfigTransactionControllerMXBean configTransactionControllerMXBeanProxy;
- private final MBeanServer configMBeanServer;
-
- public ConfigTransactionJMXClient(
- final ConfigRegistryMXBean configRegistryMXBeanProxy,
- final ObjectName configTransactionControllerON,
- final MBeanServer configMBeanServer) {
- this.configMBeanServer = configMBeanServer;
- this.configRegistryMXBeanProxy = configRegistryMXBeanProxy;
- this.configTransactionControllerON = configTransactionControllerON;
- this.configTransactionControllerMXBeanProxy = JMX.newMXBeanProxy(configMBeanServer,
- configTransactionControllerON,
- ConfigTransactionControllerMXBean.class);
- }
-
- public <T> T newMXBeanProxy(final ObjectName on, final Class<T> clazz) {
- ObjectName onName = on;
- // if on is without transaction, add it. Reason is that when using getters on MXBeans the transaction name is stripped
- onName = ObjectNameUtil.withTransactionName(onName, getTransactionName());
- // if this is service reference and user requests for implementation, look it up
- onName = ConfigRegistryJMXClient.translateServiceRefIfPossible(onName, clazz, configMBeanServer);
- onName = ObjectNameUtil.withTransactionName(onName, getTransactionName());
- return JMX.newMXBeanProxy(configMBeanServer, onName, clazz);
- }
-
- /**
- * Usage of this method indicates error as config JMX uses solely MXBeans.
- * Use {@link #newMXBeanProxy(javax.management.ObjectName, Class)}
- * or {@link JMX#newMBeanProxy(javax.management.MBeanServerConnection, javax.management.ObjectName, Class)}
- * This method will be removed soon.
- */
- @Deprecated
- public <T> T newMBeanProxy(final ObjectName on, final Class<T> clazz) {
- return JMX.newMBeanProxy(configMBeanServer, on, clazz);
- }
-
- @Override
- public CommitStatus commit() throws ConflictingVersionException,
- ValidationException {
- return configRegistryMXBeanProxy
- .commitConfig(configTransactionControllerON);
- }
-
- @Override
- public void assertVersion(final int expectedParentVersion,
- final int expectedCurrentVersion) {
- if (expectedParentVersion != getParentVersion()) {
- throw new IllegalStateException();
- }
- if (expectedCurrentVersion != getVersion()) {
- throw new IllegalStateException();
- }
- }
-
- // proxy around ConfigManagerMXBean
- @Override
- public ObjectName createModule(final String moduleName, final String instanceName)
- throws InstanceAlreadyExistsException {
- return configTransactionControllerMXBeanProxy.createModule(moduleName, instanceName);
- }
-
- @Override
- public void reCreateModule(final ObjectName objectName) throws InstanceNotFoundException {
- configTransactionControllerMXBeanProxy.reCreateModule(objectName);
- }
-
- @Override
- public void destroyModule(final ObjectName objectName)
- throws InstanceNotFoundException {
- configTransactionControllerMXBeanProxy.destroyModule(objectName);
- }
-
- @Override
- @Deprecated
- /**
- * {@inheritDoc}
- */
- public void destroyConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- destroyModule(ObjectNameUtil.createTransactionModuleON(
- getTransactionName(), moduleName, instanceName));
- }
-
- @Override
- public void destroyModule(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- destroyModule(ObjectNameUtil.createTransactionModuleON(
- getTransactionName(), moduleName, instanceName));
- }
-
- @Override
- public void abortConfig() {
- configTransactionControllerMXBeanProxy.abortConfig();
- }
-
- @Override
- public void validateConfig() throws ValidationException {
- configTransactionControllerMXBeanProxy.validateConfig();
- }
-
- @Override
- public long getParentVersion() {
- try {
- return (Long) configMBeanServer.getAttribute(
- configTransactionControllerON, "ParentVersion");
- } catch (final JMException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public long getVersion() {
- try {
- return (Long) configMBeanServer.getAttribute(
- configTransactionControllerON, "Version");
- } catch (final JMException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public String getTransactionName() {
- return configTransactionControllerMXBeanProxy.getTransactionName();
- }
-
- @Override
- public Set<String> getAvailableModuleNames() {
- return configTransactionControllerMXBeanProxy.getAvailableModuleNames();
- }
-
- @Override
- public ObjectName getObjectName() {
- return configTransactionControllerON;
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans() {
- return configTransactionControllerMXBeanProxy.lookupConfigBeans();
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName) {
- return configTransactionControllerMXBeanProxy.lookupConfigBeans(moduleName);
- }
-
- @Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- return configTransactionControllerMXBeanProxy.lookupConfigBean(moduleName, instanceName);
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName,
- final String instanceName) {
- return configTransactionControllerMXBeanProxy
- .lookupConfigBeans(moduleName, instanceName);
- }
-
- @Override
- public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
- configTransactionControllerMXBeanProxy.checkConfigBeanExists(objectName);
- }
-
- @Override
- public ObjectName saveServiceReference(final String serviceInterfaceName, final String refName, final ObjectName moduleON) throws InstanceNotFoundException {
- return configTransactionControllerMXBeanProxy.saveServiceReference(serviceInterfaceName,refName, moduleON);
- }
-
- @Override
- public void removeServiceReference(final String serviceInterfaceName, final String refName) throws InstanceNotFoundException{
- configTransactionControllerMXBeanProxy.removeServiceReference(serviceInterfaceName, refName);
- }
-
- @Override
- public void removeAllServiceReferences() {
- configTransactionControllerMXBeanProxy.removeAllServiceReferences();
- }
-
- @Override
- public ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
- return configTransactionControllerMXBeanProxy.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
- }
-
- @Override
- public Map<String, Map<String, ObjectName>> getServiceMapping() {
- return configTransactionControllerMXBeanProxy.getServiceMapping();
- }
-
- @Override
- public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
- return configTransactionControllerMXBeanProxy.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
- }
-
- @Override
- public Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
- return configTransactionControllerMXBeanProxy.lookupServiceInterfaceNames(objectName);
- }
-
- @Override
- public String getServiceInterfaceName(final String namespace, final String localName) {
- return configTransactionControllerMXBeanProxy.getServiceInterfaceName(namespace, localName);
- }
-
- @Override
- public boolean removeServiceReferences(final ObjectName objectName) throws InstanceNotFoundException {
- return configTransactionControllerMXBeanProxy.removeServiceReferences(objectName);
- }
-
- @Override
- public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
- return configTransactionControllerMXBeanProxy.getServiceReference(serviceInterfaceQName, refName);
- }
-
- @Override
- public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
- configTransactionControllerMXBeanProxy.checkServiceReferenceExists(objectName);
- }
-
- @Override
- public Attribute getAttribute(final ObjectName on, final String attrName) {
- if (ObjectNameUtil.getTransactionName(on) == null) {
- throw new IllegalArgumentException("Not in transaction instance "
- + on + ", no transaction name present");
- }
-
- try {
- return new Attribute(attrName, configMBeanServer.getAttribute(on,attrName));
- } catch (final JMException e) {
- throw new IllegalStateException("Unable to get attribute "
- + attrName + " for " + on, e);
- }
- }
-
- @Override
- public Object getAttributeCurrentValue(final ObjectName on, final String attrName) {
- return getAttribute(on, attrName).getValue();
- }
-
- @Override
- public void validateBean(final ObjectName configBeanON)
- throws ValidationException {
- try {
- configMBeanServer.invoke(configBeanON, "validate", null, null);
- } catch (final MBeanException e) {
- Exception targetException = e.getTargetException();
- if (targetException instanceof ValidationException){
- throw (ValidationException) targetException;
- } else {
- throw new RuntimeException(e);
- }
- } catch (final JMException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public void setAttribute(final ObjectName on, final String attrName, final Attribute attribute) {
- if (ObjectNameUtil.getTransactionName(on) == null) {
- throw new IllegalArgumentException("Not in transaction instance "
- + on + ", no transaction name present");
- }
-
- try {
- configMBeanServer.setAttribute(on, attribute);
- } catch (final JMException e) {
- throw new IllegalStateException("Unable to set attribute "
- + attrName + " for " + on, e);
- }
- }
-
- @Override
- public Set<String> getAvailableModuleFactoryQNames() {
- return configTransactionControllerMXBeanProxy.getAvailableModuleFactoryQNames();
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans() {
- return configTransactionControllerMXBeanProxy.lookupRuntimeBeans();
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
- return configTransactionControllerMXBeanProxy.lookupRuntimeBeans(moduleName, instanceName);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.util.capability;
-
-import com.google.common.base.Optional;
-import java.util.Collection;
-import java.util.Collections;
-
-/**
- * Capability representing a basic, one-line, string based capability
- */
-public class BasicCapability implements Capability {
-
- private final String capability;
-
- public BasicCapability(final String capability) {
- this.capability = capability;
- }
-
- @Override
- public String getCapabilityUri() {
- return capability;
- }
-
- @Override
- public Optional<String> getModuleNamespace() {
- return Optional.absent();
- }
-
- @Override
- public Optional<String> getModuleName() {
- return Optional.absent();
- }
-
- @Override
- public Optional<String> getRevision() {
- return Optional.absent();
- }
-
- @Override
- public Optional<String> getCapabilitySchema() {
- return Optional.absent();
- }
-
- @Override
- public Collection<String> getLocation() {
- return Collections.emptyList();
- }
-
- @Override
- public String toString() {
- return capability;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.util.capability;
-
-import com.google.common.base.Optional;
-import java.util.Collection;
-
-/**
- * Contains capability URI announced by server hello message and optionally its
- * corresponding yang schema that can be retrieved by get-schema rpc.
- */
-// TODO this should be placed into API bundle for netconf
-public interface Capability {
-
- String getCapabilityUri();
-
- Optional<String> getModuleNamespace();
-
- Optional<String> getModuleName();
-
- Optional<String> getRevision();
-
- Optional<String> getCapabilitySchema();
-
- Collection<String> getLocation();
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.util.capability;
-
-import java.util.Set;
-
-public interface ModuleListener {
-
- void onCapabilitiesChanged(Set<Capability> added, Set<Capability> removed);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.util.capability;
-
-import com.google.common.base.Optional;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-/**
- * Yang model representing capability.
- */
-public final class YangModuleCapability extends BasicCapability {
-
- private final String content;
- private final String revision;
- private final String moduleName;
- private final String moduleNamespace;
-
- public YangModuleCapability(final Module module, final String moduleContent) {
- super(toCapabilityURI(module));
- this.content = moduleContent;
- this.moduleName = module.getName();
- this.moduleNamespace = module.getNamespace().toString();
- this.revision = module.getRevision().map(Revision::toString).orElse(null);
- }
-
- @Override
- public Optional<String> getCapabilitySchema() {
- return Optional.of(content);
- }
-
- private static String toCapabilityURI(final Module module) {
- final StringBuilder sb = new StringBuilder();
- sb.append(module.getNamespace()).append("?module=").append(module.getName());
-
- final java.util.Optional<Revision> rev = module.getRevision();
- if (rev.isPresent()) {
- sb.append("&revision=").append(rev.get());
- }
- return sb.toString();
- }
-
- @Override
- public Optional<String> getModuleName() {
- return Optional.of(moduleName);
- }
-
- @Override
- public Optional<String> getModuleNamespace() {
- return Optional.of(moduleNamespace);
- }
-
- @Override
- public Optional<String> getRevision() {
- return Optional.of(revision);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.util.xml;
-
-import static org.opendaylight.controller.config.util.xml.XmlMappingConstants.RPC_REPLY_KEY;
-import static org.opendaylight.controller.config.util.xml.XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
-
-import com.google.common.base.Preconditions;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/**
- * Checked exception to communicate an error that needs to be sent to the
- * netconf client.
- */
-public class DocumentedException extends Exception {
-
- public static final String RPC_ERROR = "rpc-error";
- public static final String ERROR_TYPE = "error-type";
- public static final String ERROR_TAG = "error-tag";
- public static final String ERROR_SEVERITY = "error-severity";
- public static final String ERROR_APP_TAG = "error-app-tag";
- public static final String ERROR_PATH = "error-path";
- public static final String ERROR_MESSAGE = "error-message";
- public static final String ERROR_INFO = "error-info";
-
- private static final long serialVersionUID = 1L;
-
- private static final Logger LOG = LoggerFactory.getLogger(DocumentedException.class);
-
- private static final DocumentBuilderFactory BUILDER_FACTORY;
-
- static {
- BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
- try {
- BUILDER_FACTORY.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
- BUILDER_FACTORY.setFeature("http://xml.org/sax/features/external-general-entities", false);
- BUILDER_FACTORY.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
- BUILDER_FACTORY.setXIncludeAware(false);
- BUILDER_FACTORY.setExpandEntityReferences(false);
- } catch (final ParserConfigurationException e) {
- throw new ExceptionInInitializerError(e);
- }
- BUILDER_FACTORY.setNamespaceAware(true);
- BUILDER_FACTORY.setCoalescing(true);
- BUILDER_FACTORY.setIgnoringElementContentWhitespace(true);
- BUILDER_FACTORY.setIgnoringComments(true);
- }
-
- public enum ErrorType {
- TRANSPORT("transport"),
- RPC("rpc"),
- PROTOCOL("protocol"),
- APPLICATION("application");
-
- private final String typeValue;
-
- ErrorType(final String typeValue) {
- this.typeValue = Preconditions.checkNotNull(typeValue);
- }
-
- public String getTypeValue() {
- return this.typeValue;
- }
-
- /**
- * @deprecated Use {@link #getTypeValue()} instead.
- */
- @Deprecated
- public String getTagValue() {
- return this.typeValue;
- }
-
- public static ErrorType from(final String text) {
- for (ErrorType e : values()) {
- if (e.getTypeValue().equalsIgnoreCase(text)) {
- return e;
- }
- }
-
- return APPLICATION;
- }
- }
-
- public enum ErrorTag {
- ACCESS_DENIED("access-denied"),
- BAD_ATTRIBUTE("bad-attribute"),
- BAD_ELEMENT("bad-element"),
- DATA_EXISTS("data-exists"),
- DATA_MISSING("data-missing"),
- IN_USE("in-use"),
- INVALID_VALUE("invalid-value"),
- LOCK_DENIED("lock-denied"),
- MALFORMED_MESSAGE("malformed-message"),
- MISSING_ATTRIBUTE("missing-attribute"),
- MISSING_ELEMENT("missing-element"),
- OPERATION_FAILED("operation-failed"),
- OPERATION_NOT_SUPPORTED("operation-not-supported"),
- RESOURCE_DENIED("resource-denied"),
- ROLLBCK_FAILED("rollback-failed"),
- TOO_BIG("too-big"),
- UNKNOWN_ATTRIBUTE("unknown-attribute"),
- UNKNOWN_ELEMENT("unknown-element"),
- UNKNOWN_NAMESPACE("unknown-namespace");
-
- private final String tagValue;
-
- ErrorTag(final String tagValue) {
- this.tagValue = tagValue;
- }
-
- public String getTagValue() {
- return this.tagValue;
- }
-
- public static ErrorTag from( final String text ) {
- for( ErrorTag e: values() )
- {
- if( e.getTagValue().equals( text ) ) {
- return e;
- }
- }
-
- return OPERATION_FAILED;
- }
- }
-
- public enum ErrorSeverity {
- ERROR("error"),
- WARNING("warning");
-
- private final String severityValue;
-
- ErrorSeverity(final String severityValue) {
- this.severityValue = Preconditions.checkNotNull(severityValue);
- }
-
- public String getSeverityValue() {
- return this.severityValue;
- }
-
- /**
- * @deprecated Use {@link #getSeverityValue()} instead.
- */
- @Deprecated
- public String getTagValue() {
- return this.severityValue;
- }
-
- public static ErrorSeverity from(final String text) {
- for (ErrorSeverity e : values()) {
- if (e.getSeverityValue().equalsIgnoreCase(text)) {
- return e;
- }
- }
-
- return ERROR;
- }
- }
-
- private final ErrorType errorType;
- private final ErrorTag errorTag;
- private final ErrorSeverity errorSeverity;
- private final Map<String, String> errorInfo;
-
- public DocumentedException(final String message) {
- this(message,
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.INVALID_VALUE,
- DocumentedException.ErrorSeverity.ERROR
- );
- }
-
- public DocumentedException(final String message, final Exception cause) {
- this(message, cause,
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.INVALID_VALUE,
- DocumentedException.ErrorSeverity.ERROR
- );
- }
-
- public DocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity) {
- this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
- }
-
- public DocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
- super(message);
- this.errorType = errorType;
- this.errorTag = errorTag;
- this.errorSeverity = errorSeverity;
- this.errorInfo = errorInfo;
- }
-
- public DocumentedException(final String message, final Exception cause, final ErrorType errorType,
- final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
- this(message, cause, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
- }
-
- public DocumentedException(final String message, final Exception cause, final ErrorType errorType,
- final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
- super(message, cause);
- this.errorType = errorType;
- this.errorTag = errorTag;
- this.errorSeverity = errorSeverity;
- this.errorInfo = errorInfo;
- }
-
- public static <E extends Exception> DocumentedException wrap(final E exception) throws DocumentedException {
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.OPERATION_FAILED.name(), "Exception thrown");
- throw new DocumentedException(exception.getMessage(), exception, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
- ErrorSeverity.ERROR, errorInfo);
- }
- public static DocumentedException wrap(final ValidationException e) throws DocumentedException {
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.OPERATION_FAILED.name(), "Validation failed");
- throw new DocumentedException(e.getMessage(), e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
- ErrorSeverity.ERROR, errorInfo);
- }
-
- public static DocumentedException wrap(final ConflictingVersionException e) throws DocumentedException {
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.OPERATION_FAILED.name(), "Optimistic lock failed");
- throw new DocumentedException(e.getMessage(), e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
- ErrorSeverity.ERROR, errorInfo);
- }
-
- public static DocumentedException fromXMLDocument( final Document fromDoc ) {
-
- ErrorType errorType = ErrorType.APPLICATION;
- ErrorTag errorTag = ErrorTag.OPERATION_FAILED;
- ErrorSeverity errorSeverity = ErrorSeverity.ERROR;
- Map<String, String> errorInfo = null;
- String errorMessage = "";
-
- Node rpcReply = fromDoc.getDocumentElement();
-
- // FIXME: BUG? - we only handle one rpc-error.
-
- NodeList replyChildren = rpcReply.getChildNodes();
- for( int i = 0; i < replyChildren.getLength(); i++ ) {
- Node replyChild = replyChildren.item( i );
- if( RPC_ERROR.equals( replyChild.getNodeName() ) )
- {
- NodeList rpcErrorChildren = replyChild.getChildNodes();
- for( int j = 0; j < rpcErrorChildren.getLength(); j++ )
- {
- Node rpcErrorChild = rpcErrorChildren.item( j );
- if( ERROR_TYPE.equals( rpcErrorChild.getNodeName() ) ) {
- errorType = ErrorType.from(rpcErrorChild.getTextContent());
- }
- else if( ERROR_TAG.equals( rpcErrorChild.getNodeName() ) ) {
- errorTag = ErrorTag.from(rpcErrorChild.getTextContent());
- }
- else if( ERROR_SEVERITY.equals( rpcErrorChild.getNodeName() ) ) {
- errorSeverity = ErrorSeverity.from(rpcErrorChild.getTextContent());
- }
- else if( ERROR_MESSAGE.equals( rpcErrorChild.getNodeName() ) ) {
- errorMessage = rpcErrorChild.getTextContent();
- }
- else if( ERROR_INFO.equals( rpcErrorChild.getNodeName() ) ) {
- errorInfo = parseErrorInfo( rpcErrorChild );
- }
- }
-
- break;
- }
- }
-
- return new DocumentedException( errorMessage, errorType, errorTag, errorSeverity, errorInfo );
- }
-
- private static Map<String, String> parseErrorInfo( final Node node ) {
- Map<String, String> infoMap = new HashMap<>();
- NodeList children = node.getChildNodes();
- for( int i = 0; i < children.getLength(); i++ ) {
- Node child = children.item( i );
- if( child.getNodeType() == Node.ELEMENT_NODE ) {
- infoMap.put( child.getNodeName(), child.getTextContent() );
- }
- }
-
- return infoMap;
- }
-
- public ErrorType getErrorType() {
- return this.errorType;
- }
-
- public ErrorTag getErrorTag() {
- return this.errorTag;
- }
-
- public ErrorSeverity getErrorSeverity() {
- return this.errorSeverity;
- }
-
- public Map<String, String> getErrorInfo() {
- return this.errorInfo;
- }
-
- public Document toXMLDocument() {
- Document doc = null;
- try {
- doc = BUILDER_FACTORY.newDocumentBuilder().newDocument();
-
- Node rpcReply = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, RPC_REPLY_KEY);
- doc.appendChild( rpcReply );
-
- Node rpcError = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, RPC_ERROR );
- rpcReply.appendChild( rpcError );
-
- rpcError.appendChild( createTextNode( doc, ERROR_TYPE, getErrorType().getTypeValue() ) );
- rpcError.appendChild( createTextNode( doc, ERROR_TAG, getErrorTag().getTagValue() ) );
- rpcError.appendChild( createTextNode( doc, ERROR_SEVERITY, getErrorSeverity().getSeverityValue() ) );
- rpcError.appendChild( createTextNode( doc, ERROR_MESSAGE, getLocalizedMessage() ) );
-
- Map<String, String> errorInfoMap = getErrorInfo();
- if( errorInfoMap != null && !errorInfoMap.isEmpty() ) {
- /*
- * <error-info>
- * <bad-attribute>message-id</bad-attribute>
- * <bad-element>rpc</bad-element>
- * </error-info>
- */
-
- Node errorInfoNode = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, ERROR_INFO );
- errorInfoNode.setPrefix( rpcReply.getPrefix() );
- rpcError.appendChild( errorInfoNode );
-
- for ( Entry<String, String> entry : errorInfoMap.entrySet() ) {
- errorInfoNode.appendChild( createTextNode( doc, entry.getKey(), entry.getValue() ) );
- }
- }
- }
- catch( final ParserConfigurationException e ) {
- // this shouldn't happen
- LOG.error("Error outputting to XML document", e);
- }
-
- return doc;
- }
-
- private Node createTextNode( final Document doc, final String tag, final String textContent ) {
- Node node = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, tag );
- node.setTextContent( textContent );
- return node;
- }
-
- @Override
- public String toString() {
- return "NetconfDocumentedException{" + "message=" + getMessage() + ", errorType=" + this.errorType
- + ", errorTag=" + this.errorTag + ", errorSeverity=" + this.errorSeverity + ", errorInfo="
- + this.errorInfo + '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util.xml;
-
-import java.util.Collections;
-import java.util.Map;
-
-public class MissingNameSpaceException extends DocumentedException {
- private static final long serialVersionUID = 1L;
-
- public MissingNameSpaceException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
- final DocumentedException.ErrorSeverity errorSeverity) {
- this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
- }
-
- public MissingNameSpaceException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
- final DocumentedException.ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
- super(message,errorType,errorTag,errorSeverity,errorInfo);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util.xml;
-
-import java.util.Collections;
-import java.util.Map;
-
-public class UnexpectedElementException extends DocumentedException {
- private static final long serialVersionUID = 1L;
-
- public UnexpectedElementException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
- final DocumentedException.ErrorSeverity errorSeverity) {
- this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
- }
-
- public UnexpectedElementException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
- final DocumentedException.ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
- super(message,errorType,errorTag,errorSeverity,errorInfo);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util.xml;
-
-import java.util.Collections;
-import java.util.Map;
-
-public class UnexpectedNamespaceException extends DocumentedException {
- private static final long serialVersionUID = 1L;
-
- public UnexpectedNamespaceException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
- final DocumentedException.ErrorSeverity errorSeverity) {
- this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
- }
-
- public UnexpectedNamespaceException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
- final DocumentedException.ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
- super(message,errorType,errorTag,errorSeverity,errorInfo);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.util.xml;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Strings;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-import org.xml.sax.SAXException;
-
-public final class XmlElement {
-
- public static final String DEFAULT_NAMESPACE_PREFIX = "";
-
- private final Element element;
- private static final Logger LOG = LoggerFactory.getLogger(XmlElement.class);
-
- private XmlElement(final Element element) {
- this.element = element;
- }
-
- public static XmlElement fromDomElement(final Element e) {
- return new XmlElement(e);
- }
-
- public static XmlElement fromDomDocument(final Document xml) {
- return new XmlElement(xml.getDocumentElement());
- }
-
- public static XmlElement fromString(final String s) throws DocumentedException {
- try {
- return new XmlElement(XmlUtil.readXmlToElement(s));
- } catch (IOException | SAXException e) {
- throw DocumentedException.wrap(e);
- }
- }
-
- public static XmlElement fromDomElementWithExpected(final Element element, final String expectedName) throws DocumentedException {
- XmlElement xmlElement = XmlElement.fromDomElement(element);
- xmlElement.checkName(expectedName);
- return xmlElement;
- }
-
- public static XmlElement fromDomElementWithExpected(final Element element, final String expectedName, final String expectedNamespace) throws DocumentedException {
- XmlElement xmlElement = XmlElement.fromDomElementWithExpected(element, expectedName);
- xmlElement.checkNamespace(expectedNamespace);
- return xmlElement;
- }
-
- private Map<String, String> extractNamespaces() throws DocumentedException {
- Map<String, String> namespaces = new HashMap<>();
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0; i < attributes.getLength(); i++) {
- Node attribute = attributes.item(i);
- String attribKey = attribute.getNodeName();
- if (attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
- String prefix;
- if (attribKey.equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
- prefix = DEFAULT_NAMESPACE_PREFIX;
- } else {
- if (!attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY + ":")){
- throw new DocumentedException("Attribute doesn't start with :",
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.INVALID_VALUE,
- DocumentedException.ErrorSeverity.ERROR);
- }
- prefix = attribKey.substring(XmlUtil.XMLNS_ATTRIBUTE_KEY.length() + 1);
- }
- namespaces.put(prefix, attribute.getNodeValue());
- }
- }
-
- // namespace does not have to be defined on this element but inherited
- if(!namespaces.containsKey(DEFAULT_NAMESPACE_PREFIX)) {
- Optional<String> namespaceOptionally = getNamespaceOptionally();
- if(namespaceOptionally.isPresent()) {
- namespaces.put(DEFAULT_NAMESPACE_PREFIX, namespaceOptionally.get());
- }
- }
-
- return namespaces;
- }
-
- public void checkName(final String expectedName) throws UnexpectedElementException {
- if (!getName().equals(expectedName)){
- throw new UnexpectedElementException(String.format("Expected %s xml element but was %s", expectedName,
- getName()),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
-
- public void checkNamespaceAttribute(final String expectedNamespace) throws UnexpectedNamespaceException, MissingNameSpaceException {
- if (!getNamespaceAttribute().equals(expectedNamespace))
- {
- throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s should be %s",
- getNamespaceAttribute(),
- expectedNamespace),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
-
- public void checkNamespace(final String expectedNamespace) throws UnexpectedNamespaceException, MissingNameSpaceException {
- if (!getNamespace().equals(expectedNamespace))
- {
- throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s should be %s",
- getNamespace(),
- expectedNamespace),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
-
- public String getName() {
- final String localName = element.getLocalName();
- if (!Strings.isNullOrEmpty(localName)){
- return localName;
- }
- return element.getTagName();
- }
-
- public String getAttribute(final String attributeName) {
- return element.getAttribute(attributeName);
- }
-
- public String getAttribute(final String attributeName, final String namespace) {
- return element.getAttributeNS(namespace, attributeName);
- }
-
- public NodeList getElementsByTagName(final String name) {
- return element.getElementsByTagName(name);
- }
-
- public void appendChild(final Element element) {
- this.element.appendChild(element);
- }
-
- public Element getDomElement() {
- return element;
- }
-
- public Map<String, Attr> getAttributes() {
-
- Map<String, Attr> mappedAttributes = Maps.newHashMap();
-
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0; i < attributes.getLength(); i++) {
- Attr attr = (Attr) attributes.item(i);
- mappedAttributes.put(attr.getNodeName(), attr);
- }
-
- return mappedAttributes;
- }
-
- /**
- * Non recursive
- */
- private List<XmlElement> getChildElementsInternal(final ElementFilteringStrategy strat) {
- NodeList childNodes = element.getChildNodes();
- final List<XmlElement> result = new ArrayList<>();
- for (int i = 0; i < childNodes.getLength(); i++) {
- Node item = childNodes.item(i);
- if (!(item instanceof Element)) {
- continue;
- }
- if (strat.accept((Element) item)) {
- result.add(new XmlElement((Element) item));
- }
- }
-
- return result;
- }
-
- public List<XmlElement> getChildElements() {
- return getChildElementsInternal(e -> true);
- }
-
- public List<XmlElement> getChildElementsWithinNamespace(final String childName, final String namespace) {
- return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace),
- xmlElement -> xmlElement.getName().equals(childName)));
- }
-
- public List<XmlElement> getChildElementsWithinNamespace(final String namespace) {
- return getChildElementsInternal(e -> {
- try {
- return XmlElement.fromDomElement(e).getNamespace().equals(namespace);
- } catch (final MissingNameSpaceException e1) {
- return false;
- }
- });
- }
-
- /**
- *
- * @param tagName tag name without prefix
- * @return List of child elements
- */
- public List<XmlElement> getChildElements(final String tagName) {
- return getChildElementsInternal(e -> {
- // localName returns pure localName without prefix
- return e.getLocalName().equals(tagName);
- });
- }
-
- public XmlElement getOnlyChildElement(final String childName) throws DocumentedException {
- List<XmlElement> nameElements = getChildElements(childName);
- if (nameElements.size() != 1){
- throw new DocumentedException("One element " + childName + " expected in " + toString(),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.INVALID_VALUE,
- DocumentedException.ErrorSeverity.ERROR);
- }
- return nameElements.get(0);
- }
-
- public Optional<XmlElement> getOnlyChildElementOptionally(final String childName) {
- List<XmlElement> nameElements = getChildElements(childName);
- if (nameElements.size() != 1) {
- return Optional.absent();
- }
- return Optional.of(nameElements.get(0));
- }
-
- public Optional<XmlElement> getOnlyChildElementOptionally(final String childName, final String namespace) {
- List<XmlElement> children = getChildElementsWithinNamespace(namespace);
- children = Lists.newArrayList(Collections2.filter(children,
- xmlElement -> xmlElement.getName().equals(childName)));
- if (children.size() != 1){
- return Optional.absent();
- }
- return Optional.of(children.get(0));
- }
-
- public XmlElement getOnlyChildElementWithSameNamespace(final String childName) throws DocumentedException {
- return getOnlyChildElement(childName, getNamespace());
- }
-
- public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally(final String childName) {
- Optional<String> namespace = getNamespaceOptionally();
- if (namespace.isPresent()) {
- List<XmlElement> children = getChildElementsWithinNamespace(namespace.get());
- children = Lists.newArrayList(Collections2.filter(children,
- xmlElement -> xmlElement.getName().equals(childName)));
- if (children.size() != 1){
- return Optional.absent();
- }
- return Optional.of(children.get(0));
- }
- return Optional.absent();
- }
-
- public XmlElement getOnlyChildElementWithSameNamespace() throws DocumentedException {
- XmlElement childElement = getOnlyChildElement();
- childElement.checkNamespace(getNamespace());
- return childElement;
- }
-
- public Optional<XmlElement> getOnlyChildElementWithSameNamespaceOptionally() {
- Optional<XmlElement> child = getOnlyChildElementOptionally();
- if (child.isPresent()
- && child.get().getNamespaceOptionally().isPresent()
- && getNamespaceOptionally().isPresent()
- && getNamespaceOptionally().get().equals(child.get().getNamespaceOptionally().get())) {
- return child;
- }
- return Optional.absent();
- }
-
- public XmlElement getOnlyChildElement(final String childName, final String namespace) throws DocumentedException {
- List<XmlElement> children = getChildElementsWithinNamespace(namespace);
- children = Lists.newArrayList(Collections2.filter(children,
- xmlElement -> xmlElement.getName().equals(childName)));
- if (children.size() != 1){
- throw new DocumentedException(String.format("One element %s:%s expected in %s but was %s", namespace,
- childName, toString(), children.size()),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.INVALID_VALUE,
- DocumentedException.ErrorSeverity.ERROR);
- }
-
- return children.get(0);
- }
-
- public XmlElement getOnlyChildElement() throws DocumentedException {
- List<XmlElement> children = getChildElements();
- if (children.size() != 1){
- throw new DocumentedException(String.format( "One element expected in %s but was %s", toString(),
- children.size()),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.INVALID_VALUE,
- DocumentedException.ErrorSeverity.ERROR);
- }
- return children.get(0);
- }
-
- public Optional<XmlElement> getOnlyChildElementOptionally() {
- List<XmlElement> children = getChildElements();
- if (children.size() != 1) {
- return Optional.absent();
- }
- return Optional.of(children.get(0));
- }
-
- public String getTextContent() throws DocumentedException {
- NodeList childNodes = element.getChildNodes();
- if (childNodes.getLength() == 0) {
- return DEFAULT_NAMESPACE_PREFIX;
- }
- for(int i = 0; i < childNodes.getLength(); i++) {
- Node textChild = childNodes.item(i);
- if (textChild instanceof Text) {
- String content = textChild.getTextContent();
- return content.trim();
- }
- }
- throw new DocumentedException(getName() + " should contain text.",
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.INVALID_VALUE,
- DocumentedException.ErrorSeverity.ERROR
- );
- }
-
- public Optional<String> getOnlyTextContentOptionally() {
- // only return text content if this node has exactly one Text child node
- if (element.getChildNodes().getLength() == 1) {
- Node item = element.getChildNodes().item(0);
- if (item instanceof Text) {
- return Optional.of(((Text) item).getWholeText());
- }
- }
- return Optional.absent();
- }
-
- public String getNamespaceAttribute() throws MissingNameSpaceException {
- String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
- if (attribute == null || attribute.equals(DEFAULT_NAMESPACE_PREFIX)){
- throw new MissingNameSpaceException(String.format("Element %s must specify namespace",
- toString()),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- return attribute;
- }
-
- public Optional<String> getNamespaceAttributeOptionally(){
- String attribute = element.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY);
- if (attribute == null || attribute.equals(DEFAULT_NAMESPACE_PREFIX)){
- return Optional.absent();
- }
- return Optional.of(attribute);
- }
-
- public Optional<String> getNamespaceOptionally() {
- String namespaceURI = element.getNamespaceURI();
- if (Strings.isNullOrEmpty(namespaceURI)) {
- return Optional.absent();
- } else {
- return Optional.of(namespaceURI);
- }
- }
-
- public String getNamespace() throws MissingNameSpaceException {
- Optional<String> namespaceURI = getNamespaceOptionally();
- if (!namespaceURI.isPresent()){
- throw new MissingNameSpaceException(String.format("No namespace defined for %s", this),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
- DocumentedException.ErrorSeverity.ERROR);
- }
- return namespaceURI.get();
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder("XmlElement{");
- sb.append("name='").append(getName()).append('\'');
- if (element.getNamespaceURI() != null) {
- try {
- sb.append(", namespace='").append(getNamespace()).append('\'');
- } catch (final MissingNameSpaceException e) {
- LOG.trace("Missing namespace for element.");
- }
- }
- sb.append('}');
- return sb.toString();
- }
-
- /**
- * Search for element's attributes defining namespaces. Look for the one
- * namespace that matches prefix of element's text content. E.g.
- *
- * <pre>
- * <type
- * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">th-java:threadfactory-naming</type>
- * </pre>
- *
- * returns {"th-java","urn:.."}. If no prefix is matched, then default
- * namespace is returned with empty string as key. If no default namespace
- * is found value will be null.
- */
- public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() throws DocumentedException {
- Map<String, String> namespaces = extractNamespaces();
- String textContent = getTextContent();
- int indexOfColon = textContent.indexOf(':');
- String prefix;
- if (indexOfColon > -1) {
- prefix = textContent.substring(0, indexOfColon);
- } else {
- prefix = DEFAULT_NAMESPACE_PREFIX;
- }
- if (!namespaces.containsKey(prefix)) {
- throw new IllegalArgumentException("Cannot find namespace for " + XmlUtil.toString(element) + ". Prefix from content is "
- + prefix + ". Found namespaces " + namespaces);
- }
- return Maps.immutableEntry(prefix, namespaces.get(prefix));
- }
-
- public List<XmlElement> getChildElementsWithSameNamespace(final String childName) throws MissingNameSpaceException {
- List<XmlElement> children = getChildElementsWithinNamespace(getNamespace());
- return Lists.newArrayList(Collections2.filter(children, xmlElement -> xmlElement.getName().equals(childName)));
- }
-
- public void checkUnrecognisedElements(final List<XmlElement> recognisedElements,
- final XmlElement... additionalRecognisedElements) throws DocumentedException {
- List<XmlElement> childElements = getChildElements();
- childElements.removeAll(recognisedElements);
- for (XmlElement additionalRecognisedElement : additionalRecognisedElements) {
- childElements.remove(additionalRecognisedElement);
- }
- if (!childElements.isEmpty()){
- throw new DocumentedException(String.format("Unrecognised elements %s in %s", childElements, this),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.INVALID_VALUE,
- DocumentedException.ErrorSeverity.ERROR);
- }
- }
-
- public void checkUnrecognisedElements(final XmlElement... additionalRecognisedElements) throws DocumentedException {
- checkUnrecognisedElements(Collections.<XmlElement>emptyList(), additionalRecognisedElements);
- }
-
- @Override
- public boolean equals(final Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- XmlElement that = (XmlElement) o;
-
- return element.isEqualNode(that.element);
-
- }
-
- @Override
- public int hashCode() {
- return element.hashCode();
- }
-
- public boolean hasNamespace() {
- return getNamespaceAttributeOptionally().isPresent() || getNamespaceOptionally().isPresent();
- }
-
- private interface ElementFilteringStrategy {
- boolean accept(Element e);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util.xml;
-
-public final class XmlMappingConstants {
-
- public static final String RPC_REPLY_KEY = "rpc-reply";
- public static final String TYPE_KEY = "type";
- public static final String MODULE_KEY = "module";
- public static final String INSTANCE_KEY = "instance";
- public static final String OPERATION_ATTR_KEY = "operation";
- public static final String SERVICES_KEY = "services";
- public static final String CONFIG_KEY = "config";
- public static final String MODULES_KEY = "modules";
- public static final String DATA_KEY = "data";
- public static final String NAME_KEY = "name";
-
- public static final String PREFIX = "prefix";
-
- public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 = "urn:ietf:params:xml:ns:netconf:base:1.0";
- public static final String URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG = "urn:opendaylight:params:xml:ns:yang:controller:config";
-
- private XmlMappingConstants() {
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.util.xml;
-
-import com.google.common.base.Optional;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringWriter;
-import java.nio.charset.StandardCharsets;
-import javax.xml.XMLConstants;
-import javax.xml.namespace.QName;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Source;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.TransformerFactoryConfigurationError;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.validation.Schema;
-import javax.xml.validation.SchemaFactory;
-import javax.xml.xpath.XPathExpression;
-import javax.xml.xpath.XPathExpressionException;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.xml.sax.SAXException;
-
-public final class XmlUtil {
-
- public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
- public static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
- private static final DocumentBuilderFactory BUILDER_FACTORY;
- private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
- private static final SchemaFactory SCHEMA_FACTORY = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
-
- static {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- try {
- factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
- factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
- 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 (final ParserConfigurationException e) {
- throw new ExceptionInInitializerError(e);
- }
- factory.setNamespaceAware(true);
- factory.setCoalescing(true);
- factory.setIgnoringElementContentWhitespace(true);
- factory.setIgnoringComments(true);
- BUILDER_FACTORY = factory;
- }
-
- private static final ThreadLocal<DocumentBuilder> DEFAULT_DOM_BUILDER = new ThreadLocal<DocumentBuilder>(){
- @Override
- protected DocumentBuilder initialValue() {
- try {
- return BUILDER_FACTORY.newDocumentBuilder();
- } catch (final ParserConfigurationException e) {
- throw new IllegalStateException("Failed to create threadLocal dom builder", e);
- }
- }
-
- @Override
- public void set(final DocumentBuilder value) {
- throw new UnsupportedOperationException();
- }
- };
-
- private XmlUtil() {
- throw new UnsupportedOperationException("Utility class");
- }
-
- public static Element readXmlToElement(final String xmlContent) throws SAXException, IOException {
- Document doc = readXmlToDocument(xmlContent);
- return doc.getDocumentElement();
- }
-
- public static Element readXmlToElement(final InputStream xmlContent) throws SAXException, IOException {
- Document doc = readXmlToDocument(xmlContent);
- return doc.getDocumentElement();
- }
-
- public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
- return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8)));
- }
-
- // TODO improve exceptions throwing
- // along with XmlElement
-
- public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
- Document doc = DEFAULT_DOM_BUILDER.get().parse(xmlContent);
-
- doc.getDocumentElement().normalize();
- return doc;
- }
-
- public static Element readXmlToElement(final File xmlFile) throws SAXException, IOException {
- return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
- }
-
- public static Document newDocument() {
- return DEFAULT_DOM_BUILDER.get().newDocument();
- }
-
- public static Element createElement(final Document document, final String qName, final Optional<String> namespaceURI) {
- if(namespaceURI.isPresent()) {
- final Element element = document.createElementNS(namespaceURI.get(), qName);
- String name = XMLNS_ATTRIBUTE_KEY;
- if(element.getPrefix() != null) {
- name += ":" + element.getPrefix();
- }
- element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
- return element;
- }
- return document.createElement(qName);
- }
-
- public static Element createTextElement(final Document document, final String qName, final String content, final Optional<String> namespaceURI) {
- Element typeElement = createElement(document, qName, namespaceURI);
- typeElement.appendChild(document.createTextNode(content));
- return typeElement;
- }
-
- public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
- final String namespace, final String contentWithoutPrefix) {
-
- return createTextElementWithNamespacedContent(document, qName, prefix, namespace, contentWithoutPrefix, Optional.<String>absent());
- }
-
- public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
- final String namespace, final String contentWithoutPrefix, final Optional<String> namespaceURI) {
-
- String content = createPrefixedValue(XmlMappingConstants.PREFIX, contentWithoutPrefix);
- Element element = createTextElement(document, qName, content, namespaceURI);
- String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
- element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
- return element;
- }
-
- public static String createPrefixedValue(final String prefix, final String value) {
- return prefix + ":" + value;
- }
-
- public static String toString(final Document document) {
- return toString(document.getDocumentElement());
- }
-
- public static String toString(final Element xml) {
- return toString(xml, false);
- }
-
- public static String toString(final XmlElement xmlElement) {
- return toString(xmlElement.getDomElement(), false);
- }
-
- public static String toString(final Element xml, final boolean addXmlDeclaration) {
- try {
- Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
-
- StreamResult result = new StreamResult(new StringWriter());
- DOMSource source = new DOMSource(xml);
- transformer.transform(source, result);
-
- return result.getWriter().toString();
- } catch (Exception | TransformerFactoryConfigurationError e) {
- throw new IllegalStateException("Unable to serialize xml element " + xml, e);
- }
- }
-
- public static String toString(final Document doc, final boolean addXmlDeclaration) {
- return toString(doc.getDocumentElement(), addXmlDeclaration);
- }
-
- public static Schema loadSchema(final InputStream... fromStreams) {
- Source[] sources = new Source[fromStreams.length];
- int i = 0;
- for (InputStream stream : fromStreams) {
- sources[i++] = new StreamSource(stream);
- }
-
- try {
- return SCHEMA_FACTORY.newSchema(sources);
- } catch (final SAXException e) {
- throw new IllegalStateException("Failed to instantiate XML schema", e);
- }
- }
-
- public static Object evaluateXPath(final XPathExpression expr, final Object rootNode, final QName returnType) {
- try {
- return expr.evaluate(rootNode, returnType);
- } catch (final XPathExpressionException e) {
- throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
- }
- }
-
- public static Document createDocumentCopy(final Document original) {
- final Document copiedDocument = newDocument();
- final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
- copiedDocument.appendChild(copiedRoot);
- return copiedDocument;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.util;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import org.junit.Before;
-import org.junit.Test;
-
-public class AttributeEntryTest {
-
- private AttributeEntry attributeEntryClient;
- private final String key = "myKey";
- private final String description = "myDescription";
- private final String type = "myType";
- private final boolean boolValue = false;
-
- @Before
- public void setUp() throws Exception {
- attributeEntryClient = new AttributeEntry("myKey", "myDescription", null, "myType", false);
- }
-
- @Test
- public void testAttributeEntryGetters() throws Exception{
- assertEquals(key, attributeEntryClient.getKey());
- assertEquals(description, attributeEntryClient.getDescription());
- final Object value = attributeEntryClient.getValue();
- assertNull(value);
- assertEquals(type, attributeEntryClient.getType());
- assertEquals(boolValue, attributeEntryClient.isRw());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-import static org.hamcrest.CoreMatchers.hasItem;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-
-import com.google.common.collect.Sets;
-import java.lang.management.ManagementFactory;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ConfigRegistry;
-
-public class ConfigRegistryClientsTest {
-
- private TestingConfigRegistry testingRegistry;
- private ObjectName testingRegistryON;
- private final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
- private ConfigRegistryClient jmxRegistryClient;
- private ConfigTransactionClient jmxTransactionClient;
- private Map<String, ObjectName> map;
-
- @Before
- public void setUp() throws Exception {
- testingRegistry = new TestingConfigRegistry();
- testingRegistryON = ConfigRegistry.OBJECT_NAME;
- mbs.registerMBean(testingRegistry, testingRegistryON);
- jmxRegistryClient = new ConfigRegistryJMXClient(
- ManagementFactory.getPlatformMBeanServer());
- map = new HashMap<>();
- }
-
- @After
- public void cleanUp() throws Exception {
- if (testingRegistryON != null) {
- mbs.unregisterMBean(testingRegistryON);
- }
- }
-
- @Test
- public void testCreateTransaction() throws Exception{
- jmxTransactionClient = jmxRegistryClient.createTransaction();
- assertNotNull(jmxTransactionClient);
- }
-
- @Test
- public void testGetConfigTransactionClient2() throws Exception{
- jmxTransactionClient = jmxRegistryClient.getConfigTransactionClient("transactionName");
- assertNotNull(jmxTransactionClient);
- }
-
- @Test
- public void testGetConfigTransactionClient() throws Exception{
- jmxTransactionClient = jmxRegistryClient.getConfigTransactionClient(testingRegistryON);
- assertNotNull(jmxTransactionClient);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testNewMXBeanProxy() throws Exception{
- if (jmxRegistryClient instanceof ConfigRegistryJMXClient) {
- ConfigRegistryJMXClient client = (ConfigRegistryJMXClient) jmxRegistryClient;
- assertNull(client.newMXBeanProxy(testingRegistryON, String.class));
- } else {
- throw new AssertionError("brm msg");
- }
- }
-
- @Test
- public void testBeginConfig() throws Exception{
- Assert.assertNotNull(jmxRegistryClient.beginConfig());
- }
-
- @Test
- public void testCommitConfig() throws Exception{
- assertNull(jmxRegistryClient.commitConfig(testingRegistryON));
- }
-
- @Test
- public void testGetOpenConfigs() throws Exception{
- assertNull(jmxRegistryClient.getOpenConfigs());
- }
-
- @Test(expected = RuntimeException.class)
- public void testGetVersion() throws Exception{
- assertEquals(3, jmxRegistryClient.getVersion());
- }
-
- @Test
- public void testGetAvailableModuleNames() throws Exception{
- assertNull(jmxRegistryClient.getAvailableModuleNames());
- }
-
- @Test
- public void testIsHealthy() throws Exception{
- assertEquals(false, jmxRegistryClient.isHealthy());
- }
-
- @Test
- public void testLookupConfigBeans3() throws Exception{
- Set<ObjectName> son = jmxRegistryClient.lookupConfigBeans();
- assertEquals(3, son.size());
- }
-
- @Test
- public void testLookupConfigBeans2() throws Exception{
- Set<ObjectName> son = jmxRegistryClient.lookupConfigBeans(TestingConfigRegistry.moduleName1);
- assertEquals(2, son.size());
- }
-
- @Test
- public void testLookupConfigBeans() throws Exception{
- Set<ObjectName> son = jmxRegistryClient.lookupConfigBeans(TestingConfigRegistry.moduleName1, TestingConfigRegistry.instName1);
- Set<ObjectName> on = Sets.newHashSet(TestingConfigRegistry.conf2);
- assertEquals(on, son);
- }
-
- @Test
- public void testLookupConfigBean() throws Exception{
- ObjectName on = jmxRegistryClient.lookupConfigBean(TestingConfigRegistry.moduleName1, null);
- assertEquals(TestingConfigRegistry.conf3, on);
- }
-
- @Test
- public void testLookupRuntimeBeans() throws Exception {
- Set<ObjectName> jmxLookup = lookupRuntimeBeans(jmxRegistryClient);
- assertEquals(Sets.newHashSet(TestingConfigRegistry.run2, TestingConfigRegistry.run1, TestingConfigRegistry.run3), jmxLookup);
- }
-
- private Set<ObjectName> lookupRuntimeBeans(final ConfigRegistryClient client)
- throws Exception {
- Set<ObjectName> beans = client.lookupRuntimeBeans();
- for (ObjectName on : beans) {
- assertEquals("RuntimeBean", on.getKeyProperty("type"));
- }
- assertEquals(3, beans.size());
- return beans;
- }
-
- @Test
- public void testLookupRuntimeBeansWithIfcNameAndInstanceName()
- throws InstanceNotFoundException {
- Set<ObjectName> jmxLookup = clientLookupRuntimeBeansWithModuleAndInstance(
- jmxRegistryClient, TestingConfigRegistry.moduleName1,
- TestingConfigRegistry.instName1);
- assertEquals(1, jmxLookup.size());
- assertEquals(Sets.newHashSet(TestingConfigRegistry.run2), jmxLookup);
-
- jmxLookup = clientLookupRuntimeBeansWithModuleAndInstance(
- jmxRegistryClient, TestingConfigRegistry.moduleName2,
- TestingConfigRegistry.instName2);
- assertEquals(1, jmxLookup.size());
- assertEquals(Sets.newHashSet(TestingConfigRegistry.run3), jmxLookup);
-
- jmxLookup = clientLookupRuntimeBeansWithModuleAndInstance(
- jmxRegistryClient, TestingConfigRegistry.moduleName1,
- TestingConfigRegistry.instName2);
- assertEquals(0, jmxLookup.size());
- assertEquals(Sets.newHashSet(), jmxLookup);
- }
-
- private Set<ObjectName> clientLookupRuntimeBeansWithModuleAndInstance(
- final ConfigRegistryClient client, final String moduleName, final String instanceName) {
- Set<ObjectName> beans = client.lookupRuntimeBeans(moduleName, instanceName);
- if (beans.size() > 0) {
- assertEquals("RuntimeBean",
- beans.iterator().next().getKeyProperty("type"));
- }
- return beans;
- }
-
- @Test
- public void testCheckConfigBeanExists() throws Exception{
- jmxRegistryClient.checkConfigBeanExists(testingRegistryON);
- assertEquals(true, TestingConfigRegistry.checkBool);
- }
-
- @Test
- public void testLookupConfigBeanByServiceInterfaceName() throws Exception{
- ObjectName on = clientLookupConfigBeanByServiceInterfaceName();
- assertEquals(TestingConfigRegistry.conf1, on);
- }
-
- private ObjectName clientLookupConfigBeanByServiceInterfaceName(){
- return jmxRegistryClient.lookupConfigBeanByServiceInterfaceName("qnameA", "refA");
- }
-
- @Test
- public void testGetServiceMapping() throws Exception{
- assertNull(jmxRegistryClient.getServiceMapping());
- }
-
- @Test
- public void testLookupServiceReferencesByServiceInterfaceName() throws Exception{
- map.put("conf2", TestingConfigRegistry.conf2);
- assertEquals(map, jmxRegistryClient.lookupServiceReferencesByServiceInterfaceName("qnameB"));
- }
-
- @Test
- public void testLookupServiceInterfaceNames() throws Exception{
- assertThat(clientLookupServiceInterfaceNames(testingRegistryON), hasItem(TestingConfigRegistry.serviceQName1));
- assertThat(clientLookupServiceInterfaceNames(testingRegistryON), hasItem(TestingConfigRegistry.serviceQName2));
- }
-
- private Set<String> clientLookupServiceInterfaceNames(final ObjectName client) throws InstanceNotFoundException{
- return jmxRegistryClient.lookupServiceInterfaceNames(client);
- }
-
- @Test
- public void testGetServiceInterfaceName() throws Exception{
- assertNull(jmxRegistryClient.getServiceInterfaceName(null, null));
- }
-
- @Test(expected = RuntimeException.class)
- public void testInvokeMethod() throws Exception{
- assertNull(jmxRegistryClient.invokeMethod(testingRegistryON, "name", null, null));
- }
-
- @Test(expected = RuntimeException.class)
- public void testGetAttributeCurrentValue() throws Exception{
- assertNull(jmxRegistryClient.getAttributeCurrentValue(testingRegistryON, "attrName"));
- }
-
- @Test
- public void testGetAvailableModuleFactoryQNames() throws Exception{
- for(String str : jmxRegistryClient.getAvailableModuleFactoryQNames()){
- if(str != TestingConfigRegistry.moduleName1){
- assertEquals(TestingConfigRegistry.moduleName2, str);
- }
- else{
- assertEquals(TestingConfigRegistry.moduleName1, str);
- }
- }
- }
-
- @Test
- public void testGetServiceReference() throws Exception{
- Assert.assertNotNull(jmxRegistryClient.getServiceReference(null, null));
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void testcheckServiceReferenceExists() throws Exception{
- jmxRegistryClient.checkServiceReferenceExists(testingRegistryON);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-
-import com.google.common.collect.Sets;
-import java.lang.management.ManagementFactory;
-import java.util.Collections;
-import java.util.Map;
-import java.util.Set;
-import javax.management.Attribute;
-import javax.management.MBeanException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.ValidationException.ExceptionMessageWithStackTrace;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-public class ConfigTransactionClientsTest {
- private final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
- private TestingConfigTransactionController transactionController;
- private ObjectName transactionControllerON;
- private ConfigTransactionClient jmxTransactionClient;
- Attribute attr;
-
-
- @Before
- public void setUp() throws Exception {
- transactionController = new TestingConfigTransactionController();
- transactionControllerON = new ObjectName(ObjectNameUtil.ON_DOMAIN + ":"
- + ObjectNameUtil.TYPE_KEY + "=TransactionController");
- mbs.registerMBean(transactionController, transactionControllerON);
- jmxTransactionClient = new ConfigTransactionJMXClient(null,
- transactionControllerON,
- ManagementFactory.getPlatformMBeanServer());
- }
-
- @After
- public void cleanUp() throws Exception {
- if (transactionControllerON != null) {
- mbs.unregisterMBean(transactionControllerON);
- }
- }
-
- @Test
- public void testLookupConfigBeans() throws Exception {
- Set<ObjectName> jmxLookup = testClientLookupConfigBeans(jmxTransactionClient);
- assertEquals(Sets.newHashSet(transactionController.conf1,
- transactionController.conf2, transactionController.conf3),
- jmxLookup);
- }
-
- private Set<ObjectName> testClientLookupConfigBeans(
- final ConfigTransactionClient client) {
- Set<ObjectName> beans = client.lookupConfigBeans();
- for (ObjectName on : beans) {
- assertEquals("Module", on.getKeyProperty("type"));
- }
- assertEquals(3, beans.size());
- return beans;
- }
-
- @Test
- public void testGetObjectName() throws Exception {
- testClientGetObjectName(jmxTransactionClient);
- assertEquals(testClientGetObjectName(jmxTransactionClient), true);
- }
-
- private boolean testClientGetObjectName(final ConfigTransactionClient client) {
- return transactionControllerON.equals(client.getObjectName());
- }
-
- @Test
- public void testGetAvailableModuleNames() throws Exception {
- Set<String> jmxMN = testClientGetAvailableModuleNames(jmxTransactionClient);
- assertNull(jmxMN);
- }
-
- private Set<String> testClientGetAvailableModuleNames(
- final ConfigTransactionClient client) {
- return client.getAvailableModuleNames();
- }
-
- @Test
- public void testGetTransactionName() throws Exception {
- String jmxTN = testClientGetTransactionName(jmxTransactionClient);
- assertEquals("transactionName", jmxTN);
- }
-
- private String testClientGetTransactionName(final ConfigTransactionClient client) {
- return client.getTransactionName();
- }
-
- @Ignore
- public void testGetVersion() throws Exception {
- long jmxVersion = jmxTransactionClient.getVersion();
- assertNull(jmxVersion);
- }
-
- @Ignore
- public void testGetParentVersion() throws Exception {
- long jmxParentVersion = jmxTransactionClient.getParentVersion();
- assertNull(jmxParentVersion);
- }
-
- @Test
- public void testValidateConfig() throws Exception {
- jmxTransactionClient.validateConfig();
- }
-
- @Test
- public void testAbortConfig() throws Exception {
- jmxTransactionClient.abortConfig();
- }
-
- @Test
- public void testDestroyModule2() throws Exception {
- jmxTransactionClient.destroyModule("moduleB", "instB");
- assertNull(transactionController.conf4);
- }
-
- @Test
- public void testDestroyModule() throws Exception {
- ObjectName on = testClientCreateModule(jmxTransactionClient);
- jmxTransactionClient.destroyModule(on);
- }
-
- @Test
- public void testCreateModule() throws Exception {
- ObjectName on = testClientCreateModule(jmxTransactionClient);
- Assert.assertNotNull(on);
- }
-
- private ObjectName testClientCreateModule(final ConfigTransactionClient client)
- throws Exception {
- return client.createModule("testModuleName", "testInstanceName");
- }
-
- @Ignore
- public void testAssertVersion() {
- jmxTransactionClient.assertVersion((int)jmxTransactionClient.getParentVersion(),
- (int)jmxTransactionClient.getVersion());
- }
-
- @Test(expected = NullPointerException.class)
- public void testCommit() throws Exception {
- jmxTransactionClient.commit();
- }
-
- @Test
- public void testLookupConfigBeans2() throws Exception {
- Set<ObjectName> jmxLookup = testClientLookupConfigBeans2(
- jmxTransactionClient, "moduleB");
- assertEquals(Sets.newHashSet(transactionController.conf3), jmxLookup);
- }
-
- private Set<ObjectName> testClientLookupConfigBeans2(
- final ConfigTransactionClient client, final String moduleName) {
- Set<ObjectName> beans = client.lookupConfigBeans(moduleName);
- assertEquals(1, beans.size());
- return beans;
- }
-
- @Test
- public void testLookupConfigBean() throws Exception {
- Set<ObjectName> jmxLookup = testClientLookupConfigBean(
- jmxTransactionClient, "moduleB", "instB");
- assertEquals(Sets.newHashSet(transactionController.conf3), jmxLookup);
- }
-
- private Set<ObjectName> testClientLookupConfigBean(
- final ConfigTransactionClient client, final String moduleName,
- final String instanceName) {
- Set<ObjectName> beans = client.lookupConfigBeans(moduleName,
- instanceName);
- assertEquals(1, beans.size());
- return beans;
- }
-
- @Test
- public void testLookupConfigBeans3() throws Exception {
- Set<ObjectName> jmxLookup = testClientLookupConfigBeans3(
- jmxTransactionClient, "moduleB", "instB");
- assertEquals(Sets.newHashSet(transactionController.conf3), jmxLookup);
- }
-
- private Set<ObjectName> testClientLookupConfigBeans3(
- final ConfigTransactionClient client, final String moduleName,
- final String instanceName) {
- Set<ObjectName> beans = client.lookupConfigBeans(moduleName,
- instanceName);
- assertEquals(1, beans.size());
- return beans;
- }
-
- @Test
- public void testCheckConfigBeanExists() throws Exception {
- jmxTransactionClient.checkConfigBeanExists(transactionControllerON);
- assertEquals("configBeanExists", transactionController.check);
- }
-
- @Test
- public void testSaveServiceReference() throws Exception {
- assertEquals(transactionControllerON, jmxTransactionClient.saveServiceReference("serviceInterfaceName", "refName", transactionControllerON));
- }
-
- @Test
- public void testRemoveServiceReference() throws Exception {
- jmxTransactionClient.removeServiceReference("serviceInterface", "refName");
- assertEquals("refName", transactionController.check);
- }
-
- @Test
- public void testRemoveAllServiceReferences() throws Exception {
- jmxTransactionClient.removeAllServiceReferences();
- assertNull(transactionController.check);
- }
-
- @Test
- public void testLookupConfigBeanByServiceInterfaceName() throws Exception {
- assertEquals(transactionController.conf3, jmxTransactionClient.lookupConfigBeanByServiceInterfaceName("serviceInterface", "refName"));
- }
-
- @Test
- public void testGetServiceMapping() throws Exception {
- Assert.assertNotNull(jmxTransactionClient.getServiceMapping());
- }
-
- @Test
- public void testLookupServiceReferencesByServiceInterfaceName() throws Exception {
- Assert.assertNotNull(jmxTransactionClient.lookupServiceReferencesByServiceInterfaceName("serviceInterfaceQName"));
- }
-
- @Test
- public void testLookupServiceInterfaceNames() throws Exception {
- assertEquals(Sets.newHashSet("setA"), jmxTransactionClient.lookupServiceInterfaceNames(transactionControllerON));
- }
-
- @Test
- public void testGetServiceInterfaceName() throws Exception {
- assertEquals("namespace" + "localName", jmxTransactionClient.getServiceInterfaceName("namespace", "localName"));
- }
-
- @Test
- public void removeServiceReferences() throws Exception {
- assertEquals(true, jmxTransactionClient.removeServiceReferences(transactionControllerON));
- }
-
- @Test
- public void testGetServiceReference() throws Exception {
- assertEquals(transactionController.conf3, jmxTransactionClient.getServiceReference("serviceInterfaceQName", "refName"));
- }
-
- @Test
- public void testCheckServiceReferenceExists() throws Exception {
- jmxTransactionClient.checkServiceReferenceExists(transactionControllerON);
- assertEquals("referenceExist", transactionController.check);
- }
-
- @Test(expected = RuntimeException.class)
- public void testValidateBean() throws Exception {
- jmxTransactionClient.validateBean(transactionControllerON);
- }
-
- @Test(expected = ValidationException.class)
- public void testValidateBean2() throws Exception {
- MBeanServer mbsLocal = mock(MBeanServer.class);
- MBeanException mBeanException = new MBeanException(new ValidationException(
- Collections.<String, Map<String, ExceptionMessageWithStackTrace>>emptyMap()));
- doThrow(mBeanException).when(mbsLocal).invoke(transactionControllerON, "validate", null, null);
-
- ConfigTransactionJMXClient jmxTransactionClientFake = new ConfigTransactionJMXClient(null,
- transactionControllerON,
- mbsLocal);
- jmxTransactionClientFake.validateBean(transactionControllerON);
- }
-
- @Test(expected = RuntimeException.class)
- public void testValidateBean3() throws Exception {
- MBeanServer mbsLocal = mock(MBeanServer.class);
- MBeanException mBeanException = new MBeanException(new RuntimeException());
- doThrow(mBeanException).when(mbsLocal).invoke(transactionControllerON, "validate", null, null);
- ConfigTransactionJMXClient jmxTransactionClientFake = new ConfigTransactionJMXClient(null,
- transactionControllerON,
- mbsLocal);
- jmxTransactionClientFake.validateBean(transactionControllerON);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testSetAttribute() throws Exception {
- attr = null;
- jmxTransactionClient.setAttribute(transactionControllerON, "attrName", attr);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGetAttribute() throws Exception {
- attr = jmxTransactionClient.getAttribute(transactionController.conf3, "attrName");
- assertNull(attr);
- }
-
- @Test
- public void testGetAvailableModuleFactoryQNames() throws Exception {
- Assert.assertNotNull(jmxTransactionClient.getAvailableModuleFactoryQNames());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Sets;
-import java.lang.management.ManagementFactory;
-import java.lang.reflect.Method;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ConfigRegistry;
-import org.opendaylight.controller.config.api.LookupRegistry;
-import org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-public class LookupTest {
-
- private TestingConfigRegistry testingRegistry;
- private ObjectName testingRegistryON;
- private final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
- private ConfigRegistryClient jmxRegistryClient;
- private ConfigTransactionControllerMXBean testingTransactionController;
- private ObjectName testingTransactionControllerON;
- private ConfigTransactionClient jmxTransactionClient;
-
- Map<LookupRegistry, ? extends Set<? extends LookupRegistry>> lookupProvidersToClients;
-
- @Before
- public void setUp() throws Exception {
- testingRegistry = new TestingConfigRegistry();
- testingRegistryON = ConfigRegistry.OBJECT_NAME;
- mbs.registerMBean(testingRegistry, testingRegistryON);
- jmxRegistryClient = new ConfigRegistryJMXClient(
- ManagementFactory.getPlatformMBeanServer());
-
-
- testingTransactionController = new TestingConfigTransactionController();
- testingTransactionControllerON = new ObjectName(
- ObjectNameUtil.ON_DOMAIN + ":" + ObjectNameUtil.TYPE_KEY
- + "=TransactionController");
- mbs.registerMBean(testingTransactionController,
- testingTransactionControllerON);
-
- jmxTransactionClient = new ConfigTransactionJMXClient(null,
- testingTransactionControllerON,
- ManagementFactory.getPlatformMBeanServer());
-
- HashSet<ConfigRegistryClient> registryClients = Sets.newHashSet(jmxRegistryClient);
- HashSet<ConfigTransactionClient> configTransactionClients = Sets.newHashSet(jmxTransactionClient);
- lookupProvidersToClients = ImmutableMap.of((LookupRegistry) testingRegistry, registryClients,
- testingTransactionController, configTransactionClients);
- }
-
- @After
- public void cleanUp() throws Exception {
- mbs.unregisterMBean(testingRegistryON);
- mbs.unregisterMBean(testingTransactionControllerON);
- }
-
- @Test
- public void testLookupConfigBeans() throws Exception {
- Method method = LookupRegistry.class.getMethod("lookupConfigBeans");
- Object[] args = new Object[0];
- test(method, args);
- }
-
- @Test
- public void testLookupConfigBeans1() throws Exception {
- Method method = LookupRegistry.class.getMethod("lookupConfigBeans",
- String.class);
- Object[] args = new Object[] { TestingConfigRegistry.moduleName1 };
- test(method, args);
- }
-
- @Test
- public void testLookupConfigBeans2() throws Exception {
- Method method = LookupRegistry.class.getMethod("lookupConfigBeans",
- String.class, String.class);
- Object[] args = new Object[] { TestingConfigRegistry.moduleName1, TestingConfigRegistry.instName1 };
- test(method, args);
- }
-
- @Test
- public void testLookupConfigBean() throws Exception {
- Method method = LookupRegistry.class.getMethod("lookupConfigBean",
- String.class, String.class);
- Object[] args = new Object[] { TestingConfigRegistry.moduleName1, TestingConfigRegistry.instName1 };
- test(method, args);
- }
-
- private void test(final Method method, final Object[] args) throws Exception {
- for (Entry<LookupRegistry, ? extends Set<? extends LookupRegistry>> entry : lookupProvidersToClients
- .entrySet()) {
- Object expected = method.invoke(entry.getKey(), args);
- for (LookupRegistry client : entry.getValue()) {
- Object actual = method.invoke(client, args);
- assertEquals("Error while comparing " + entry.getKey()
- + " with client " + client, expected, actual);
- }
- }
- }
-
- @Test
- public void testException() {
- for (Entry<LookupRegistry, ? extends Set<? extends LookupRegistry>> entry : lookupProvidersToClients
- .entrySet()) {
- for (LookupRegistry client : entry.getValue()) {
- try {
- client.lookupConfigBean(
- InstanceNotFoundException.class.getSimpleName(), "");
- fail(client.toString());
- } catch (final InstanceNotFoundException e) {
-
- }
- }
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-public class TestingBeanImpl implements TestingBeanMXBean {
-
- @Override
- public int getStat() {
- return 0;
- }
-
- @Override
- public void setStat() {
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-public interface TestingBeanMXBean {
-
- int getStat();
-
- void setStat();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-import com.google.common.collect.Sets;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-public class TestingConfigRegistry implements ConfigRegistryMXBean {
-
- static final ObjectName conf1, conf2, conf3, run1, run2, run3;
- public static String check;
- public static boolean checkBool;
- private Map<String, ObjectName> map = new HashMap<>();
-
- public static final String moduleName1 = "moduleA";
- public static final String moduleName2 = "moduleB";
- public static final String instName1 = "instA";
- public static final String instName2 = "instB";
- public static final String refName1 = "refA";
- public static final String refName2 = "refB";
- public static final String serviceQName1 = "qnameA";
- public static final String serviceQName2 = "qnameB";
-
- static {
- conf1 = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=Module," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName1 + "," + ObjectNameUtil.SERVICE_QNAME_KEY
- + "=" + serviceQName1 + "," + ObjectNameUtil.REF_NAME_KEY
- + "=" + refName1);
- conf2 = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=Module," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName1 + "," + ObjectNameUtil.INSTANCE_NAME_KEY
- + "=" + instName1 + "," + ObjectNameUtil.SERVICE_QNAME_KEY
- + "=" + serviceQName2 + "," + ObjectNameUtil.REF_NAME_KEY
- + "=" + refName1);
- conf3 = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=Module," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName2 + "," + ObjectNameUtil.INSTANCE_NAME_KEY
- + "=" + instName2);
- run1 = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=RuntimeBean," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName1);
- run2 = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=RuntimeBean," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName1 + "," + ObjectNameUtil.INSTANCE_NAME_KEY
- + "=" + instName1);
- run3 = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=RuntimeBean," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName2 + "," + ObjectNameUtil.INSTANCE_NAME_KEY
- + "=" + instName2);
-
- check = null;
- checkBool = false;
-
- }
-
- @Override
- public ObjectName beginConfig() {
- return conf2;
- }
-
- @Override
- public CommitStatus commitConfig(final ObjectName transactonControllerON)
- throws ConflictingVersionException, ValidationException {
- if (transactonControllerON == null) {
- Exception e = new RuntimeException("message");
- throw ValidationException.createForSingleException(
- new ModuleIdentifier("moduleName", "instanceName"), e);
- }
- return null;
- }
-
- @Override
- public List<ObjectName> getOpenConfigs() {
- return null;
- }
-
- @Override
- public boolean isHealthy() {
- return false;
- }
-
- @Override
- public Set<String> getAvailableModuleNames() {
- return null;
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans() {
- return Sets.newHashSet(conf1, conf2, conf3);
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName) {
- if (moduleName.equals(moduleName1)) {
- return Sets.newHashSet(conf1, conf2);
- } else if (moduleName.equals(moduleName2)) {
- return Sets.newHashSet(conf3);
- } else {
- return null;
- }
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName,
- final String instanceName) {
- if (moduleName.equals(moduleName1) && instanceName.equals(instName1)) {
- return Sets.newHashSet(conf2);
- } else if (moduleName.equals(moduleName2)
- && instanceName.equals(instName2)) {
- return Sets.newHashSet(conf3);
- } else {
- return null;
- }
- }
-
- @Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- if (moduleName.equals(InstanceNotFoundException.class.getSimpleName())) {
- throw new InstanceNotFoundException();
- }
- return conf3;
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans() {
- return Sets.<ObjectName> newHashSet(run1, run2, run3);
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName,
- final String instanceName) {
- if (moduleName.equals(moduleName1) && instanceName.equals(instName1)) {
- return Sets.<ObjectName> newHashSet(run2);
- } else if (moduleName.equals(moduleName2)
- && instanceName.equals(instName2)) {
- return Sets.<ObjectName> newHashSet(run3);
- } else {
- return Sets.<ObjectName> newHashSet();
- }
- }
-
- @Override
- public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
- Set<ObjectName> configBeans = Sets.<ObjectName> newHashSet(run1, run2, run3);
- if(configBeans.size()>0){
- checkBool = true;
- }
- }
-
- @Override
- public ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
- if (serviceInterfaceQName.equals(serviceQName1) && refName.equals(refName1)) {
- return conf1;
- }
- else{
- return null;
- }
- }
-
- @Override
- public Map<String, Map<String, ObjectName>> getServiceMapping() {
- return null;
- }
-
- @Override
- public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
-
- if(serviceInterfaceQName.equals(serviceQName1)){
- map.put("conf1", conf1);
- }
- else if(serviceInterfaceQName.equals(serviceQName2)){
- map.put("conf2", conf2);
- }
- else{
- map.put("conf3", conf3);
- }
- return map;
- }
-
- @Override
- public Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
- return Sets.<String> newHashSet(serviceQName1, serviceQName2);
- }
-
- @Override
- public String getServiceInterfaceName(final String namespace, final String localName) {
- return null;
- }
-
- @Override
- public Set<String> getAvailableModuleFactoryQNames() {
- return Sets.<String> newHashSet(moduleName1, moduleName2);
- }
-
- @Override
- public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
- return conf1;
- }
-
- @Override
- public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
- throw new UnsupportedOperationException();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.util;
-
-import com.google.common.collect.Sets;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-public class TestingConfigTransactionController implements
- ConfigTransactionControllerMXBean {
-
- public final ObjectName conf1, conf2, conf3;
- public ObjectName conf4;
- public String check;
- Map<String, ObjectName> mapSub;
- Map<String, Map<String, ObjectName>> map;
-
- public static final String moduleName1 = "moduleA";
- public static final String moduleName2 = "moduleB";
- public static final String instName1 = "instA";
- public static final String instName2 = "instB";
-
- public TestingConfigTransactionController() throws Exception {
- conf1 = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=Module," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName1);
- conf2 = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=Module," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName1 + "," + ObjectNameUtil.INSTANCE_NAME_KEY
- + "=" + instName1);
- conf3 = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=Module," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName2 + "," + ObjectNameUtil.INSTANCE_NAME_KEY
- + "=" + instName2);
- conf4 = ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=Module," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName2 + "," + ObjectNameUtil.INSTANCE_NAME_KEY
- + "=" + instName2);
- mapSub = new HashMap<>();
- map = new HashMap<>();
- }
-
- @Override
- public ObjectName createModule(final String moduleName, final String instanceName)
- throws InstanceAlreadyExistsException {
- //return null;
- return ObjectNameUtil.createON(ObjectNameUtil.ON_DOMAIN
- + ":type=Module," + ObjectNameUtil.MODULE_FACTORY_NAME_KEY
- + "=" + moduleName);
- }
-
- @Override
- public void reCreateModule(final ObjectName objectName) {
- }
-
- @Override
- public void destroyModule(final ObjectName objectName)
- throws InstanceNotFoundException {
- if(objectName != null){
- conf4 = null;
- }
- }
-
- @Override
- public void abortConfig() {
- }
-
- @Override
- public void validateConfig() throws ValidationException {
- }
-
- @Override
- public String getTransactionName() {
- //return null;
- return "transactionName";
- }
-
- @Override
- public Set<String> getAvailableModuleNames() {
- return null;
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans() {
- return Sets.newHashSet(conf1, conf2, conf3);
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName) {
- if (moduleName.equals(moduleName1)) {
- return Sets.newHashSet(conf1, conf2);
- } else if (moduleName.equals(moduleName2)) {
- return Sets.newHashSet(conf3);
- } else {
- return null;
- }
- }
-
- @Override
- public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
- throws InstanceNotFoundException {
- if (moduleName.equals(InstanceNotFoundException.class.getSimpleName())) {
- throw new InstanceNotFoundException();
- }
- return conf3;
- }
-
- @Override
- public Set<ObjectName> lookupConfigBeans(final String moduleName,
- final String instanceName) {
- if (moduleName.equals(moduleName1) && instanceName.equals(instName1)) {
- return Sets.newHashSet(conf2);
- } else if (moduleName.equals(moduleName2)
- && instanceName.equals(instName2)) {
- return Sets.newHashSet(conf3);
- } else {
- return null;
- }
- }
-
- @Override
- public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
- check = "configBeanExists";
- }
-
- @Override
- public ObjectName saveServiceReference(final String serviceInterfaceName, final String refName, final ObjectName moduleON) throws InstanceNotFoundException {
- return moduleON;
- }
-
- @Override
- public void removeServiceReference(final String serviceInterfaceName, final String refName) {
- check = refName;
- }
-
- @Override
- public void removeAllServiceReferences() {
- check = null;
- }
-
- @Override
- public ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
- return conf3;
- }
-
- @Override
- public Map<String, Map<String, ObjectName>> getServiceMapping() {
- mapSub.put("A",conf2);
- map.put("AA", mapSub);
- return map;
- }
-
- @Override
- public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
- mapSub.put("A",conf2);
- return mapSub;
- }
-
- @Override
- public Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
- return Sets.newHashSet("setA");
- }
-
- @Override
- public String getServiceInterfaceName(final String namespace, final String localName) {
- return check=namespace+localName;
- }
-
- @Override
- public boolean removeServiceReferences(final ObjectName objectName) throws InstanceNotFoundException {
- return true;
- }
-
- @Override
- public Set<String> getAvailableModuleFactoryQNames() {
- return Sets.newHashSet("availableModuleFactoryQNames");
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans() {
- return Collections.emptySet();
- }
-
- @Override
- public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
- return Collections.emptySet();
- }
-
- @Override
- public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
- return conf3;
- }
-
- @Override
- public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
- check = "referenceExist";
- }
-}
+++ /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.config.util.xml;
-
-import static org.hamcrest.CoreMatchers.both;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import com.google.common.base.Optional;
-import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class XmlElementTest {
-
- private final String elementAsString = "<top xmlns=\"namespace\" xmlns:a=\"attrNamespace\" a:attr1=\"value1\" attr2=\"value2\">" +
- "<inner>" +
- "<deepInner>deepValue</deepInner>" +
- "</inner>" +
- "<innerNamespace xmlns=\"innerNamespace\">innerNamespaceValue</innerNamespace>" +
- "<innerPrefixed xmlns:b=\"prefixedValueNamespace\">b:valueWithPrefix</innerPrefixed>" +
- "</top>";
- private Document document;
- private Element element;
- private XmlElement xmlElement;
-
- @Before
- public void setUp() throws Exception {
- document = XmlUtil.readXmlToDocument(elementAsString);
- element = document.getDocumentElement();
- xmlElement = XmlElement.fromDomElement(element);
- }
-
- @Test
- public void testConstruct() throws Exception {
- final XmlElement fromString = XmlElement.fromString(elementAsString);
- assertEquals(fromString, xmlElement);
- XmlElement.fromDomDocument(document);
- XmlElement.fromDomElement(element);
- XmlElement.fromDomElementWithExpected(element, "top");
- XmlElement.fromDomElementWithExpected(element, "top", "namespace");
-
- try {
- XmlElement.fromString("notXml");
- fail();
- } catch (final DocumentedException e) {}
-
- try {
- XmlElement.fromDomElementWithExpected(element, "notTop");
- fail();
- } catch (final DocumentedException e) {}
-
- try {
- XmlElement.fromDomElementWithExpected(element, "top", "notNamespace");
- fail();
- } catch (final DocumentedException e) {}
- }
-
- @Test
- public void testGetters() throws Exception {
- assertEquals(element, xmlElement.getDomElement());
- assertEquals(element.getElementsByTagName("inner").getLength(), xmlElement.getElementsByTagName("inner").getLength());
-
- assertEquals("top", xmlElement.getName());
- assertTrue(xmlElement.hasNamespace());
- assertEquals("namespace", xmlElement.getNamespace());
- assertEquals("namespace", xmlElement.getNamespaceAttribute());
- assertEquals(Optional.of("namespace"), xmlElement.getNamespaceOptionally());
-
- assertEquals("value1", xmlElement.getAttribute("attr1", "attrNamespace"));
- assertEquals("value2", xmlElement.getAttribute("attr2"));
- assertEquals(2 + 2/*Namespace definition*/, xmlElement.getAttributes().size());
-
- assertEquals(3, xmlElement.getChildElements().size());
- assertEquals(1, xmlElement.getChildElements("inner").size());
- assertTrue(xmlElement.getOnlyChildElementOptionally("inner").isPresent());
- assertTrue(xmlElement.getOnlyChildElementWithSameNamespaceOptionally("inner").isPresent());
- assertEquals(0, xmlElement.getChildElements("unknown").size());
- assertFalse(xmlElement.getOnlyChildElementOptionally("unknown").isPresent());
- assertEquals(1, xmlElement.getChildElementsWithSameNamespace("inner").size());
- assertEquals(0, xmlElement.getChildElementsWithSameNamespace("innerNamespace").size());
- assertEquals(1, xmlElement.getChildElementsWithinNamespace("innerNamespace", "innerNamespace").size());
- assertTrue(xmlElement.getOnlyChildElementOptionally("innerNamespace", "innerNamespace").isPresent());
- assertFalse(xmlElement.getOnlyChildElementOptionally("innerNamespace", "unknownNamespace").isPresent());
-
- final XmlElement noNamespaceElement = XmlElement.fromString("<noNamespace/>");
- assertFalse(noNamespaceElement.hasNamespace());
- try {
- noNamespaceElement.getNamespace();
- fail();
- } catch (final MissingNameSpaceException e) {}
-
- final XmlElement inner = xmlElement.getOnlyChildElement("inner");
- final XmlElement deepInner = inner.getOnlyChildElementWithSameNamespaceOptionally().get();
- assertEquals(deepInner, inner.getOnlyChildElementWithSameNamespace());
- assertEquals(Optional.<XmlElement>absent(), xmlElement.getOnlyChildElementOptionally("unknown"));
- assertEquals("deepValue", deepInner.getTextContent());
- assertEquals("deepValue", deepInner.getOnlyTextContentOptionally().get());
- assertEquals("deepValue", deepInner.getOnlyTextContentOptionally().get());
- }
-
- @Test
- public void testExtractNamespaces() throws Exception {
- final XmlElement innerPrefixed = xmlElement.getOnlyChildElement("innerPrefixed");
- Map.Entry<String, String> namespaceOfTextContent = innerPrefixed.findNamespaceOfTextContent();
-
- assertNotNull(namespaceOfTextContent);
- assertEquals("b", namespaceOfTextContent.getKey());
- assertEquals("prefixedValueNamespace", namespaceOfTextContent.getValue());
- final XmlElement innerNamespace = xmlElement.getOnlyChildElement("innerNamespace");
- namespaceOfTextContent = innerNamespace.findNamespaceOfTextContent();
-
- assertEquals("", namespaceOfTextContent.getKey());
- assertEquals("innerNamespace", namespaceOfTextContent.getValue());
- }
-
- @Test
- public void testUnrecognisedElements() throws Exception {
- xmlElement.checkUnrecognisedElements(xmlElement.getOnlyChildElement("inner"), xmlElement.getOnlyChildElement("innerPrefixed"), xmlElement.getOnlyChildElement("innerNamespace"));
-
- try {
- xmlElement.checkUnrecognisedElements(xmlElement.getOnlyChildElement("inner"));
- fail();
- } catch (final DocumentedException e) {
- assertThat(e.getMessage(), both(containsString("innerNamespace")).and(containsString("innerNamespace")));
- }
- }
-}
+++ /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.config.util.xml;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import com.google.common.base.Optional;
-import java.io.ByteArrayInputStream;
-import org.custommonkey.xmlunit.Diff;
-import org.custommonkey.xmlunit.XMLUnit;
-import org.junit.Test;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.xml.sax.SAXParseException;
-
-public class XmlUtilTest {
-
- private final String xml = "<top xmlns=\"namespace\">\n" +
- "<innerText>value</innerText>\n" +
- "<innerPrefixedText xmlns:pref=\"prefixNamespace\">prefix:value</innerPrefixedText>\n" +
- "<innerPrefixedText xmlns=\"randomNamespace\" xmlns:pref=\"prefixNamespace\">prefix:value</innerPrefixedText>\n" +
- "</top>";
-
- @Test
- public void testCreateElement() throws Exception {
- final Document document = XmlUtil.newDocument();
- final Element top = XmlUtil.createElement(document, "top", Optional.of("namespace"));
-
- top.appendChild(XmlUtil.createTextElement(document, "innerText", "value", Optional.of("namespace")));
- top.appendChild(XmlUtil.createTextElementWithNamespacedContent(document, "innerPrefixedText", "pref", "prefixNamespace", "value", Optional.of("namespace")));
- top.appendChild(XmlUtil.createTextElementWithNamespacedContent(document, "innerPrefixedText", "pref", "prefixNamespace", "value", Optional.of("randomNamespace")));
-
- document.appendChild(top);
- assertEquals("top", XmlUtil.createDocumentCopy(document).getDocumentElement().getTagName());
-
- XMLUnit.setIgnoreAttributeOrder(true);
- XMLUnit.setIgnoreWhitespace(true);
-
- final Diff diff = XMLUnit.compareXML(XMLUnit.buildControlDocument(xml), document);
- assertTrue(diff.toString(), diff.similar());
- }
-
- @Test
- public void testLoadSchema() throws Exception {
- XmlUtil.loadSchema();
- try {
- XmlUtil.loadSchema(new ByteArrayInputStream(xml.getBytes()));
- fail("Input stream does not contain xsd");
- } catch (final IllegalStateException e) {
- assertTrue(e.getCause() instanceof SAXParseException);
- }
-
- }
-
- @Test(expected = SAXParseException.class)
- public void testXXEFlaw() throws Exception {
- XmlUtil.readXmlToDocument("<!DOCTYPE foo [ \n" +
- "<!ELEMENT foo ANY >\n" +
- "<!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]>\n" +
- "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- " <capabilities>\n" +
- " <capability>urn:ietf:params:netconf:base:1.0 &xxe;</capability>\n" +
- " </capabilities>\n" +
- " </hello>]]>]]>");
- }
-
-}
\ No newline at end of file
<name>${project.artifactId}</name>
<modules>
- <module>config-api</module>
- <module>config-manager</module>
- <module>config-plugin-parent</module>
- <module>config-util</module>
- <module>config-persister-api</module>
- <module>config-persister-file-xml-adapter</module>
- <module>config-persister-feature-adapter</module>
- <module>config-manager-facade-xml</module>
- <module>yang-jmx-generator</module>
- <module>yang-jmx-generator-plugin</module>
<module>threadpool-config-api</module>
<module>netty-config-api</module>
<module>threadpool-config-impl</module>
<module>netty-threadgroup-config</module>
<module>netty-event-executor-config</module>
<module>netty-timer-config</module>
- <module>config-persister-directory-xml-adapter</module>
- <module>yang-test-plugin</module>
- <module>shutdown-api</module>
- <module>shutdown-impl</module>
- <module>config-netty-config</module>
<module>config-artifacts</module>
- <module>config-parent</module>
- <module>config-filtering-parent</module>
- <module>config-persister-impl</module>
- <module>config-it-base</module>
</modules>
<dependencyManagement>
</dependency>
</dependencies>
</dependencyManagement>
-
- <profiles>
- <profile>
- <id>integrationtests</id>
- <activation>
- <activeByDefault>false</activeByDefault>
- </activation>
- <modules>
- <module>yang-jmx-generator-it</module>
- </modules>
- </profile>
- </profiles>
</project>
+++ /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>config-plugin-parent</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>../config-plugin-parent</relativePath>
- </parent>
- <artifactId>shutdown-api</artifactId>
- <packaging>bundle</packaging>
-
- <dependencies>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-api</artifactId>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.shutdown;
-
-import com.google.common.base.Optional;
-
-public interface ShutdownService {
-
- /**
- * Shut down the server.
- *
- * @param inputSecret must match configured secret of the implementation
- * @param reason Optional string to be logged while shutting down
- */
- void shutdown(String inputSecret, Long maxWaitTime, Optional<String> reason);
-}
+++ /dev/null
-module shutdown {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:shutdown";
- prefix "shutdown";
-
- import config { prefix config; revision-date 2013-04-05; }
-
- description
- "This module contains the base YANG definitions for
- shutdown service.
-
- Copyright (c)2013 Cisco Systems, Inc. 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";
-
- revision "2013-12-18" {
- description
- "Initial revision.";
- }
-
- identity shutdown {
- base "config:service-type";
- config:java-class "org.opendaylight.controller.config.shutdown.ShutdownService";
- }
-
-}
+++ /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>config-plugin-parent</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>../config-plugin-parent</relativePath>
- </parent>
- <artifactId>shutdown-impl</artifactId>
- <packaging>bundle</packaging>
-
- <dependencies>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>shutdown-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-manager</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-util</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
-</project>
+++ /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
- */
-/**
- * Generated file
-
- * Generated from: yang module name: shutdown-impl yang module local name: shutdown
- * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
- * Generated at: Wed Dec 18 14:02:06 CET 2013
- *
- * Do not modify this file unless it is present under src/main directory
- */
-package org.opendaylight.controller.config.yang.shutdown.impl;
-
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.JmxAttributeValidationException;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.osgi.framework.Bundle;
-
-public final class ShutdownModule extends AbstractShutdownModule {
- private final Bundle systemBundle;
-
- public ShutdownModule(final ModuleIdentifier identifier, final Bundle systemBundle) {
- super(identifier, null);
- singletonCheck(identifier);
- this.systemBundle = systemBundle;
- }
-
- public ShutdownModule(final ModuleIdentifier identifier, final ShutdownModule oldModule, final java.lang.AutoCloseable oldInstance,
- final Bundle systemBundle) {
- super(identifier, null, oldModule, oldInstance);
- singletonCheck(identifier);
- this.systemBundle = systemBundle;
- }
-
- private static void singletonCheck(final ModuleIdentifier identifier) {
- if (AbstractShutdownModuleFactory.NAME.equals(identifier.getInstanceName()) == false) {
- throw new IllegalArgumentException("Singleton enforcement failed. Expected instance name " + AbstractShutdownModuleFactory.NAME);
- }
- }
-
- @Deprecated // needed for generated code
- public ShutdownModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver, final ShutdownModule oldModule,
- final AutoCloseable oldInstance) {
- super(identifier, dependencyResolver, oldModule, oldInstance);
- throw new UnsupportedOperationException();
- }
-
- @Deprecated // needed for generated code
- public ShutdownModule(final ModuleIdentifier identifier, final DependencyResolver dependencyResolver) {
- super(identifier, dependencyResolver);
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected void customValidation() {
- JmxAttributeValidationException.checkNotNull(super.getSecret(), secretJmxAttribute);
- }
-
- @Override
- public java.lang.AutoCloseable createInstance() {
- return new ShutdownServiceImpl(getSecret(), systemBundle, getRootRuntimeBeanRegistratorWrapper());
- }
-}
+++ /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.config.yang.shutdown.impl;
-
-import java.util.Arrays;
-import java.util.Set;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DependencyResolverFactory;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-
-public class ShutdownModuleFactory extends AbstractShutdownModuleFactory {
-
- public ShutdownModule instantiateModule(final String instanceName, final DependencyResolver dependencyResolver,
- final ShutdownModule oldModule, final AutoCloseable oldInstance,
- final BundleContext bundleContext) {
- Bundle systemBundle = bundleContext.getBundle(0);
- return new ShutdownModule(new ModuleIdentifier(NAME, instanceName), oldModule, oldInstance, systemBundle);
- }
-
-
- public ShutdownModule instantiateModule(final String instanceName, final DependencyResolver dependencyResolver,
- final BundleContext bundleContext) {
- Bundle systemBundle = bundleContext.getBundle(0);
- return new ShutdownModule(new ModuleIdentifier(NAME, instanceName), systemBundle);
- }
-
- @Override
- public Set<ShutdownModule> getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, final BundleContext bundleContext) {
- ModuleIdentifier id = new ModuleIdentifier(NAME, NAME);
- DependencyResolver dependencyResolver = dependencyResolverFactory.createDependencyResolver(id);
- ShutdownModule shutdownModule = instantiateModule(NAME, dependencyResolver, bundleContext);
- return new java.util.HashSet<>(Arrays.asList(shutdownModule));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.shutdown.impl;
-
-import com.google.common.base.Optional;
-import java.lang.management.ManagementFactory;
-import java.lang.management.ThreadInfo;
-import org.opendaylight.controller.config.shutdown.ShutdownService;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ShutdownServiceImpl implements ShutdownService, AutoCloseable {
- private final ShutdownService impl;
- private final ShutdownRuntimeRegistration registration;
-
- public ShutdownServiceImpl(final String secret, final Bundle systemBundle,
- final ShutdownRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
- if (secret == null) {
- throw new IllegalArgumentException("Secret cannot be null");
- }
- impl = new Impl(secret, systemBundle);
- registration = rootRuntimeBeanRegistratorWrapper.register(new MXBeanImpl(impl));
- }
-
- @Override
- public void shutdown(final String inputSecret, final Long maxWaitTime, final Optional<String> reason) {
- impl.shutdown(inputSecret, maxWaitTime, reason);
- }
-
- @Override
- public void close() {
- registration.close();
- }
-}
-
-class Impl implements ShutdownService {
- private static final Logger LOG = LoggerFactory.getLogger(Impl.class);
- private final String secret;
- private final Bundle systemBundle;
-
- Impl(final String secret, final Bundle systemBundle) {
- this.secret = secret;
- this.systemBundle = systemBundle;
- }
-
- @Override
- public void shutdown(final String inputSecret, final Long maxWaitTime, final Optional<String> reason) {
- LOG.warn("Shutdown issued with secret {} and reason {}", inputSecret, reason);
- try {
- Thread.sleep(1000); // prevent brute force attack
- } catch (final InterruptedException e) {
- Thread.currentThread().interrupt();
- LOG.warn("Shutdown process interrupted", e);
- }
- if (this.secret.equals(inputSecret)) {
- LOG.info("Server is shutting down");
-
- // actual work:
- Thread stopSystemBundleThread = new StopSystemBundleThread(systemBundle);
- stopSystemBundleThread.start();
- if (maxWaitTime != null && maxWaitTime > 0) {
- Thread systemExitThread = new CallSystemExitThread(maxWaitTime);
- LOG.debug("Scheduling {}", systemExitThread);
- systemExitThread.start();
- }
- // end
- } else {
- LOG.warn("Unauthorized attempt to shut down server");
- throw new IllegalArgumentException("Invalid secret");
- }
- }
-
-}
-
-class StopSystemBundleThread extends Thread {
- private static final Logger LOG = LoggerFactory.getLogger(StopSystemBundleThread.class);
- private final Bundle systemBundle;
-
- StopSystemBundleThread(final Bundle systemBundle) {
- super("stop-system-bundle");
- this.systemBundle = systemBundle;
- }
-
- @Override
- public void run() {
- try {
- // wait so that JMX response is received
- Thread.sleep(1000);
- LOG.debug("Stopping system bundle");
- systemBundle.stop();
- } catch (final BundleException e) {
- LOG.warn("Can not stop OSGi server", e);
- } catch (final InterruptedException e) {
- LOG.warn("Shutdown process interrupted", e);
- }
- }
-}
-
-class CallSystemExitThread extends Thread {
- private static final Logger LOG = LoggerFactory.getLogger(CallSystemExitThread.class);
- private final long maxWaitTime;
- CallSystemExitThread(final long maxWaitTime) {
- super("call-system-exit-daemon");
- setDaemon(true);
- if (maxWaitTime <= 0){
- throw new IllegalArgumentException("Cannot schedule to zero or negative time:" + maxWaitTime);
- }
- this.maxWaitTime = maxWaitTime;
- }
-
- @Override
- public String toString() {
- return "CallSystemExitThread{" +
- "maxWaitTime=" + maxWaitTime +
- '}';
- }
-
- @Override
- public void run() {
- try {
- // wait specified time
- Thread.sleep(maxWaitTime);
- LOG.error("Since some threads are still running, server is going to shut down via System.exit(1) !");
- // do a thread dump
- ThreadInfo[] threads = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);
- StringBuffer sb = new StringBuffer();
- for(ThreadInfo info : threads) {
- sb.append(info);
- sb.append("\n");
- }
- LOG.warn("Thread dump:{}", sb);
- System.exit(1);
- } catch (final InterruptedException e) {
- LOG.warn("Interrupted, not going to call System.exit(1)");
- }
- }
-}
-
-
-class MXBeanImpl implements ShutdownRuntimeMXBean {
- private final ShutdownService impl;
-
- MXBeanImpl(final ShutdownService impl) {
- this.impl = impl;
- }
-
- @Override
- public void shutdown(final String inputSecret, final Long maxWaitTime, final String nullableReason) {
- Optional<String> optionalReason;
- if (nullableReason == null) {
- optionalReason = Optional.absent();
- } else {
- optionalReason = Optional.of(nullableReason);
- }
- impl.shutdown(inputSecret, maxWaitTime, optionalReason);
- }
-}
+++ /dev/null
-module shutdown-impl {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:shutdown:impl";
- prefix "shutdown-impl";
-
- import shutdown { prefix shutdown; revision-date 2013-12-18; }
- import config { prefix config; revision-date 2013-04-05; }
- import rpc-context { prefix rpcx; revision-date 2013-06-17; }
-
- organization "Cisco Systems, Inc.";
-
- description
- "This module contains the base YANG definitions for
- shutdown implementation.
-
- Copyright (c)2013 Cisco Systems, Inc. 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";
-
- revision "2013-12-18" {
- description
- "Initial revision.";
- }
-
- identity shutdown {
- base config:module-type;
- config:provided-service shutdown:shutdown;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case shutdown {
- when "/config:modules/config:module/config:type = 'shutdown'";
- leaf secret {
- type string;
- default "";
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case shutdown {
- when "/config:modules/config:module/config:type = 'shutdown'";
- rpcx:rpc-context-instance "shutdown-rpc";
- }
- }
-
- identity shutdown-rpc;
-
- rpc shutdown {
- input {
- uses rpcx:rpc-context-ref {
- refine context-instance {
- rpcx:rpc-context-instance shutdown-rpc;
- }
- }
- leaf input-secret {
- type string;
- }
- leaf max-wait-time {
- type uint32;
- description "Maximum time in milliseconds before process is forcibly exited. Zero or null cancels this functionality.";
- }
- leaf reason {
- type string;
- }
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.shutdown.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.verify;
-import static org.opendaylight.controller.config.yang.shutdown.impl.ShutdownModuleFactory.NAME;
-
-import java.util.Collections;
-import javax.management.InstanceNotFoundException;
-import javax.management.JMX;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import org.osgi.framework.Bundle;
-
-public class ShutdownTest extends AbstractConfigTest {
- private final ShutdownModuleFactory factory = new ShutdownModuleFactory();
- @Mock
- private Bundle mockedSysBundle;
-
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- ModuleFactoriesResolver factoriesResolver = new HardcodedModuleFactoriesResolver(mockedContext, factory);
- super.initConfigTransactionManagerImpl(factoriesResolver);
- doReturn(mockedSysBundle).when(mockedContext).getBundle(0);
- mockedContext.getBundle(0);
- doNothing().when(mockedSysBundle).stop();
- doReturn(mockedContext).when(mockedSysBundle).getBundleContext();
- doReturn(new Bundle[]{mockedSysBundle}).when(mockedContext).getBundles();
- doReturn("system bundle").when(mockedSysBundle).getSymbolicName();
-
-
-
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- // initialize default instance
- transaction.commit();
- }
-
- @Test
- public void testSingleton_invalidName() throws Exception {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- try {
- transaction.createModule(NAME, "foo");
- fail();
- } catch (final IllegalArgumentException e) {
- assertEquals("Singleton enforcement failed. Expected instance name shutdown", e.getMessage());
- }
- }
-
- private static final ObjectName runtimeON = ObjectNameUtil.createRuntimeBeanName(NAME, NAME, Collections.<String, String>emptyMap());
-
- @Test
- public void testWithoutSecret() throws Exception {
- // test JMX rpc
-
- ShutdownRuntimeMXBean runtime = configRegistryClient.newMXBeanProxy(runtimeON, ShutdownRuntimeMXBean.class);
- try {
- runtime.shutdown("foo", 60000L, null);
- fail();
- } catch (final IllegalArgumentException e) {
- assertEquals("Invalid secret", e.getMessage());
- }
- runtime.shutdown("", 60000L, null);
- assertStopped();
- }
-
-
- @Test
- public void testWithSecret() throws Exception {
- String secret = "secret";
- setSecret(secret);
- shutdownViaRuntimeJMX(secret);
- }
-
- private void setSecret(final String secret) throws InstanceNotFoundException, ValidationException, ConflictingVersionException {
- ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
- ObjectName on = transaction.lookupConfigBean(NAME, NAME);
- ShutdownModuleMXBean proxy = transaction.newMXBeanProxy(on, ShutdownModuleMXBean.class);
- proxy.setSecret(secret);
- transaction.commit();
- }
-
- @Test
- public void testWrongSecret() throws Exception {
- setSecret("secret");
- try {
- ShutdownRuntimeMXBean runtime = JMX.newMXBeanProxy(platformMBeanServer, runtimeON, ShutdownRuntimeMXBean.class);
- runtime.shutdown("foo", 60000L, null);
- fail();
- } catch (final IllegalArgumentException e) {
- assertEquals("Invalid secret", e.getMessage());
- }
- }
-
- private void shutdownViaRuntimeJMX(final String secret) throws Exception {
- // test JMX rpc
- ShutdownRuntimeMXBean runtime = JMX.newMXBeanProxy(platformMBeanServer, runtimeON, ShutdownRuntimeMXBean.class);
- try {
- runtime.shutdown("", 60000L, null);
- fail();
- } catch (final IllegalArgumentException e) {
- assertEquals("Invalid secret", e.getMessage());
- }
- runtime.shutdown(secret, 60000L, null);
- assertStopped();
- }
-
- private void assertStopped() throws Exception {
- Thread.sleep(3000); // happens on another thread
- verify(mockedSysBundle).stop();
- }
-}
+++ /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>config-subsystem</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- </parent>
-
- <artifactId>yang-jmx-generator-it</artifactId>
- <name>${project.artifactId}</name>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-api</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-manager</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-manager</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-util</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>yang-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.it;
-
-import static org.junit.Assert.fail;
-
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.ObjectName;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
-import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
-import org.opendaylight.controller.config.yang.test.impl.DtoA;
-import org.opendaylight.controller.config.yang.test.impl.DtoB;
-import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
-import org.opendaylight.controller.config.yang.test.impl.TestImplModuleMXBean;
-
-@Ignore
-// ietf beans are not JMX compliant beans:
-// Do not know how to make a
-// org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev2010924.AsNumber
-// from a CompositeData: no method from(CompositeData); no constructor has
-// @ConstructorProperties annotation; does not have a public no-arg constructor;
-// not an interface
-public class ITTest extends AbstractConfigTest {
-
- private TestImplModuleFactory factory;
- private final String instanceName = "instance";
-
- @Before
- public void setUp() {
-
- factory = new TestImplModuleFactory();
- super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,
- factory));
- }
-
- @Test
- public void testCreateBean() throws InstanceAlreadyExistsException,
- ValidationException, ConflictingVersionException {
- ConfigTransactionJMXClient transaction = configRegistryClient
- .createTransaction();
-
- createModule(transaction, instanceName);
- transaction.validateConfig();
- CommitStatus status = transaction.commit();
-
- assertBeanCount(1, factory.getImplementationName());
- assertStatus(status, 1, 0, 0);
- }
-
- @Test
- public void testReusingOldInstance() throws InstanceAlreadyExistsException,
- ConflictingVersionException, ValidationException {
-
- ConfigTransactionJMXClient transaction = configRegistryClient
- .createTransaction();
- createModule(transaction, instanceName);
-
- transaction.commit();
-
- assertBeanCount(1, factory.getImplementationName());
-
- transaction = configRegistryClient.createTransaction();
- CommitStatus status = transaction.commit();
-
- assertBeanCount(1, factory.getImplementationName());
- assertStatus(status, 0, 0, 1);
-
- }
-
- @Test
- public void testInstanceAlreadyExistsException()
- throws ConflictingVersionException, ValidationException,
- InstanceAlreadyExistsException {
- ConfigTransactionJMXClient transaction = configRegistryClient
- .createTransaction();
-
- createModule(transaction, instanceName);
- transaction.commit();
-
- transaction = configRegistryClient.createTransaction();
- try {
- createModule(transaction, instanceName);
- fail();
- } catch (InstanceAlreadyExistsException e) {
-
- }
- }
-
- private ObjectName createModule(ConfigTransactionJMXClient transaction,
- String instanceName) throws InstanceAlreadyExistsException {
- ObjectName nameCreated = transaction.createModule(
- factory.getImplementationName(), instanceName);
- TestImplModuleMXBean mxBean = transaction.newMBeanProxy(nameCreated,
- TestImplModuleMXBean.class);
- mxBean.setSimpleInt((long) 45);
- // mxBean.setAsNumber(new AsNumber((long) 999));
- mxBean.setDtoA(new DtoA());
- mxBean.setDtoB(new DtoB());
- return nameCreated;
-
- }
-
-}
+++ /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>config-subsystem</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>..</relativePath>
- </parent>
- <artifactId>yang-jmx-generator-plugin</artifactId>
-
- <dependencies>
-
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-api</artifactId>
- </dependency>
-
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-binding-generator-impl</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-maven-plugin-spi</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.maven</groupId>
- <artifactId>maven-core</artifactId>
- <version>3.1.1</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
-
- <dependency>
- <groupId>net.sourceforge.pmd</groupId>
- <artifactId>pmd</artifactId>
- <version>5.1.0</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>com.github.javaparser</groupId>
- <artifactId>javaparser-core</artifactId>
- <version>2.3.0</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-test-util</artifactId>
- </dependency>
-
- </dependencies>
-
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.GeneralClassTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.GeneralInterfaceTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.RuntimeRegistratorFtlTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.StubFactoryTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.AbsFactoryGeneratedObjectFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.AbsModuleGeneratedObjectFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.ConcreteModuleGeneratedObjectFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.GenericGeneratedObjectFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-final class CodeWriter {
-
- private static final Logger LOG = LoggerFactory.getLogger(CodeWriter.class);
- private static final Optional<String> COPYRIGHT = StringUtil.loadCopyright();
-
- public File writeSie(final ServiceInterfaceEntry sie, final File outputBaseDir) {
- try {
- GeneralInterfaceTemplate generalInterfaceTemplate = TemplateFactory.serviceInterfaceFromSie(sie);
- GeneratedObject go = new GenericGeneratedObjectFactory().toGeneratedObject(generalInterfaceTemplate, COPYRIGHT);
- return go.persist(outputBaseDir).get().getValue();
- } catch (Exception e) {
- String message = "An error occurred during Service interface generating, sie:"
- + sie.getTypeName() + ", " + sie.getFullyQualifiedName();
- LOG.error(message, e);
- throw new RuntimeException(message, e);
- }
- }
-
- public List<File> writeMbe(final ModuleMXBeanEntry mbe, final File targetBaseDir,
- final File mainBaseDir) {
- try {
- List<File> generatedFiles = Lists.newArrayList();
-
-
- Map<GeneratedObject, Boolean /*overwrite*/> gos = new HashMap<>();
-
- // generate mx interface and abstract factory
-
- // TOs
- Map<String,GeneralClassTemplate> tosFromMbe = TemplateFactory.tOsFromMbe(mbe);
- for(GeneralClassTemplate template: tosFromMbe.values()) {
- gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(template, COPYRIGHT), true);
- }
-
- // MXBean interface
- GeneralInterfaceTemplate ifcTemplate = TemplateFactory.mXBeanInterfaceTemplateFromMbe(mbe);
- gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(ifcTemplate, COPYRIGHT), true);
-
-
- // generate abstract factory
- gos.put(new AbsFactoryGeneratedObjectFactory().toGeneratedObject(mbe, COPYRIGHT), true);
-
- // generate abstract module
- gos.put(new AbsModuleGeneratedObjectFactory().toGeneratedObject(mbe, COPYRIGHT), true);
-
- // generate concrete factory
- StubFactoryTemplate concreteFactory = TemplateFactory.stubFactoryTemplateFromMbe(mbe);
- gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(concreteFactory, COPYRIGHT), false);
-
-
- // generate concrete module
-
- gos.put(new ConcreteModuleGeneratedObjectFactory().toGeneratedObject(mbe, COPYRIGHT, Optional.<String>absent()), false);
-
- // write runtime bean MXBeans and registrators
- List<FtlTemplate> allFtlFiles = getRuntimeBeanFtlTemplates(mbe.getRuntimeBeans());
- for(FtlTemplate template: allFtlFiles) {
- gos.put(new GenericGeneratedObjectFactory().toGeneratedObject(template, COPYRIGHT), true);
- }
-
- generatedFiles.addAll(persistGeneratedObjects(targetBaseDir, mainBaseDir, gos));
-
- // purge nulls
- for (Iterator<File> it = generatedFiles.iterator(); it.hasNext(); ) {
- if (it.next() == null) {
- it.remove();
- }
- }
-
- return generatedFiles;
-
- } catch (Exception e) {
- String message = "An error occurred during Module generating, mbe:"
- + mbe.getJavaNamePrefix();
- LOG.error(message, e);
- throw new RuntimeException(message, e);
- }
- }
-
- private static List<File> persistGeneratedObjects(final File targetBaseDir, final File mainBaseDir,
- final Map<GeneratedObject, Boolean> gos) throws IOException {
- List<File> generatedFiles = new ArrayList<>();
- for (Entry<GeneratedObject, Boolean> entry : gos.entrySet()) {
- boolean overwrite = entry.getValue();
- File dst;
- if (overwrite) {
- dst = targetBaseDir;
- } else {
- dst = mainBaseDir;
- }
- Optional<Entry<FullyQualifiedName, File>> maybePersistEntry = entry.getKey().persist(dst, overwrite);
-
- if (maybePersistEntry.isPresent()) {
- generatedFiles.add(maybePersistEntry.get().getValue());
- }
- }
- return generatedFiles;
- }
-
- private static List<FtlTemplate> getRuntimeBeanFtlTemplates(final Collection<RuntimeBeanEntry> runtimeBeans) {
- if (runtimeBeans.isEmpty()) {
- return Collections.emptyList();
- }
- List<FtlTemplate> allFtlFiles = new ArrayList<>();
- { // registrators
- Map<String, FtlTemplate> registratorNamesToFtls = RuntimeRegistratorFtlTemplate
- .create(RuntimeRegistratorFtlTemplate.findRoot(runtimeBeans));
-
- allFtlFiles.addAll(registratorNamesToFtls.values());
- }
- { // TOs, MXBean interfaces
- for (RuntimeBeanEntry runtimeBeanEntry : runtimeBeans) {
- Collection<FtlTemplate> ftlFiles = TemplateFactory
- .getTOAndMXInterfaceFtlFiles(runtimeBeanEntry)
- .values();
- allFtlFiles.addAll(ftlFiles);
- }
- }
- return allFtlFiles;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
-import com.google.common.io.Files;
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import org.apache.maven.project.MavenProject;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
-import org.opendaylight.mdsal.binding.yang.types.TypeProviderImpl;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
-import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This class interfaces with yang-maven-plugin. Gets parsed yang modules in
- * {@link SchemaContext}, and parameters form the plugin configuration, and
- * writes service interfaces and/or modules.
- */
-public class JMXGenerator implements BasicCodeGenerator, MavenProjectAware {
- private static final class NamespaceMapping {
- private final String namespace, packageName;
-
- public NamespaceMapping(final String namespace, final String packagename) {
- this.namespace = namespace;
- this.packageName = packagename;
- }
- }
-
- @VisibleForTesting
- static final String NAMESPACE_TO_PACKAGE_DIVIDER = "==";
- @VisibleForTesting
- static final String NAMESPACE_TO_PACKAGE_PREFIX = "namespaceToPackage";
- @VisibleForTesting
- static final String MODULE_FACTORY_FILE_BOOLEAN = "moduleFactoryFile";
-
- private static final Logger LOG = LoggerFactory.getLogger(JMXGenerator.class);
- private static final Pattern NAMESPACE_MAPPING_PATTERN = Pattern.compile("(.+)" + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
-
- private final CodeWriter codeWriter;
- private Map<String, String> namespaceToPackageMapping;
- private File resourceBaseDir;
- private File projectBaseDir;
- private boolean generateModuleFactoryFile = true;
-
- public JMXGenerator() {
- this(new CodeWriter());
- }
-
- public JMXGenerator(final CodeWriter codeWriter) {
- this.codeWriter = codeWriter;
- }
-
- @Override
- public Collection<File> generateSources(final SchemaContext context, final File outputBaseDir,
- final Set<Module> currentModules, final Function<Module, Optional<String>> moduleResourcePathResolver) {
-
- Preconditions.checkArgument(context != null, "Null context received");
- Preconditions.checkArgument(outputBaseDir != null,
- "Null outputBaseDir received");
-
- Preconditions
- .checkArgument(this.namespaceToPackageMapping != null && !this.namespaceToPackageMapping.isEmpty(),
- "No namespace to package mapping provided in additionalConfiguration");
-
- final PackageTranslator packageTranslator = new PackageTranslator(this.namespaceToPackageMapping);
-
- if (!outputBaseDir.exists()) {
- outputBaseDir.mkdirs();
- }
-
- final GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker();
- // create SIE structure qNamesToSIEs
- final Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>();
-
-
- final Map<IdentitySchemaNode, ServiceInterfaceEntry> knownSEITracker = new HashMap<>();
- for (final Module module : context.getModules()) {
- final String packageName = packageTranslator.getPackageName(module);
- final Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry
- .create(module, packageName, knownSEITracker);
-
- for (final Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries
- .entrySet()) {
- // merge value into qNamesToSIEs
- if (qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue()) != null) {
- throw new IllegalStateException(
- "Cannot add two SIE with same qname "
- + sieEntry.getValue());
- }
- }
- if (currentModules.contains(module)) {
- // write this sie to disk
- for (final ServiceInterfaceEntry sie : namesToSIEntries.values()) {
- try {
- generatedFiles.addFile(this.codeWriter.writeSie(sie,
- outputBaseDir));
- } catch (final Exception e) {
- throw new RuntimeException(
- "Error occurred during SIE source generate phase",
- e);
- }
- }
- }
- }
-
- final File mainBaseDir = concatFolders(this.projectBaseDir, "src", "main", "java");
- Preconditions.checkNotNull(this.resourceBaseDir,
- "resource base dir attribute was null");
-
- final StringBuilder fullyQualifiedNamesOfFactories = new StringBuilder();
- // create MBEs
- for (final Module module : currentModules) {
- final String packageName = packageTranslator.getPackageName(module);
- final Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
- .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)),
- packageName);
-
- for (final Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs
- .entrySet()) {
- final ModuleMXBeanEntry mbe = mbeEntry.getValue();
- try {
- final List<File> files1 = this.codeWriter.writeMbe(mbe, outputBaseDir,
- mainBaseDir);
- generatedFiles.addFile(files1);
- } catch (final Exception e) {
- throw new RuntimeException(
- "Error occurred during MBE source generate phase",
- e);
- }
- fullyQualifiedNamesOfFactories.append(mbe
- .getFullyQualifiedName(mbe.getStubFactoryName()));
- fullyQualifiedNamesOfFactories.append("\n");
- }
- }
- // create ModuleFactory file if needed
- if (fullyQualifiedNamesOfFactories.length() > 0
- && this.generateModuleFactoryFile) {
- final File serviceLoaderFile = JMXGenerator.concatFolders(
- this.resourceBaseDir, "META-INF", "services",
- ModuleFactory.class.getName());
- // if this file does not exist, create empty file
- serviceLoaderFile.getParentFile().mkdirs();
- try {
- serviceLoaderFile.createNewFile();
- Files.asCharSink(serviceLoaderFile, StandardCharsets.UTF_8).write(
- fullyQualifiedNamesOfFactories.toString());
- } catch (final IOException e) {
- final String message = "Cannot write to " + serviceLoaderFile;
- LOG.error(message, e);
- throw new RuntimeException(message, e);
- }
- }
- return generatedFiles.getFiles();
- }
-
- @VisibleForTesting
- static File concatFolders(final File projectBaseDir, final String... folderNames) {
- File result = projectBaseDir;
- for (final String folder: folderNames) {
- result = new File(result, folder);
- }
- return result;
- }
-
- @Override
- public void setAdditionalConfig(final Map<String, String> additionalCfg) {
- LOG.debug("{}: Additional configuration received: {}", getClass().getCanonicalName(), additionalCfg);
- this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg);
- this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg);
- }
-
- private static boolean extractModuleFactoryBoolean(final Map<String, String> additionalCfg) {
- final String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
- return !"false".equals(bool);
- }
-
- private static Map<String, String> extractNamespaceMapping(
- final Map<String, String> additionalCfg) {
- final Map<String, String> namespaceToPackage = new HashMap<>();
- for (final String key : additionalCfg.keySet()) {
- if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) {
- final String mapping = additionalCfg.get(key);
- final NamespaceMapping mappingResolved = extractNamespaceMapping(mapping);
- namespaceToPackage.put(mappingResolved.namespace,
- mappingResolved.packageName);
- }
- }
- return namespaceToPackage;
- }
-
- private static NamespaceMapping extractNamespaceMapping(final String mapping) {
- final Matcher matcher = NAMESPACE_MAPPING_PATTERN.matcher(mapping);
- Preconditions.checkArgument(matcher.matches(),
- "Namespace to package mapping:%s is in invalid format, requested format is: %s",
- mapping, NAMESPACE_MAPPING_PATTERN);
- return new NamespaceMapping(matcher.group(1), matcher.group(2));
- }
-
- @Override
- public void setResourceBaseDir(final File resourceDir) {
- this.resourceBaseDir = resourceDir;
- }
-
- @Override
- public void setMavenProject(final MavenProject project) {
- this.projectBaseDir = project.getBasedir();
- LOG.debug("{}: project base dir: {}", getClass().getCanonicalName(), this.projectBaseDir);
- }
-
- @VisibleForTesting
- static class GeneratedFilesTracker {
- private final Set<File> files = new HashSet<>();
-
- void addFile(final File file) {
- if (this.files.contains(file)) {
- final List<File> undeletedFiles = new ArrayList<>();
- for (final File presentFile : this.files) {
- if (!presentFile.delete()) {
- undeletedFiles.add(presentFile);
- }
- }
- if (!undeletedFiles.isEmpty()) {
- LOG.error("Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
- undeletedFiles);
- }
- throw new IllegalStateException("Name conflict in generated files, file" + file + " present twice");
- }
- this.files.add(file);
- }
-
- void addFile(final Collection<File> files) {
- for (final File file : files) {
- addFile(file);
- }
- }
-
- public Set<File> getFiles() {
- return this.files;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import com.google.common.collect.Lists;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
-
-public class AbstractFactoryTemplate extends GeneralClassTemplate {
-
- private static final List<String> IMPLEMENTED_IFCS = Lists
- .newArrayList(ModuleFactory.class.getCanonicalName());
-
- public AbstractFactoryTemplate(Header header, String packageName,
- String abstractFactoryName,
- List<Field> fields) {
- super(header, packageName, abstractFactoryName, Collections
- .<String> emptyList(), IMPLEMENTED_IFCS, fields, Collections
- .<MethodDefinition> emptyList(), true, false, Collections
- .<Constructor> emptyList());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Method;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.TypeDeclaration;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
-
-public abstract class AbstractFtlTemplate implements FtlTemplate {
- private final String packageName;
- private final List<Field> fields;
- private final List<Annotation> annotations;
- private final List<? extends Method> methods;
- private String javadoc = null;
- private final TypeDeclaration typeDeclaration;
- private final Header header;
-
- protected AbstractFtlTemplate(Header header, String packageName,
- List<Field> fields, List<? extends Method> methods,
- TypeDeclaration typeDeclaration) {
- this.packageName = packageName;
- this.fields = fields;
- this.methods = methods;
- this.annotations = Lists.newArrayList();
- this.typeDeclaration = typeDeclaration;
- this.header = header;
- }
-
- @Override
- public Header getHeader() {
- return header;
- }
-
- @Override
- public Optional<String> getHeaderString() {
- if (header == null) {
- return Optional.absent();
- } else {
- return Optional.of(header.toString());
- }
- }
-
- @Override
- public String getFullyQualifiedName() {
- return FullyQualifiedNameHelper.getFullyQualifiedName(getPackageName(),
- getTypeDeclaration().getName());
- }
-
- @Override
- public String getPackageName() {
- return packageName;
- }
-
- @Override
- public TypeDeclaration getTypeDeclaration() {
- return typeDeclaration;
- }
-
-
- @Override
- public Optional<String> getMaybeJavadoc() {
- if (javadoc == null) {
- return Optional.absent();
- } else {
- return Optional.of(javadoc);
- }
- }
-
- public void setJavadoc(String javadoc) {
- this.javadoc = javadoc;
- }
-
- @Override
- public List<Annotation> getAnnotations() {
- return annotations;
- }
-
- @Override
- public List<Field> getFields() {
- return fields;
- }
-
- @Override
- public List<? extends Method> getMethods() {
- return methods;
- }
-
-
- @Override
- public List<Constructor> getConstructors() {
- return Collections.emptyList();
- }
-
- @Override
- public String toString() {
- return "AbstractFtlTemplate{" + "typeDeclaration=" + typeDeclaration
- + ", packageName='" + packageName + '\'' + '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.ModuleField;
-
-public class AbstractModuleTemplate extends GeneralClassTemplate {
-
- private final List<ModuleField> moduleFields;
- private final boolean runtime;
- private final String registratorType;
-
- public AbstractModuleTemplate(Header header, String packageName,
- String abstractModuleName, List<String> extendedClasses,
- List<String> implementedIfcs, List<ModuleField> moduleFields, List<MethodDefinition> methods,
- boolean isRuntime, String registratorType) {
- super(header, packageName, abstractModuleName, extendedClasses,
- implementedIfcs, Collections.<Field> emptyList(), methods,
- true, false, Collections.<Constructor> emptyList());
- this.moduleFields = moduleFields;
- this.runtime = isRuntime;
- this.registratorType = registratorType;
- }
-
- public List<ModuleField> getModuleFields() {
- return moduleFields;
- }
-
- public String getRegistratorType() {
- return registratorType;
- }
-
- public boolean isRuntime() {
- return runtime;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import com.google.common.base.Optional;
-import java.util.List;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Method;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.TypeDeclaration;
-
-public interface FtlTemplate {
-
- Header getHeader();
- Optional<String> getHeaderString();
-
- String getPackageName();
-
- Optional<String> getMaybeJavadoc();
-
- List<Annotation> getAnnotations();
-
- TypeDeclaration getTypeDeclaration();
-
- String getFullyQualifiedName();
-
- List<Field> getFields();
-
- List<? extends Method> getMethods();
-
- List<Constructor> getConstructors();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.TypeDeclaration;
-
-public class GeneralClassTemplate extends AbstractFtlTemplate {
-
- private final List<Constructor> constructors;
-
- public GeneralClassTemplate(Header header, String packageName, String name,
- List<String> extendedClasses, List<String> implementedIfcs,
- List<Field> fields, List<MethodDefinition> methods) {
- this(header, packageName, name, extendedClasses, implementedIfcs,
- fields, methods, false, false, Collections
- .<Constructor> emptyList());
- }
-
- public GeneralClassTemplate(Header header, String packageName, String name,
- List<String> extendedClasses, List<String> implementedIfcs,
- List<Field> fields, List<MethodDefinition> methods,
- boolean isAbstract, boolean isFinal, List<Constructor> constructors) {
- super(header, packageName, fields, methods, new TypeDeclaration(
- "class", name, checkCardinality(extendedClasses),
- implementedIfcs, isAbstract, isFinal));
- this.constructors = constructors;
- }
-
- static List<String> checkCardinality(List<String> extendedClass) {
- if (extendedClass.size() > 1) {
- throw new IllegalArgumentException(
- "Class cannot have more than one super class, found: " + extendedClass);
- }
- return extendedClass;
- }
-
- public List<Constructor> getConstructors() {
- return constructors;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDeclaration;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.TypeDeclaration;
-
-public class GeneralInterfaceTemplate extends AbstractFtlTemplate {
-
- public GeneralInterfaceTemplate(Header header, String packageName,
- String name, List<String> extendedInterfaces,
- List<MethodDeclaration> methods) {
- super(header, packageName, Collections.<Field> emptyList(), methods,
- new TypeDeclaration("interface", name, extendedInterfaces,
- Collections.<String> emptyList()));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkState;
-import static java.lang.String.format;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-import java.io.Closeable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
-import javax.lang.model.element.Modifier;
-import org.opendaylight.controller.config.api.runtime.HierarchicalRuntimeBeanRegistration;
-import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
-
-public class RuntimeRegistratorFtlTemplate extends GeneralClassTemplate {
-
- private RuntimeRegistratorFtlTemplate(RuntimeBeanEntry runtimeBeanEntry,
- String name, List<Field> fields, List<MethodDefinition> methods) {
- // TODO header
- super(null, runtimeBeanEntry.getPackageName(), name, Collections
- .emptyList(), Collections.singletonList(Closeable.class
- .getCanonicalName()), fields, methods);
- }
-
- public static RuntimeBeanEntry findRoot(
- Collection<RuntimeBeanEntry> runtimeBeanEntries) {
- RuntimeBeanEntry result = null;
- for (RuntimeBeanEntry rb : runtimeBeanEntries) {
- if (rb.isRoot()) {
- if (result != null) {
- throw new IllegalArgumentException(
- "More than one root runtime bean found");
- }
- result = rb;
- }
- }
- if (result != null) {
- return result;
- }
- throw new IllegalArgumentException("No root runtime bean found");
- }
-
- private static String constructConstructorBody(
- List<Field> constructorParameters) {
- StringBuilder constructorBody = new StringBuilder();
- for (Field field : constructorParameters) {
- constructorBody.append("this.");
- constructorBody.append(field.getName());
- constructorBody.append("=");
- constructorBody.append(field.getName());
- constructorBody.append(";\n");
- }
- return constructorBody.toString();
- }
-
- // TODO Move to factory
- /**
- * Get registrator and n registration ftls where n is equal to total number
- * of runtime beans in hierarchy.
- */
- public static Map<String, FtlTemplate> create(RuntimeBeanEntry rootRB) {
- checkArgument(rootRB.isRoot(), "RuntimeBeanEntry must be root");
- String registratorName = getJavaNameOfRuntimeRegistrator(rootRB);
- List<MethodDefinition> methods = new ArrayList<>();
- Field rootRuntimeBeanRegistratorField = new Field(
- Collections.singletonList(Modifier.FINAL),
- RootRuntimeBeanRegistrator.class.getName(),
- "rootRuntimeBeanRegistrator");
- List<Field> constructorParameters = Lists
- .newArrayList(rootRuntimeBeanRegistratorField);
- String constructorBody = constructConstructorBody(constructorParameters);
- MethodDefinition constructor = MethodDefinition.createConstructor(
- registratorName, constructorParameters, constructorBody);
- methods.add(constructor);
-
- LinkedHashMap<String, RuntimeRegistratorFtlTemplate> RuntimeRegistratorFtlTemplates =
- createRegistrationHierarchy(rootRB, Collections.emptySet());
- RuntimeRegistratorFtlTemplate rootFtlFile = RuntimeRegistratorFtlTemplates
- .values().iterator().next();
-
- {// add register(rootruntimemxbean)
- String fullyQualifiedNameOfMXBean = FullyQualifiedNameHelper
- .getFullyQualifiedName(rootRB.getPackageName(), rootRB.getJavaNameOfRuntimeMXBean());
- String childRegistratorFQN = rootFtlFile.getFullyQualifiedName();
- Field rbParameter = new Field(fullyQualifiedNameOfMXBean, "rb");
- String registerBody = format("%s %s = this.%s.registerRoot(%s);\n"
- + "return new %s(%2$s);\n",
- HierarchicalRuntimeBeanRegistration.class.getCanonicalName(),
- hierachicalRegistration.getName(),
- rootRuntimeBeanRegistratorField.getName(),
- rbParameter.getName(),
- rootFtlFile.getFullyQualifiedName());
-
- MethodDefinition registerMethod = new MethodDefinition(
- childRegistratorFQN, "register",
- Collections.singletonList(rbParameter), registerBody);
- methods.add(registerMethod);
- }
-
- MethodDefinition closeRegistrator = createCloseMethodToCloseField(rootRuntimeBeanRegistratorField);
- methods.add(closeRegistrator);
-
- // TODO add header
- GeneralClassTemplate registrator = new GeneralClassTemplate(null,
- rootRB.getPackageName(), registratorName,
- Collections.emptyList(), Collections.singletonList(Closeable.class
- .getCanonicalName()), constructorParameters, methods);
-
- checkState(!RuntimeRegistratorFtlTemplates.containsKey(registrator
- .getTypeDeclaration().getName()), "Name conflict: "
- + registrator.getTypeDeclaration().getName());
- Map<String, FtlTemplate> result = new HashMap<>();
- result.putAll(RuntimeRegistratorFtlTemplates);
- result.put(registrator.getTypeDeclaration().getName(), registrator);
- return result;
- }
-
- private static Field hierachicalRegistration = new Field(
- Collections.singletonList(Modifier.FINAL),
- HierarchicalRuntimeBeanRegistration.class.getCanonicalName(),
- "registration");
-
- // TODO move to factory + RuntimeBeanEntry
- /**
- * Create ftls representing registrations. First registration is represents
- * parent.
- *
- * @return map containing java class name as key, instance representing the
- * java file as value.
- */
- private static LinkedHashMap<String, RuntimeRegistratorFtlTemplate> createRegistrationHierarchy(
- RuntimeBeanEntry parent, Set<String> occupiedKeys) {
- LinkedHashMap<String, RuntimeRegistratorFtlTemplate> unorderedResult = new LinkedHashMap<>();
- List<MethodDefinition> methods = new ArrayList<>();
-
- // hierarchy of ON is created as follows:
- // root RB: <domain>, type=RuntimeBean
- // 1st RB in hierarchy: <domain>, type=RuntimeBean, <java name of leaf
- // list>: key or counter
- // n-th RB in hierarchy has same ON as n-1, with added <java name of
- // leaf list>: key or counter
- if (occupiedKeys.contains(parent.getJavaNamePrefix())) {
- throw new IllegalArgumentException(
- "Name conflict in runtime bean hierarchy - java name found more than "
- + "once. Consider using java-name extension. Conflicting name: "
- + parent.getJavaNamePrefix());
- }
- Set<String> currentOccupiedKeys = new HashSet<>(occupiedKeys);
- currentOccupiedKeys.add(parent.getJavaNamePrefix());
-
- Field registratorsMapField = new Field(Collections.singletonList(Modifier.FINAL),
- TypeHelper.getGenericType(Map.class, String.class,
- AtomicInteger.class), "unkeyedMap", "new "
- + TypeHelper.getGenericType(HashMap.class,
- String.class, AtomicInteger.class) + "()");
-
- // create register methods for children
- for (RuntimeBeanEntry child : parent.getChildren()) {
- checkArgument(parent.getPackageName()
- .equals(child.getPackageName()), "Invalid package name");
-
- // call itself recursively to generate child
- // registrators/registrations
- LinkedHashMap<String, RuntimeRegistratorFtlTemplate> childRegistratorMap = createRegistrationHierarchy(
- child, currentOccupiedKeys);
- for (Entry<String, RuntimeRegistratorFtlTemplate> entry : childRegistratorMap
- .entrySet()) {
- if (unorderedResult.containsKey(entry.getKey())) {
- throw new IllegalStateException(
- "Conflicting name found while generating runtime registration:"
- + entry.getKey());
- }
- unorderedResult.put(entry.getKey(), entry.getValue());
- }
-
- if (!childRegistratorMap.isEmpty()) {
- // first entry is the direct descendant according to the create
- // contract
- RuntimeRegistratorFtlTemplate childRegistrator = childRegistratorMap
- .values().iterator().next();
- StringBuilder body = new StringBuilder();
- String key, value;
- key = child.getJavaNamePrefix();
- body.append(format(
- "String key = \"%s\"; //TODO: check for conflicts\n",
- key));
-
- Optional<String> childKeyJavaName = child.getKeyJavaName();
- if (childKeyJavaName.isPresent()) {
- value = "bean.get" + childKeyJavaName.get() + "()";
- value = "String.valueOf(" + value + ")";
- } else {
- body.append("java.util.concurrent.atomic.AtomicInteger counter = unkeyedMap.get(key);\n"
- + "if (counter==null){\n"
- + "counter = new java.util.concurrent.atomic.AtomicInteger();\n"
- + "unkeyedMap.put(key, counter);\n" + "}\n");
- value = "String.valueOf(counter.incrementAndGet())";
- }
- body.append(format("String value = %s;\n", value));
- body.append(format("%s r = %s.register(key, value, bean);\n",
- HierarchicalRuntimeBeanRegistration.class
- .getCanonicalName(), hierachicalRegistration
- .getName()));
- body.append(format("return new %s(r);",
- childRegistrator.getFullyQualifiedName()));
-
- Field param = new Field(Collections.singletonList(Modifier.FINAL),
- child.getJavaNameOfRuntimeMXBean(), "bean");
- MethodDefinition register = new MethodDefinition(
- Collections.singletonList(Modifier.SYNCHRONIZED),
- childRegistrator.getFullyQualifiedName(), "register",
- Collections.singletonList(param), Collections.emptyList(),
- Collections.emptyList(), body.toString());
- methods.add(register);
-
- }
- }
-
- // create parent registration
- String createdName = getJavaNameOfRuntimeRegistration(parent.getJavaNamePrefix());
-
- List<Field> constructorParameters = Collections.singletonList(hierachicalRegistration);
- String constructorBody = constructConstructorBody(constructorParameters);
-
- MethodDefinition constructor = MethodDefinition.createConstructor(
- createdName, constructorParameters, constructorBody);
-
- MethodDefinition closeRegistrator = createCloseMethodToCloseField(hierachicalRegistration);
- methods.add(closeRegistrator);
- methods.add(constructor);
- List<Field> privateFields = Lists.newArrayList(registratorsMapField);
- privateFields.addAll(constructorParameters);
-
- RuntimeRegistratorFtlTemplate created = new RuntimeRegistratorFtlTemplate(
- parent, createdName, privateFields, methods);
-
- LinkedHashMap<String, RuntimeRegistratorFtlTemplate> result = new LinkedHashMap<>();
- result.put(created.getTypeDeclaration().getName(), created);
- checkState(!unorderedResult.containsKey(created.getTypeDeclaration()
- .getName()), "Naming conflict: "
- + created.getTypeDeclaration().getName());
- result.putAll(unorderedResult);
- return result;
- }
-
- private static MethodDefinition createCloseMethodToCloseField(Field field) {
- String body = field.getName() + ".close();";
- // TODO Thrown exception breaks build
- // return new MethodDefinition(Collections.<String> emptyList(), "void",
- // "close", Collections.<Field> emptyList(),
- // Arrays.asList(IOException.class.getCanonicalName()),
- // Collections.<Annotation> emptyList(), body);
- List<Annotation> annotations = Lists.newArrayList(new Annotation(
- "Override", Collections.emptyList()));
- return new MethodDefinition(Collections.emptyList(), "void",
- "close", Collections.emptyList(),
- Collections.emptyList(), annotations, body);
- }
-
- @VisibleForTesting
- public static String getJavaNameOfRuntimeRegistration(String javaNamePrefix) {
- return javaNamePrefix + "RuntimeRegistration";
- }
-
- public static String getJavaNameOfRuntimeRegistrator(RuntimeBeanEntry rootRB) {
- checkArgument(rootRB.isRoot(), "RuntimeBeanEntry must be root");
- return rootRB.getJavaNamePrefix() + "RuntimeRegistrator";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import com.google.common.collect.Lists;
-import java.util.Collections;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
-
-public class StubFactoryTemplate extends GeneralClassTemplate {
-
- public StubFactoryTemplate(Header header, String packageName, String name,
- String extendedClass) {
- super(header, packageName, name, Lists.newArrayList(extendedClass),
- Collections.<String> emptyList(), Collections
- .<Field> emptyList(), Collections
- .<MethodDefinition> emptyList());
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.IdentityAttributeRef;
-import org.opendaylight.controller.config.api.RuntimeBeanRegistratorAwareModule;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.api.runtime.RuntimeBean;
-import org.opendaylight.controller.config.spi.AbstractModule;
-import org.opendaylight.controller.config.yangjmxgenerator.AbstractEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry.Rpc;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AbstractDependencyAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.Dependency;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TypedAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.VoidAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation.Parameter;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.IdentityRefModuleField;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDeclaration;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.ModuleField;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
-import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
-import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
-import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.yangtools.yang.binding.BindingMapping;
-
-public class TemplateFactory {
-
- /**
- * Get map of file name as key, FtlFile instance representing runtime mx
- * bean as value that should be persisted from this instance.
- */
- public static Map<String, FtlTemplate> getTOAndMXInterfaceFtlFiles(
- final RuntimeBeanEntry entry) {
- final Map<String, FtlTemplate> result = new HashMap<>();
- { // create GeneralInterfaceFtlFile for runtime MXBean. Attributes will
- // be transformed to getter methods
- final String mxBeanTypeName = entry.getJavaNameOfRuntimeMXBean();
- final List<String> extendedInterfaces = Collections.singletonList(RuntimeBean.class
- .getCanonicalName());
- final List<MethodDeclaration> methods = new ArrayList<>();
-
- // convert attributes to getters
- for (final AttributeIfc attributeIfc : entry.getAttributes()) {
- String returnType;
- returnType = getReturnType(attributeIfc);
- final String getterName = "get"
- + attributeIfc.getUpperCaseCammelCase();
- final MethodDeclaration getter = new MethodDeclaration(returnType,
- getterName, Collections.<Field> emptyList());
- methods.add(getter);
- }
-
- // add rpc methods
- for (final Rpc rpc : entry.getRpcs()) {
- // convert JavaAttribute parameters into fields
- final List<Field> fields = new ArrayList<>();
- for (final JavaAttribute ja : rpc.getParameters()) {
- final Field field = new Field(Collections.emptyList(),
- ja.getType().getFullyQualifiedName(),
- ja.getLowerCaseCammelCase(), ja.getNullableDefaultWrappedForCode());
- fields.add(field);
- }
- final MethodDeclaration operation = new MethodDeclaration(
- getReturnType(rpc.getReturnType()), rpc.getName(), fields);
- methods.add(operation);
- }
-
- // FIXME header
- final GeneralInterfaceTemplate runtimeMxBeanIfc = new GeneralInterfaceTemplate(
- null, entry.getPackageName(), mxBeanTypeName,
- extendedInterfaces, methods);
-
- result.put(runtimeMxBeanIfc.getTypeDeclaration().getName()
- + ".java", runtimeMxBeanIfc);
- }
-
- result.putAll(TemplateFactory.tOsFromRbe(entry));
-
- return result;
- }
-
- // FIXME: put into Type.toString
- static String serializeType(final Type type, final boolean addWildcards) {
- if (type instanceof ParameterizedType){
- final ParameterizedType parameterizedType = (ParameterizedType) type;
- final StringBuilder sb = new StringBuilder();
- sb.append(parameterizedType.getRawType().getFullyQualifiedName());
- sb.append(addWildcards ? "<? extends " : "<");
- boolean first = true;
- for(final Type parameter: parameterizedType.getActualTypeArguments()) {
- if (first) {
- first = false;
- } else {
- sb.append(",");
- }
- sb.append(serializeType(parameter));
- }
- sb.append(">");
- return sb.toString();
- } else {
- return type.getFullyQualifiedName();
- }
- }
-
- static String serializeType(final Type type) {
- return serializeType(type, false);
- }
-
- private static String getReturnType(final AttributeIfc attributeIfc) {
- String returnType;
- if (attributeIfc instanceof TypedAttribute) {
- final Type type = ((TypedAttribute) attributeIfc).getType();
- returnType = serializeType(type);
- } else if (attributeIfc == VoidAttribute.getInstance()) {
- return "void";
- } else {
- throw new UnsupportedOperationException(
- "Attribute not supported: "
- + attributeIfc.getClass());
- }
- return returnType;
- }
-
- public static GeneralInterfaceTemplate serviceInterfaceFromSie(
- final ServiceInterfaceEntry sie) {
-
- final List<String> extendedInterfaces = Lists
- .newArrayList(AbstractServiceInterface.class.getCanonicalName());
- if (sie.getBase().isPresent()) {
- extendedInterfaces.add(sie.getBase().get().getFullyQualifiedName());
- }
-
- // FIXME header
- final GeneralInterfaceTemplate sieTemplate = new GeneralInterfaceTemplate(
- getHeaderFromEntry(sie), sie.getPackageName(),
- sie.getTypeName(), extendedInterfaces,
- Lists.<MethodDeclaration> newArrayList());
- sieTemplate.setJavadoc(sie.getNullableDescription());
-
- if (sie.getNullableDescription() != null) {
- sieTemplate.getAnnotations().add(
- Annotation.createDescriptionAnnotation(sie
- .getNullableDescription()));
- }
- sieTemplate.getAnnotations().addAll(Annotation.createSieAnnotations(sie));
-
- return sieTemplate;
- }
-
- public static AbstractFactoryTemplate abstractFactoryTemplateFromMbe(
- final ModuleMXBeanEntry mbe) {
- final AbstractFactoryAttributesProcessor attrProcessor = new AbstractFactoryAttributesProcessor();
- attrProcessor.processAttributes(mbe.getAttributes());
-
-
-
- return new AbstractFactoryTemplate(getHeaderFromEntry(mbe),
- mbe.getPackageName(), mbe.getAbstractFactoryName(),
- attrProcessor.getFields()
- );
- }
-
- public static AbstractModuleTemplate abstractModuleTemplateFromMbe(
- final ModuleMXBeanEntry mbe) {
- final AbstractModuleAttributesProcessor attrProcessor = new AbstractModuleAttributesProcessor(mbe.getAttributes());
-
- final List<ModuleField> moduleFields = attrProcessor.getModuleFields();
- final List<String> implementedIfcs = Lists.newArrayList(
- mbe.getFullyQualifiedName(mbe.getMXBeanInterfaceName()));
-
- for (final String implementedService : mbe.getProvidedServices().keySet()) {
- implementedIfcs.add(implementedService);
- }
-
- boolean generateRuntime = false;
- String registratorFullyQualifiedName = null;
- if (mbe.getRuntimeBeans() != null
- && !mbe.getRuntimeBeans().isEmpty()) {
- generateRuntime = true;
- final RuntimeBeanEntry rootEntry = RuntimeRegistratorFtlTemplate
- .findRoot(mbe.getRuntimeBeans());
- registratorFullyQualifiedName = rootEntry
- .getPackageName()
- .concat(".")
- .concat(RuntimeRegistratorFtlTemplate.getJavaNameOfRuntimeRegistrator(rootEntry));
- implementedIfcs.add(RuntimeBeanRegistratorAwareModule.class
- .getCanonicalName());
- }
-
- final List<String> extendedClasses = Collections.singletonList(AbstractModule.class.getCanonicalName() + "<" + mbe.getAbstractModuleName() + ">");
-
- final AbstractModuleTemplate abstractModuleTemplate = new AbstractModuleTemplate(
- getHeaderFromEntry(mbe), mbe.getPackageName(),
- mbe.getAbstractModuleName(), extendedClasses, implementedIfcs, moduleFields,
- attrProcessor.getMethods(), generateRuntime,
- registratorFullyQualifiedName);
-
- if (mbe.getNullableDescription() != null) {
- abstractModuleTemplate.getAnnotations().add(
- Annotation.createDescriptionAnnotation(mbe
- .getNullableDescription()));
- }
- return abstractModuleTemplate;
- }
-
- public static StubFactoryTemplate stubFactoryTemplateFromMbe(
- final ModuleMXBeanEntry mbe) {
- return new StubFactoryTemplate(getHeaderFromEntry(mbe),
- mbe.getPackageName(), mbe.getStubFactoryName(),
- mbe.getFullyQualifiedName(mbe.getAbstractFactoryName())
- );
- }
-
- public static GeneralInterfaceTemplate mXBeanInterfaceTemplateFromMbe(
- final ModuleMXBeanEntry mbe) {
- final MXBeanInterfaceAttributesProcessor attrProcessor = new MXBeanInterfaceAttributesProcessor();
- attrProcessor.processAttributes(mbe.getAttributes());
- final GeneralInterfaceTemplate ifcTemplate = new GeneralInterfaceTemplate(
- getHeaderFromEntry(mbe), mbe.getPackageName(),
- mbe.getMXBeanInterfaceName(), Lists.<String> newArrayList(),
- attrProcessor.getMethods());
- ifcTemplate.setJavadoc(mbe.getNullableDescription());
- return ifcTemplate;
- }
-
- public static Map<String, GeneralClassTemplate> tOsFromMbe(
- final ModuleMXBeanEntry mbe) {
- final Map<String, GeneralClassTemplate> retVal = Maps.newHashMap();
- final TOAttributesProcessor processor = new TOAttributesProcessor();
- processor.processAttributes(mbe.getAttributes());
- for (final org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory.TOAttributesProcessor.TOInternal to : processor
- .getTOs()) {
- final List<Constructor> constructors = Lists.newArrayList();
- constructors.add(new Constructor(to.getName(), "super();"));
-
- final Header header = getHeaderFromEntry(mbe);
- retVal.put(
- to.getType(),
- new GeneralClassTemplate(header, mbe.getPackageName(), to
- .getName(), Collections.<String> emptyList(),
- Collections.<String> emptyList(), to.getFields(),
- to.getMethods(), false, false, constructors));
- }
- return retVal;
- }
-
- public static Map<String, GeneralClassTemplate> tOsFromRbe(
- final RuntimeBeanEntry rbe) {
- final Map<String, GeneralClassTemplate> retVal = Maps.newHashMap();
- final TOAttributesProcessor processor = new TOAttributesProcessor();
- final Map<String, AttributeIfc> yangPropertiesToTypesMap = Maps.newHashMap(rbe.getYangPropertiesToTypesMap());
-
- // Add TOs from output parameters
- for (final Rpc rpc : rbe.getRpcs()) {
- final AttributeIfc returnType = rpc.getReturnType();
-
- if (returnType == VoidAttribute.getInstance()) {
- continue;
- }
- if (returnType instanceof JavaAttribute) {
- continue;
- }
- if (returnType instanceof ListAttribute && returnType.getOpenType() instanceof SimpleType) {
- continue;
- }
-
- Preconditions.checkState(!yangPropertiesToTypesMap.containsKey(returnType.getAttributeYangName()),
- "Duplicate TO %s for %s", returnType.getAttributeYangName(), rbe);
- yangPropertiesToTypesMap.put(returnType.getAttributeYangName(), returnType);
- }
-
- processor.processAttributes(yangPropertiesToTypesMap);
- for (final org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory.TOAttributesProcessor.TOInternal to : processor
- .getTOs()) {
- final List<Constructor> constructors = Lists.newArrayList();
- constructors.add(new Constructor(to.getName(), "super();"));
-
- // TODO header
- retVal.put(
- to.getType(),
- new GeneralClassTemplate(null, rbe.getPackageName(), to
- .getName(), Collections.<String> emptyList(),
- Collections.<String> emptyList(), to.getFields(),
- to.getMethods(), false, false, constructors));
- }
- return retVal;
- }
-
- private static Header getHeaderFromEntry(final AbstractEntry mbe) {
- return new Header(mbe.getYangModuleName(), mbe.getYangModuleLocalname());
- }
-
- // TODO refactor attribute processors
-
- private static class TOAttributesProcessor {
-
- private final List<TOInternal> tos = Lists.newArrayList();
-
- void processAttributes(final Map<String, AttributeIfc> attributes) {
- for (final Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
- final AttributeIfc attributeIfc = attrEntry.getValue();
- if (attributeIfc instanceof TOAttribute) {
- createTOInternal((TOAttribute) attributeIfc);
- }
- if (attributeIfc instanceof ListAttribute) {
- final AttributeIfc innerAttr = ((ListAttribute) attributeIfc)
- .getInnerAttribute();
- if (innerAttr instanceof TOAttribute) {
- createTOInternal((TOAttribute) innerAttr);
- }
- }
- }
- }
-
- private void createTOInternal(final TOAttribute toAttribute) {
-
- final Map<String, AttributeIfc> attrs = toAttribute.getCapitalizedPropertiesToTypesMap();
- // recursive processing of TO's attributes
- processAttributes(attrs);
-
- this.tos.add(new TOInternal(toAttribute.getType(), attrs));
- }
-
- List<TOInternal> getTOs() {
- return this.tos;
- }
-
- private static class TOInternal {
- private final String fullyQualifiedName, name;
- private List<Field> fields;
- private List<MethodDefinition> methods;
-
- public TOInternal(final Type type, final Map<String, AttributeIfc> attrs) {
- this(type.getFullyQualifiedName(), type.getName(), attrs, type.getPackageName());
- }
-
- public TOInternal(final String fullyQualifiedName, final String name,
- final Map<String, AttributeIfc> attrs, final String packageName) {
- this.fullyQualifiedName = fullyQualifiedName;
- this.name = name;
- processAttrs(attrs, packageName);
- }
-
- private final static String dependencyResolverVarName = "dependencyResolver";
- private final static String dependencyResolverInjectMethodName = "injectDependencyResolver";
-
- private void processAttrs(final Map<String, AttributeIfc> attrs, final String packageName) {
- this.fields = Lists.newArrayList();
- this.methods = Lists.newArrayList();
-
- // FIXME conflict if "dependencyResolver" field from yang
- final Field depRes = new Field(DependencyResolver.class.getName(), dependencyResolverVarName);
- this.fields.add(depRes);
- this.methods.add(new MethodDefinition("void", dependencyResolverInjectMethodName, Lists.newArrayList(depRes),
- "this." + dependencyResolverVarName + " = " + dependencyResolverVarName + ";"));
-
- for (final Entry<String, AttributeIfc> attrEntry : attrs.entrySet()) {
- final String innerName = attrEntry.getKey();
- final String varName = BindingMapping.getPropertyName(attrEntry.getKey());
-
- String fullyQualifiedName, nullableDefault = null;
- if (attrEntry.getValue() instanceof TypedAttribute) {
- Type type = ((TypedAttribute) attrEntry.getValue()).getType();
- if(attrEntry.getValue() instanceof JavaAttribute) {
- nullableDefault = ((JavaAttribute)attrEntry.getValue()).getNullableDefaultWrappedForCode();
- if(((JavaAttribute)attrEntry.getValue()).isIdentityRef()) {
-
- final String fieldType = serializeType(type, true);
- final String innerType = getInnerTypeFromIdentity(type);
- this.methods.add(new MethodDefinition(fieldType, "resolve" + attrEntry.getKey(), Collections.<Field>emptyList(),
- "return " + varName + ".resolveIdentity(" + dependencyResolverVarName + "," + innerType + ".class);"));
- type = identityRefType;
- }
- }
- fullyQualifiedName = serializeType(type);
- } else {
- fullyQualifiedName = FullyQualifiedNameHelper
- .getFullyQualifiedName(packageName, attrEntry.getValue().getUpperCaseCammelCase());
- }
- this.fields.add(new Field(fullyQualifiedName, varName, nullableDefault, needsDepResolver(attrEntry.getValue())));
-
- final String getterName = "get" + innerName;
- final MethodDefinition getter = new MethodDefinition(
- fullyQualifiedName, getterName,
- Collections.<Field> emptyList(), "return "
- + varName + ";");
-
- final String setterName = "set" + innerName;
- final MethodDefinition setter = new MethodDefinition("void",
- setterName, Lists.newArrayList(new Field(
- fullyQualifiedName, varName)), "this."
- + varName + " = " + varName + ";");
- this.methods.add(getter);
- this.methods.add(setter);
- }
-
- // Add hashCode
- final MethodDefinition hashCode = getHash(attrs);
- this.methods.add(hashCode);
-
- // Add equals
- final MethodDefinition equals = getEquals(attrs);
- this.methods.add(equals);
- }
-
- private MethodDefinition getEquals(final Map<String, AttributeIfc> attrs) {
- final StringBuilder equalsBodyBuilder = new StringBuilder(
- " if (this == o) { return true; }\n" +
- " if (o == null || getClass() != o.getClass()) { return false; }\n");
- equalsBodyBuilder.append(String.format(
- " final %s that = (%s) o;\n", this.name, this.name));
- for (final AttributeIfc s : attrs.values()) {
- equalsBodyBuilder.append(String.format(
- " if (!java.util.Objects.equals(%1$s, that.%1$s)) {\n" +
- " return false;\n" +
- " }\n\n", s.getLowerCaseCammelCase()));
- }
- equalsBodyBuilder.append(
- " return true;\n");
- return new MethodDefinition("boolean", "equals", Collections.singletonList(new Field("Object", "o")),
- Collections.singletonList(new Annotation("Override", Collections.<Parameter>emptyList())), equalsBodyBuilder.toString());
- }
-
- private static MethodDefinition getHash(final Map<String, AttributeIfc> attrs) {
- final StringBuilder hashBodyBuilder = new StringBuilder(
- " return java.util.Objects.hash(");
- for (final AttributeIfc s : attrs.values()) {
- hashBodyBuilder.append(s.getLowerCaseCammelCase());
- hashBodyBuilder.append(", ");
- }
- hashBodyBuilder.replace(hashBodyBuilder.length() - 2, hashBodyBuilder.length(), ");\n");
- return new MethodDefinition("int", "hashCode", Collections.<Field>emptyList(),
- Collections.singletonList(new Annotation("Override", Collections.<Parameter>emptyList())), hashBodyBuilder.toString());
- }
-
- String getType() {
- return this.fullyQualifiedName;
- }
-
- String getName() {
- return this.name;
- }
-
- List<Field> getFields() {
- return this.fields;
- }
-
- List<MethodDefinition> getMethods() {
- return this.methods;
- }
- }
- }
-
-
- private static class MXBeanInterfaceAttributesProcessor {
- private final List<MethodDeclaration> methods = Lists.newArrayList();
-
- void processAttributes(final Map<String, AttributeIfc> attributes) {
- for (final Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
- String returnType;
- final AttributeIfc attributeIfc = attrEntry.getValue();
-
- if (attributeIfc instanceof TypedAttribute) {
- final TypedAttribute typedAttribute = (TypedAttribute) attributeIfc;
- returnType = serializeType(typedAttribute.getType());
-
- if (attributeIfc instanceof JavaAttribute && ((JavaAttribute)attrEntry.getValue()).isIdentityRef()) {
- returnType = serializeType(identityRefType);
- }
-
- } else {
- throw new UnsupportedOperationException(
- "Attribute not supported: "
- + attributeIfc.getClass());
- }
-
- final String getterName = "get"
- + attributeIfc.getUpperCaseCammelCase();
- final MethodDeclaration getter = new MethodDeclaration(returnType,
- getterName, Collections.<Field> emptyList());
-
- final String varName = BindingMapping.getPropertyName(attrEntry.getKey());
- final String setterName = "set"
- + attributeIfc.getUpperCaseCammelCase();
- final MethodDeclaration setter = new MethodDeclaration("void",
- setterName, Lists.newArrayList(new Field(returnType,
- varName)));
-
- this.methods.add(getter);
- this.methods.add(setter);
-
- if (attributeIfc.getNullableDescription() != null) {
- setter.setJavadoc(attrEntry.getValue()
- .getNullableDescription());
- }
- }
- }
-
- List<MethodDeclaration> getMethods() {
- return this.methods;
- }
- }
-
- private static final Type identityRefType = new Type() {
- public final Class<IdentityAttributeRef> IDENTITY_ATTRIBUTE_REF_CLASS = IdentityAttributeRef.class;
- private final JavaTypeName identifier = JavaTypeName.create(IDENTITY_ATTRIBUTE_REF_CLASS);
-
- @Override
- public JavaTypeName getIdentifier() {
- return identifier;
- }
- };
-
- private static class AbstractFactoryAttributesProcessor {
-
- private final List<Field> fields = Lists.newArrayList();
-
- void processAttributes(final Map<String, AttributeIfc> attributes) {
- for (final AttributeIfc attributeIfc : attributes.values()) {
- if (attributeIfc instanceof TypedAttribute) {
- final TypedAttribute typedAttribute = (TypedAttribute) attributeIfc;
- final String type = serializeType(typedAttribute.getType());
-
- this.fields.add(new Field(type, attributeIfc
- .getUpperCaseCammelCase(), null));
- } else {
- throw new UnsupportedOperationException(
- "Attribute not supported: "
- + attributeIfc.getClass());
- }
- }
- }
-
- List<Field> getFields() {
- return this.fields;
- }
- }
-
- private static class AbstractModuleAttributesProcessor {
- private static class Holder {
- private final List<ModuleField> moduleFields;
- private final List<MethodDefinition> methods;
-
- private Holder(final List<ModuleField> moduleFields, final List<MethodDefinition> methods) {
- this.moduleFields = Collections.unmodifiableList(moduleFields);
- this.methods = Collections.unmodifiableList(methods);
- }
- }
-
- private final Holder holder;
-
-
- private AbstractModuleAttributesProcessor(final Map<String, AttributeIfc> attributes) {
- this.holder = processAttributes(attributes);
- }
-
- private static Holder processAttributes(final Map<String, AttributeIfc> attributes) {
- final List<ModuleField> moduleFields = new ArrayList<>();
- final List<MethodDefinition> methods = new ArrayList<>();
- for (final Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
- String type, nullableDefaultWrapped = null;
- final AttributeIfc attributeIfc = attrEntry.getValue();
- boolean isIdentity = false;
- final boolean needsDepResolver = needsDepResolver(attrEntry.getValue());
-
- if (attributeIfc instanceof TypedAttribute) {
- final TypedAttribute typedAttribute = (TypedAttribute) attributeIfc;
- type = serializeType(typedAttribute.getType());
- if (attributeIfc instanceof JavaAttribute) {
- nullableDefaultWrapped = ((JavaAttribute) attributeIfc).getNullableDefaultWrappedForCode();
- if(((JavaAttribute)attrEntry.getValue()).isIdentityRef()) {
- isIdentity = true;
- type = serializeType(typedAttribute.getType(), true);
- }
- }
- } else {
- throw new UnsupportedOperationException(
- "Attribute not supported: "
- + attributeIfc.getClass());
- }
-
- boolean isDependency = false;
- boolean isListOfDependencies = false;
- Dependency dependency = null;
- final Annotation overrideAnnotation = new Annotation("Override",
- Collections.<Parameter> emptyList());
- final List<Annotation> annotations = Lists
- .newArrayList(overrideAnnotation);
-
- if (attributeIfc instanceof AbstractDependencyAttribute) {
- isDependency = true;
- dependency = ((AbstractDependencyAttribute) attributeIfc)
- .getDependency();
- annotations.add(Annotation
- .createRequireIfcAnnotation(dependency.getSie()));
- if (attributeIfc instanceof ListDependenciesAttribute) {
- isListOfDependencies = true;
- }
- }
-
- final String varName = BindingMapping.getPropertyName(attrEntry.getKey());
-
- ModuleField field;
- if (isIdentity) {
- final String identityBaseClass = getInnerTypeFromIdentity(((TypedAttribute) attributeIfc).getType());
- final IdentityRefModuleField identityField = new IdentityRefModuleField(type, varName,
- attributeIfc.getUpperCaseCammelCase(), identityBaseClass);
-
- final String getterName = "get"
- + attributeIfc.getUpperCaseCammelCase() + "Identity";
- final MethodDefinition additionalGetter = new MethodDefinition(type, getterName, Collections.<Field> emptyList(),
- Collections.<Annotation> emptyList(), "return " + identityField.getIdentityClassName()
- + ";");
- methods.add(additionalGetter);
-
- final String setterName = "set"
- + attributeIfc.getUpperCaseCammelCase();
-
- final String setterBody = "this." + identityField.getIdentityClassName() + " = " + identityField.getIdentityClassName() + ";";
- final MethodDefinition additionalSetter = new MethodDefinition("void",
- setterName,
- Lists.newArrayList(new Field(type, identityField.getIdentityClassName())),
- Collections.<Annotation> emptyList(), setterBody);
- additionalSetter.setJavadoc(attributeIfc.getNullableDescription());
-
- methods.add(additionalSetter);
-
- type = serializeType(identityRefType);
- field = identityField;
- } else {
- field = new ModuleField(type, varName, attributeIfc.getUpperCaseCammelCase(),
- nullableDefaultWrapped, isDependency, dependency, isListOfDependencies, needsDepResolver);
- }
- moduleFields.add(field);
-
-
- final String getterName = "get"
- + attributeIfc.getUpperCaseCammelCase();
- final MethodDefinition getter = new MethodDefinition(type,
- getterName, Collections.<Field> emptyList(),
- Lists.newArrayList(overrideAnnotation), "return "
- + varName + ";");
-
- methods.add(getter);
-
- final String setterName = "set"
- + attributeIfc.getUpperCaseCammelCase();
-
- if (attributeIfc.getNullableDescription() != null) {
- annotations.add(Annotation
- .createDescriptionAnnotation(attributeIfc.getNullableDescription()));
- }
-
- String setterBody = "this." + varName + " = " + varName + ";";
- if (isListOfDependencies) {
- final String nullCheck = String.format("if (%s == null) {\n%s = new java.util.ArrayList<>(); \n}%n",
- varName, varName);
- setterBody = nullCheck + setterBody;
- }
- final MethodDefinition setter = new MethodDefinition("void",
- setterName,
- Lists.newArrayList(new Field(type, varName)),
- annotations, setterBody);
- setter.setJavadoc(attributeIfc.getNullableDescription());
-
- methods.add(setter);
- }
- return new Holder(moduleFields, methods);
- }
-
- List<ModuleField> getModuleFields() {
- return this.holder.moduleFields;
- }
-
- List<MethodDefinition> getMethods() {
- return this.holder.methods;
- }
-
- }
-
-
- private static boolean needsDepResolver(final AttributeIfc value) {
- if(value instanceof TOAttribute) {
- return true;
- }
- if(value instanceof ListAttribute) {
- final AttributeIfc innerAttribute = ((ListAttribute) value).getInnerAttribute();
- return needsDepResolver(innerAttribute);
- }
-
- return false;
- }
-
- private static String getInnerTypeFromIdentity(final Type type) {
- Preconditions.checkArgument(type instanceof ParameterizedType);
- final Type[] args = ((ParameterizedType) type).getActualTypeArguments();
- Preconditions.checkArgument(args.length ==1);
- return serializeType(args[0]);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
-
-class TypeHelper {
-
- /**
- * Output string representing java notation of generic class, e.g.
- * "List<String>" for input parameters List.class, String.class
- */
- static String getGenericType(Class<?> type, Class<?>... parameters) {
- StringBuilder sb = new StringBuilder();
- sb.append(type.getCanonicalName());
- if (parameters.length > 0) {
- sb.append("<");
- boolean first = true;
- for (Class<?> parameter : parameters) {
- if (first) {
- first = false;
- } else {
- sb.append(",");
- }
- sb.append(parameter.getCanonicalName());
- }
- sb.append(">");
- }
- return sb.toString();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.opendaylight.controller.config.api.annotations.Description;
-import org.opendaylight.controller.config.api.annotations.RequireInterface;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.yangtools.yang.binding.annotations.ModuleQName;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.Revision;
-
-public class Annotation {
- final String name;
- final List<Parameter> params;
-
- public Annotation(final String name, final List<Parameter> params) {
- this.name = name;
- this.params = params;
- }
-
- public String getName() {
- return name;
- }
-
- public List<Parameter> getParams() {
- return params;
- }
-
- public static Annotation createFromMap(final Class<?> annotationClass, final Map<String, String> parameters) {
- List<Parameter> parameterList = new ArrayList<>();
- for(Entry<String, String> entry: parameters.entrySet()) {
- parameterList.add(new Parameter(entry.getKey(), entry.getValue()));
- }
- return new Annotation(annotationClass.getCanonicalName(), parameterList);
- }
-
- public static Annotation createDescriptionAnnotation(final String description) {
- Preconditions.checkNotNull(description,
- "Cannot create annotation from null description");
- return new Annotation(Description.class.getCanonicalName(),
- Lists.newArrayList(new Parameter("value", q(description))));
- }
-
- public static Annotation createModuleQNameANnotation(final QName qName) {
- Map<String, String> parameters = new HashMap<>();
- parameters.put("namespace", q(qName.getNamespace().toString()));
- parameters.put("revision", q(qName.getRevision().map(Revision::toString).orElse(null)));
- parameters.put("name", q(qName.getLocalName()));
- return Annotation.createFromMap(ModuleQName.class, parameters);
- }
-
- public static Collection<Annotation> createSieAnnotations(final ServiceInterfaceEntry sie){
-
- String exportedClassName = sie.getExportedOsgiClassName();
- Preconditions.checkNotNull(sie.getQName(),
- "Cannot create annotation from null qname");
- Preconditions.checkNotNull(exportedClassName,
- "Cannot create annotation from null exportedClassName");
- List<Annotation> result = new ArrayList<>();
- {
- List<Parameter> params = Lists.newArrayList(new Parameter("value", q(sie.getQName().toString())));
- params.add(new Parameter("osgiRegistrationType", exportedClassName + ".class"));
- params.add(new Parameter("registerToOsgi", Boolean.toString(sie.isRegisterToOsgi())));
- params.add(new Parameter("namespace", q(sie.getQName().getNamespace().toString())));
- params.add(new Parameter("revision", q(sie.getQName().getRevision().map(Revision::toString).orElse(null))));
- params.add(new Parameter("localName", q(sie.getQName().getLocalName())));
-
- Annotation sieAnnotation = new Annotation(ServiceInterfaceAnnotation.class.getCanonicalName(), params);
- result.add(sieAnnotation);
-
- }
- {
- List<Parameter> params = new ArrayList<>();
- params.add(new Parameter("namespace", q(sie.getYangModuleQName().getNamespace().toString())));
- params.add(new Parameter("revision", q(sie.getYangModuleQName().getRevision()
- .map(Revision::toString).orElse(null))));
- params.add(new Parameter("name", q(sie.getYangModuleQName().getLocalName())));
-
- Annotation moduleQNameAnnotation = new Annotation(ModuleQName.class.getCanonicalName(), params);
- result.add(moduleQNameAnnotation);
- }
- return result;
- }
-
- public static Annotation createRequireIfcAnnotation(
- final ServiceInterfaceEntry sie) {
- String reqIfc = sie.getFullyQualifiedName() + ".class";
- return new Annotation(RequireInterface.class.getCanonicalName(),
- Lists.newArrayList(new Parameter("value", reqIfc)));
- }
-
- private static final String quote = "\"";
-
- public static String q(final String nullableDescription) {
- return nullableDescription == null ? null : quote + nullableDescription + quote;
- }
-
- public static class Parameter {
- private final String key, value;
-
- public Parameter(final String key, final String value) {
- this.key = key;
- this.value = value;
- }
-
- public String getKey() {
- return key;
- }
-
- public String getValue() {
- return value;
- }
- }
-
- @Override
- public String toString() {
- return AnnotationSerializer.toString(this);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation.Parameter;
-
-class AnnotationSerializer {
-
- static String toString(Annotation annotation) {
- StringBuilder builder = new StringBuilder();
- builder.append("@");
- builder.append(annotation.getName());
- if (!annotation.getParams().isEmpty()) {
- builder.append("(");
- for (Parameter param : annotation.getParams()) {
- builder.append(param.getKey());
- builder.append(" = ");
- builder.append(fixString(param.getValue()));
- builder.append(", ");
- }
- builder.setCharAt(builder.length() - 2, ')');
- }
- builder.append("\n");
- return builder.toString();
- }
-
- private static String fixString(String value) {
- // TODO replace with compress single line if possible
- return value.replaceAll("\\r\\n|\\r|\\n", " ").replaceAll(" +", " ");
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-public class Constructor {
-
- private final String typeName, body;
- private final boolean isPublic;
-
- public Constructor(String typeName, String body, boolean isPublic) {
- this.typeName = typeName;
- this.body = body;
- this.isPublic = isPublic;
- }
-
- // TODO add arguments if necessary
-
- public Constructor(String typeName, String body) {
- this(typeName, body, true);
- }
-
- public String getTypeName() {
- return typeName;
- }
-
- public String getBody() {
- return body;
- }
-
- public boolean isPublic() {
- return isPublic;
- }
-
- @Override
- public String toString() {
- return ConstructorSerializer.toString(this);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-public class ConstructorSerializer {
-
- public static String toString(Constructor constr) {
- StringBuilder build = new StringBuilder();
- build.append(" ");
- if (constr.isPublic()) {
- build.append("public ");
- }
- build.append(constr.getTypeName());
- build.append("() {");
- build.append("\n");
- build.append(" ");
- build.append(" ");
- build.append(constr.getBody());
- build.append("\n");
- build.append(" ");
- build.append("}");
- build.append("\n");
- build.append("\n");
- return build.toString();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.lang.model.element.Modifier;
-
-public class Field {
- private final String type;
- private final String name;
- private final String definition;
- private final List<Modifier> modifiers;
- private final boolean needsDepResolver;
-
- public Field(String type, String name) {
- this(new ArrayList<>(), type, name, null, false);
- }
-
- public Field(String type, String name, String definition) {
- this(new ArrayList<>(), type, name, definition, false);
- }
-
- public Field(List<Modifier> modifiers, String type, String name) {
- this(modifiers, type, name, null, false);
- }
-
- public Field(List<Modifier> modifiers, String type, String name,
- String definition) {
- this(modifiers, type, name, definition, false);
- }
-
- public Field(List<Modifier> modifiers, String type, String name,
- String nullableDefinition, boolean needsDepResolver) {
- this.modifiers = checkNotNull(modifiers);
- this.type = checkNotNull(type);
- this.name = checkNotNull(name);
- this.definition = nullableDefinition;
- this.needsDepResolver = needsDepResolver;
- }
-
- public Field(String type, String name, String definition, boolean needsDepResolver) {
- this(new ArrayList<>(), type, name, definition, needsDepResolver);
- }
-
- public boolean isNeedsDepResolver() {
- return needsDepResolver;
- }
-
- public String getType() {
- return type;
- }
-
- public String getGenericInnerType() {
- return type.substring(type.indexOf("<") + 1, type.indexOf(">"));
- }
-
- public List<Modifier> getModifiers() {
- return modifiers;
- }
-
- public String getName() {
- return name;
- }
-
- public String getDefinition() {
- return definition;
- }
-
- public boolean isArray() {
- return type.endsWith("[]");
- }
-
- @Override
- public String toString() {
- return FieldSerializer.toString(this);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-public class FieldSerializer {
-
- public static String toString(Field field) {
- StringBuilder build = new StringBuilder();
- build.append("private ");
- field.getModifiers().forEach(mod -> build.append(mod).append(" "));
- build.append(field.getType()).append(" ");
- build.append(field.getName());
- if (field.getDefinition() != null) {
- build.append(" = ").append(field.getDefinition());
- }
- build.append(";");
- build.append("\n");
- return build.toString();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-public class Header {
- private final String yangModuleName, yangModuleLocalName;
-
- public Header(String yangModuleName, String yangModuleLocalName) {
- this.yangModuleName = yangModuleName;
- this.yangModuleLocalName = yangModuleLocalName;
- }
-
- public String getYangModuleName() {
- return yangModuleName;
- }
-
- public String getYangModuleLocalName() {
- return yangModuleLocalName;
- }
-
- @Override
- public String toString() {
- return HeaderSerializer.toString(this);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import java.util.Date;
-
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator;
-
-public class HeaderSerializer {
- private static final String GENERATOR_CLASS = JMXGenerator.class.getCanonicalName();
-
- public static String toString(Header header) {
- return "Generated file" + "\n" +
- "\n" +
- "Generated from: " +
- "yang module name: " + header.getYangModuleName() +
- " yang module local name: " + header.getYangModuleLocalName() + "\n" +
- "Generated by: " + GENERATOR_CLASS + "\n" +
- "Generated at: " + new Date() + "\n" +
- "\n" +
- "Do not modify this file unless it is present under src/main directory ";
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import org.opendaylight.controller.config.api.IdentityAttributeRef;
-
-public class IdentityRefModuleField extends ModuleField {
-
- public static final String IDENTITY_CLASS_FIELD_SUFFIX = "IdentityClass";
- private final String identityBaseClass;
-
- public IdentityRefModuleField(String type, String name, String attributeName, String identityBaseClass) {
- super(type, name, attributeName, null, false, null, false, false);
- this.identityBaseClass = identityBaseClass;
- }
-
- public String getIdentityBaseClass() {
- return identityBaseClass;
- }
-
- @Override
- public boolean isIdentityRef() {
- return true;
- }
-
- public String getType() {
- return IdentityAttributeRef.class.getName();
- }
-
- public String getIdentityClassType() {
- return super.getType();
- }
-
- public String getIdentityClassName() {
- return addIdentityClassFieldSuffix(getName());
- }
-
- public static String addIdentityClassFieldSuffix(String prefix) {
- return prefix + IDENTITY_CLASS_FIELD_SUFFIX;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import java.util.List;
-import java.util.Optional;
-import javax.lang.model.element.Modifier;
-
-public interface Method {
- Optional<Modifier> getVisibility();
-
- List<Modifier> getModifiers();
-
- String getReturnType();
-
- String getName();
-
- List<Field> getParameters();
-
- String getJavadoc();
-
- List<Annotation> getAnnotations();
-
- List<String> getThrowsExceptions();
-
- Optional<String> getBody();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-import javax.lang.model.element.Modifier;
-
-public class MethodDeclaration implements Method {
- private final String returnType;
- private final String name;
- private final List<Field> parameters;
- private String javadoc = null;
- private final List<Annotation> annotations;
-
- public MethodDeclaration(String returnType, String name,
- List<Field> parameters) {
- this(returnType, name, parameters, Collections.emptyList());
- }
-
- public MethodDeclaration(String returnType, String name,
- List<Field> parameters, List<Annotation> annotations) {
- this.returnType = returnType;
- this.name = name;
- this.parameters = parameters;
- this.annotations = annotations;
- }
-
- @Override
- public List<Annotation> getAnnotations() {
- return annotations;
- }
-
- @Override
- public List<String> getThrowsExceptions() {
- return Collections.emptyList();
- }
-
- @Override
- public Optional<String> getBody() {
- return Optional.empty();
- }
-
- @Override
- public String getJavadoc() {
- return javadoc;
- }
-
- public void setJavadoc(String javadoc) {
- this.javadoc = javadoc;
- }
-
- @Override
- public Optional<Modifier> getVisibility() {
- return Optional.empty();
- }
-
- @Override
- public String getReturnType() {
- return returnType;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public List<Field> getParameters() {
- return parameters;
- }
-
- @Override
- public List<Modifier> getModifiers() {
- return Collections.emptyList();
- }
-
- @Override
- public String toString() {
- return MethodSerializer.toString(this);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-import javax.lang.model.element.Modifier;
-
-public class MethodDefinition implements Method {
- private final List<Modifier> modifiers;
- private final String returnType;
- private final String name;
- private final List<Field> parameters;
- private final List<String> throwsExceptions;
- private final String body;
- private String javadoc = null;
- private final List<Annotation> annotations;
-
- // TODO remove, Constructor is in separate class
- public static MethodDefinition createConstructor(String name,
- List<Field> parameters, String body) {
- return new MethodDefinition("", name, parameters, body);
-
- }
-
- public MethodDefinition(String returnType, String name,
- List<Field> parameters, String body) {
- this(Collections.emptyList(), returnType, name, parameters,
- Collections.emptyList(), Collections.emptyList(), body);
- }
-
- public MethodDefinition(String returnType, String name,
- List<Field> parameters, List<Annotation> annotations, String body) {
- this(Collections.emptyList(), returnType, name, parameters,
- Collections.emptyList(), annotations, body);
- }
-
- public MethodDefinition(List<Modifier> modifiers, String returnType,
- String name, List<Field> parameters, List<String> throwsExceptions,
- List<Annotation> annotations, String body) {
- this.modifiers = modifiers;
- this.returnType = returnType;
- this.name = name;
- this.parameters = parameters;
- this.throwsExceptions = throwsExceptions;
- this.body = body;
- this.annotations = annotations;
- }
-
- @Override
- public List<Annotation> getAnnotations() {
- return annotations;
- }
-
- @Override
- public String getJavadoc() {
- return javadoc;
- }
-
- public void setJavadoc(String javadoc) {
- this.javadoc = javadoc;
- }
-
- @Override
- public Optional<Modifier> getVisibility() {
- return Optional.of(Modifier.PUBLIC);
- }
-
- @Override
- public String getReturnType() {
- return returnType;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public List<Field> getParameters() {
- return parameters;
- }
-
- @Override
- public List<String> getThrowsExceptions() {
- return throwsExceptions;
- }
-
- @Override
- public Optional<String> getBody() {
- return Optional.of(body);
- }
-
- @Override
- public List<Modifier> getModifiers() {
- return modifiers;
- }
-
- @Override
- public String toString() {
- return MethodSerializer.toString(this);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import java.util.Optional;
-import java.util.function.Consumer;
-import java.util.stream.Collectors;
-import javax.lang.model.element.Modifier;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil;
-
-class MethodSerializer {
-
- static String toString(Method method) {
- StringBuilder build = new StringBuilder();
- Consumer<Modifier> appendWithSpace = string -> build.append(string).append(" ");
-
- if (method.getJavadoc() != null) {
- build.append(StringUtil.writeComment(method.getJavadoc(), true));
- }
-
- method.getAnnotations().forEach(build::append);
-
- build.append(" ");
- method.getVisibility().ifPresent(appendWithSpace);
- method.getModifiers().forEach(appendWithSpace);
- build.append(method.getReturnType()).append(" ");
-
- build.append(method.getName()).append("(");
- boolean firstParam = true;
- for (Field param : method.getParameters()) {
- if (!firstParam) {
- build.append(", ");
- }
- param.getModifiers().forEach(appendWithSpace);
- build.append(param.getType()).append(" ");
- build.append(param.getName());
- firstParam = false;
- }
- build.append(")");
-
- if (!method.getThrowsExceptions().isEmpty()) {
- build.append(" throws ");
- build.append(method.getThrowsExceptions().stream().collect(Collectors.joining(", ")));
- }
-
- Optional<String> body = method.getBody();
- if (!body.isPresent()) {
- build.append(";");
- build.append("\n");
- } else {
- build.append(" {");
- build.append("\n");
- build.append(" ");
- build.append(body.get());
- build.append("\n");
- build.append(" ");
- build.append("}");
- build.append("\n");
- }
- build.append("\n");
- return build.toString();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import javax.lang.model.element.Modifier;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.Dependency;
-
-public class ModuleField extends Field {
-
- private final String nullableDefault, attributeName;
- private final boolean dependent, isListOfDependencies;
- private final Dependency dependency;
-
- private ModuleField(List<Modifier> modifiers, String type, String name, String attributeName,
- String nullableDefault, boolean isDependency, Dependency dependency, boolean isListOfDependencies,
- boolean needsDepResolver) {
- super(modifiers, type, name, null, needsDepResolver);
- this.dependent = isDependency;
- this.dependency = dependency;
- this.attributeName = attributeName;
- if (type.startsWith(List.class.getName()) && nullableDefault == null) {
- String generics = type.substring(List.class.getName().length());
- nullableDefault = "new " + ArrayList.class.getName() + generics + "()";
- }
- this.nullableDefault = nullableDefault;
- this.isListOfDependencies = isListOfDependencies;
- }
-
- public ModuleField(String type, String name, String attributeName, String nullableDefault, boolean isDependency,
- Dependency dependency, boolean isListOfDependencies, boolean needsDepResolve) {
- this(Collections.emptyList(), type, name, attributeName, nullableDefault, isDependency, dependency,
- isListOfDependencies, needsDepResolve);
- }
-
- public boolean isIdentityRef() {
- return false;
- }
-
- @Override
- public String toString() {
- return ModuleFieldSerializer.toString(this);
- }
-
- public Dependency getDependency() {
- return dependency;
- }
-
- public String getNullableDefault() {
- return nullableDefault;
- }
-
- public boolean isDependent() {
- return dependent;
- }
-
- public boolean isListOfDependencies() {
- return isListOfDependencies;
- }
-
- public String getAttributeName() {
- return attributeName;
- }
-
-
- public boolean isList() {
- return getType().startsWith("java.util.List");
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import org.opendaylight.controller.config.api.JmxAttribute;
-
-public class ModuleFieldSerializer {
-
-
- public static String toString(ModuleField moduleField) {
- StringBuilder builder = new StringBuilder();
- builder.append(" ");
- builder.append("public static final ");
- builder.append(JmxAttribute.class.getCanonicalName());
- builder.append(" ");
- builder.append(moduleField.getName());
- builder.append("JmxAttribute = new ");
- builder.append(JmxAttribute.class.getCanonicalName());
- builder.append("(\"");
- builder.append(moduleField.getAttributeName());
- builder.append("\");");
- builder.append("\n");
-
- builder.append(" private ");
- moduleField.getModifiers().forEach(mod -> builder.append(mod).append(" "));
- builder.append(moduleField.getType()).append(" ");
- builder.append(moduleField.getName());
- if (moduleField.getNullableDefault() != null) {
- builder.append(" = ").append(moduleField.getNullableDefault());
- }
- builder.append(";");
-
- if (moduleField.isDependent()) {
- String comment = moduleField.getDependency().isMandatory() ? "mandatory"
- : "optional";
- builder.append(" // ").append(comment);
- }
- builder.append("\n");
-
- builder.append("\n");
-
- return builder.toString();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model;
-
-import java.util.List;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.TypeName;
-
-public class TypeDeclaration {
- private final String type, name;
- private final List<String> extended, implemented;
- private final boolean isAbstract, isFinal;
-
- public TypeDeclaration(String type, String name, List<String> extended,
- List<String> implemented, boolean isAbstract, boolean isFinal) {
- this.type = type;
- this.name = name;
- this.extended = extended;
- this.implemented = implemented;
- this.isAbstract = isAbstract;
- this.isFinal = isFinal;
- }
-
- public TypeDeclaration(String type, String name, List<String> extended,
- List<String> implemented) {
- this(type, name, extended, implemented, false, false);
- }
-
- public boolean isAbstract() {
- return isAbstract;
- }
-
- public boolean isFinal() {
- return isFinal;
- }
-
- public String getType() {
- return type;
- }
-
- public String getName() {
- return name;
- }
-
- public List<String> getExtended() {
- return extended;
- }
-
- public List<String> getImplemented() {
- return implemented;
- }
-
- public TypeName toTypeName() {
- if ("interface".equals(type)) {
- return TypeName.interfaceType;
- } else if ("class".equals(type)) {
- if (isAbstract) {
- return TypeName.absClassType;
- } else if (isFinal) {
- return TypeName.finalClassType;
- } else {
- return TypeName.classType;
- }
- } else if ("enum".equals(type)) {
- return TypeName.enumType;
- } else {
- throw new IllegalStateException("Type not supported: " + type);
- }
- }
-
- @Override
- public String toString() {
- return "TypeDeclaration{" + "type='" + type + '\'' + ", name='" + name
- + '\'' + '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory;
-
-import static java.lang.String.format;
-
-import com.google.common.base.Optional;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
-import org.opendaylight.controller.config.api.annotations.Description;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.AbstractFactoryTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObjectBuilder;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.JavaFileInputBuilder;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.TypeName;
-import org.opendaylight.yangtools.yang.common.QName;
-
-public class AbsFactoryGeneratedObjectFactory {
- private static final String BUNDLE_CONTEXT = "org.osgi.framework.BundleContext";
-
- public GeneratedObject toGeneratedObject(ModuleMXBeanEntry mbe, Optional<String> copyright) {
- FullyQualifiedName absFactoryFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getAbstractFactoryName());
- FullyQualifiedName moduleFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getStubModuleName());
- Optional<String> classJavaDoc = Optional.fromNullable(mbe.getNullableDescription());
-
- AbstractFactoryTemplate abstractFactoryTemplate = TemplateFactory.abstractFactoryTemplateFromMbe(mbe);
- Optional<String> header = abstractFactoryTemplate.getHeaderString();
-
- List<FullyQualifiedName> providedServices = new ArrayList<>();
- for(String providedService: mbe.getProvidedServices().keySet()) {
- providedServices.add(FullyQualifiedName.fromString(providedService));
- }
-
- return toGeneratedObject(absFactoryFQN, copyright,
- header, classJavaDoc, mbe.getYangModuleQName(),
- mbe.getGloballyUniqueName(),
- providedServices,
- moduleFQN,
- abstractFactoryTemplate.getFields());
- }
-
- public GeneratedObject toGeneratedObject(FullyQualifiedName absFactoryFQN, Optional<String> copyright,
- Optional<String> header, Optional<String> classJavaDoc, QName yangModuleQName,
- String globallyUniqueName,
- List<FullyQualifiedName> providedServices,
- FullyQualifiedName moduleFQN,
- List<Field> moduleFields) {
- JavaFileInputBuilder b = new JavaFileInputBuilder();
-
- b.addImportFQN(new FullyQualifiedName(Module.class));
- b.addImportFQN(new FullyQualifiedName(ModuleIdentifier.class));
-
- Annotation moduleQNameAnnotation = Annotation.createModuleQNameANnotation(yangModuleQName);
- b.addClassAnnotation(moduleQNameAnnotation);
-
- b.setFqn(absFactoryFQN);
- b.setTypeName(TypeName.absClassType);
-
- b.setCopyright(copyright);
- b.setHeader(header);
- b.setClassJavaDoc(classJavaDoc);
- b.addImplementsFQN(new FullyQualifiedName(ModuleFactory.class));
- if (classJavaDoc.isPresent()) {
- b.addClassAnnotation(format("@%s(value=\"%s\")", Description.class.getCanonicalName(), classJavaDoc.get()));
- }
-
- b.addToBody(format("public static final java.lang.String NAME = \"%s\";", globallyUniqueName));
- b.addToBody(format("private static final java.util.Set<Class<? extends %s>> serviceIfcs;",
- AbstractServiceInterface.class.getCanonicalName()));
-
- b.addToBody("@Override\n public final String getImplementationName() { \n return NAME; \n}");
-
- b.addToBody(getServiceIfcsInitialization(providedServices));
-
- // createModule
- b.addToBody(format("\n"+
- "@Override\n"+
- "public %s createModule(String instanceName, %s dependencyResolver, %s bundleContext) {\n"+
- "return instantiateModule(instanceName, dependencyResolver, bundleContext);\n"+
- "}\n",
- Module.class.getCanonicalName(), DependencyResolver.class.getCanonicalName(), BUNDLE_CONTEXT));
-
- b.addToBody(getCreateModule(moduleFQN, moduleFields));
-
- b.addToBody(format("\n"+
- "public %s instantiateModule(String instanceName, %s dependencyResolver, %s oldModule, %s oldInstance, %s bundleContext) {\n"+
- "return new %s(new %s(NAME, instanceName), dependencyResolver, oldModule, oldInstance);\n"+
- "}\n",
- moduleFQN, DependencyResolver.class.getCanonicalName(), moduleFQN, AutoCloseable.class.getCanonicalName(),
- BUNDLE_CONTEXT, moduleFQN, ModuleIdentifier.class.getCanonicalName()));
-
- b.addToBody(format("\n"+
- "public %s instantiateModule(String instanceName, %s dependencyResolver, %s bundleContext) {\n"+
- "return new %s(new %s(NAME, instanceName), dependencyResolver);\n"+
- "}\n", moduleFQN, DependencyResolver.class.getCanonicalName(), BUNDLE_CONTEXT,
- moduleFQN, ModuleIdentifier.class.getCanonicalName()
- ));
-
- b.addToBody(format("\n"+
- "public %s handleChangedClass(%s dependencyResolver, %s old, %s bundleContext) throws Exception {\n" +
- // "// @Deprecated return handleChangedClass(old);\n" +
- "String instanceName = old.getModule().getIdentifier().getInstanceName();\n" +
- "%1$s newModule = new %1$s(new ModuleIdentifier(NAME, instanceName), dependencyResolver);\n" +
- "Module oldModule = old.getModule();\n" +
- "Class<? extends Module> oldModuleClass = oldModule.getClass();\n" +
- genCodeToCopyAttributes(moduleFields) +
- "return newModule;\n" +
- "}\n", moduleFQN, DependencyResolver.class.getCanonicalName(), DynamicMBeanWithInstance.class.getCanonicalName(), BUNDLE_CONTEXT));
-
- b.addToBody(format("\n@Deprecated\n"+
- "public %s handleChangedClass(%s old) throws Exception {\n"+
- "throw new UnsupportedOperationException(\"Class reloading is not supported\");\n"+
- "}\n", moduleFQN, DynamicMBeanWithInstance.class.getCanonicalName()));
-
- b.addToBody(format("\n"+
- "@Override\n"+
- "public java.util.Set<%s> getDefaultModules(org.opendaylight.controller.config.api.DependencyResolverFactory dependencyResolverFactory, %s bundleContext) {\n"+
- "return new java.util.HashSet<>();\n"+
- "}\n", moduleFQN, BUNDLE_CONTEXT));
-
- return new GeneratedObjectBuilder(b.build()).toGeneratedObject();
- }
-
- private String genCodeToCopyAttributes(List<Field> moduleFields) {
- StringBuilder sb = new StringBuilder("\n");
- for (Field field : moduleFields) {
- sb.append(format("newModule.set%1$s( (%2$s) oldModuleClass.getMethod(\"get%1$s\").invoke(oldModule));\n", field.getName(), field.getType()));
- }
- sb.append('\n');
- return sb.toString();
- }
-
- private static String getCreateModule(FullyQualifiedName moduleFQN, List<Field> moduleFields) {
- StringBuilder result = new StringBuilder("\n" +
- "@Override\n");
- result.append(
- format("public %s createModule(String instanceName, %s dependencyResolver, %s old, %s bundleContext) "
- + "throws Exception {\n",
- Module.class.getCanonicalName(), DependencyResolver.class.getCanonicalName(),
- DynamicMBeanWithInstance.class.getCanonicalName(), BUNDLE_CONTEXT))
- .append(format("%s oldModule;\n", moduleFQN))
- .append("try {\n")
- .append(format("oldModule = (%s) old.getModule();\n", moduleFQN))
- .append("} catch(Exception e) {\n"
- + "return handleChangedClass(dependencyResolver, old, bundleContext);\n"
- + "}\n")
- .append(format("%s module = instantiateModule(instanceName, dependencyResolver, oldModule, old"
- + ".getInstance(), bundleContext);\n",
- moduleFQN));
-
- for (Field field : moduleFields) {
- result.append(format("module.set%s(oldModule.get%1$s());\n", field.getName()));
- }
-
- result.append("\n"
- + "return module;\n"
- + "}\n");
- return result.toString();
- }
-
- private static String getServiceIfcsInitialization(List<FullyQualifiedName> providedServices) {
- String generic = format("Class<? extends %s>", AbstractServiceInterface.class.getCanonicalName());
-
- StringBuilder result = new StringBuilder("static {\n");
- if (!providedServices.isEmpty()) {
- result.append(format("java.util.Set<%1$s> serviceIfcs2 = new java.util.HashSet<>();\n", generic));
-
- for (FullyQualifiedName fqn : providedServices) {
- result.append(format("serviceIfcs2.add(%s.class);\n", fqn));
- }
-
- result.append("serviceIfcs = java.util.Collections.unmodifiableSet(serviceIfcs2);\n");
- } else {
- result.append("serviceIfcs = java.util.Collections.emptySet();\n");
- }
- result.append("}\n");
-
- // add isModuleImplementingServiceInterface and getImplementedServiceIntefaces methods
-
- result.append(format("\n"
- + "@Override\n"
- + "public final boolean isModuleImplementingServiceInterface(Class<? extends %1$s> serviceInterface) "
- + "{\n"
- + "for (Class<?> ifc: serviceIfcs) {\n"
- + "if (serviceInterface.isAssignableFrom(ifc)){\n"
- + "return true;\n"
- + "}\n"
- + "}\n"
- + "return false;\n"
- + "}\n"
- + "\n"
- + "@Override\n"
- + "public java.util.Set<Class<? extends %1$s>> getImplementedServiceIntefaces() {\n"
- + "return serviceIfcs;\n"
- + "}\n", AbstractServiceInterface.class.getCanonicalName()));
-
- return result.toString();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory;
-
-import static com.google.common.base.Preconditions.checkState;
-import static java.lang.String.format;
-
-import com.google.common.base.Joiner;
-import com.google.common.base.Optional;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.api.annotations.Description;
-import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.AbstractModuleTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.IdentityRefModuleField;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Method;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.ModuleField;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObjectBuilder;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.JavaFileInputBuilder;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.TypeName;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AbsModuleGeneratedObjectFactory {
-
- public GeneratedObject toGeneratedObject(ModuleMXBeanEntry mbe, Optional<String> copyright) {
- FullyQualifiedName abstractFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getAbstractModuleName());
- Optional<String> classJavaDoc = Optional.fromNullable(mbe.getNullableDescription());
- AbstractModuleTemplate abstractModuleTemplate = TemplateFactory.abstractModuleTemplateFromMbe(mbe);
- Optional<String> header = abstractModuleTemplate.getHeaderString();
-
- List<FullyQualifiedName> implementedInterfaces =
- Lists.transform(abstractModuleTemplate.getTypeDeclaration().getImplemented(),
- FullyQualifiedName::fromString);
-
- Optional<FullyQualifiedName> extended =
- Optional.fromNullable(
- Iterables.getFirst(
- Collections2.transform(abstractModuleTemplate.getTypeDeclaration().getExtended(),
- FullyQualifiedName::fromString), null));
-
- Optional<FullyQualifiedName> maybeRegistratorType;
- if (abstractModuleTemplate.isRuntime()) {
- maybeRegistratorType = Optional.of(FullyQualifiedName.fromString(abstractModuleTemplate.getRegistratorType()));
- } else {
- maybeRegistratorType = Optional.absent();
- }
-
- return toGeneratedObject(abstractFQN, copyright, header, classJavaDoc, extended, implementedInterfaces,
- abstractModuleTemplate.getModuleFields(), maybeRegistratorType, abstractModuleTemplate.getMethods(),
- mbe.getYangModuleQName());
- }
-
- public GeneratedObject toGeneratedObject(FullyQualifiedName abstractFQN,
- Optional<String> copyright,
- Optional<String> header,
- Optional<String> classJavaDoc,
- Optional<FullyQualifiedName> extended,
- List<FullyQualifiedName> implementedInterfaces,
- List<ModuleField> moduleFields,
- Optional<FullyQualifiedName> maybeRegistratorType,
- List<? extends Method> methods,
- QName yangModuleQName) {
- JavaFileInputBuilder b = new JavaFileInputBuilder();
-
- Annotation moduleQNameAnnotation = Annotation.createModuleQNameANnotation(yangModuleQName);
- b.addClassAnnotation(moduleQNameAnnotation);
-
- b.setFqn(abstractFQN);
- b.setTypeName(TypeName.absClassType);
-
- b.setCopyright(copyright);
- b.setHeader(header);
- b.setClassJavaDoc(classJavaDoc);
- for(FullyQualifiedName implemented: implementedInterfaces) {
- b.addImplementsFQN(implemented);
- }
- if(extended.isPresent()) {
- b.addExtendsFQN(extended.get());
- }
- if (classJavaDoc.isPresent()) {
- b.addClassAnnotation(format("@%s(value=\"%s\")", Description.class.getCanonicalName(), classJavaDoc.get()));
- }
-
- // add logger:
- b.addToBody(getLoggerDefinition(abstractFQN));
-
- b.addToBody("//attributes start");
- for(ModuleField moduleField: moduleFields) {
- b.addToBody(moduleField.toString() +"\n");
- }
-
- b.addToBody("//attributes end");
-
-
- b.addToBody(getNewConstructor(abstractFQN));
- b.addToBody(getCopyFromOldConstructor(abstractFQN));
-
- b.addToBody(getRuntimeRegistratorCode(maybeRegistratorType));
- b.addToBody(getValidationMethods(moduleFields));
-
- b.addToBody(getCachesOfResolvedDependencies(moduleFields));
- b.addToBody(getCachesOfResolvedIdentityRefs(moduleFields));
- b.addToBody(getResolveDependencies(moduleFields));
- b.addToBody(getReuseLogic(moduleFields, abstractFQN));
- b.addToBody(getEqualsAndHashCode(abstractFQN));
-
- b.addToBody(getMethods(methods));
- b.addToBody(getGetLogger());
-
- return new GeneratedObjectBuilder(b.build()).toGeneratedObject();
- }
-
- private static String getMethods(List<? extends Method> methods) {
- StringBuilder result = new StringBuilder("\n// getters and setters\n");
- for (Method method : methods) {
- result.append(method).append("\n");
- }
- return result.toString();
- }
-
- private static String getEqualsAndHashCode(FullyQualifiedName abstractFQN) {
- return "\n"+
- "@Override\n"+
- "public boolean equals(Object o) {\n"+
- "if (this == o) { return true; }\n"+
- "if (o == null || getClass() != o.getClass()) { return false; }\n"+
- format("%s that = (%1$s) o;\n", abstractFQN.getTypeName())+
- "return identifier.equals(that.identifier);\n"+
- "}\n"+
- "\n"+
- "@Override\n"+
- "public int hashCode() {\n"+
- "return identifier.hashCode();\n"+
- "}\n";
- }
-
- private static String getReuseLogic(List<ModuleField> moduleFields, FullyQualifiedName abstractFQN) {
- StringBuilder result = new StringBuilder("\n" +
- format("public boolean canReuseInstance(%s oldModule){\n", abstractFQN.getTypeName()) +
- "// allow reusing of old instance if no parameters was changed\n" +
- "return isSame(oldModule);\n" +
- "}\n" +
- "\n" +
- format("public %s reuseInstance(%1$s oldInstance){\n", AutoCloseable.class.getCanonicalName()) +
- "// implement if instance reuse should be supported." +
- "Override canReuseInstance to change the criteria.\n" +
- "return oldInstance;\n" +
- "}\n");
- // isSame method that detects changed fields
- result.append("\n")
- .append(format("public boolean isSame(%s other) {\n", abstractFQN.getTypeName()))
- .append("if (other == null) {\n")
- .append("throw new IllegalArgumentException(\"Parameter 'other' is null\");\n")
- .append("}\n");
-
- // loop through fields, do deep equals on each field
- for (ModuleField moduleField : moduleFields) {
- result.append(format(
- "if (!java.util.Objects.deepEquals(%s, other.%1$s)) {\n" +
- "return false;\n" +
- "}\n", moduleField.getName()));
-
- if (moduleField.isListOfDependencies()) {
- result.append(format(
- "for (int idx = 0; idx < %1$s.size(); idx++) {\n" +
- "if (!dependencyResolver.canReuseDependency(%1$s.get(idx), %1$sJmxAttribute)) {\n" +
- "return false;\n" +
- "}\n" +
- "}\n", moduleField.getName()));
- } else if (moduleField.isDependent()) {
- result.append(format(
- // If a reference is null (ie optional reference) it makes no sens to call canReuse on it
- // In such case we continue in the isSame method because if we have null here, the previous
- // value was null as well
- // If the previous value was not null and current is or vice verse, the deepEquals comparison
- // would return false
- "if(%1$s!= null) {\n" +
- "// reference to dependency must be reusable as well\n" +
- "if (!dependencyResolver.canReuseDependency(%1$s, %1$sJmxAttribute)) {\n" +
- "return false;\n" +
- "}\n" +
- "}\n", moduleField.getName()));
- }
- }
-
- result.append("\n" +
- "return true;\n" +
- "}\n");
-
- return result.toString();
- }
-
- private static String getResolveDependencies(final List<ModuleField> moduleFields) {
- // loop through dependent fields, use dependency resolver to instantiate dependencies. Do it in loop in case field represents list of dependencies.
- Map<ModuleField, String> resolveDependenciesMap = new HashMap<>();
- for(ModuleField moduleField: moduleFields) {
- if (moduleField.isDependent()) {
- String str;
- String osgi = moduleField.getDependency().getSie().getExportedOsgiClassName();
- if (moduleField.isList()) {
- str = format(
- "%sDependency = new java.util.ArrayList<%s>();\n"+
- "for(javax.management.ObjectName dep : %1$s) {\n"+
- "%1$sDependency.add(dependencyResolver.resolveInstance(%2$s.class, dep, %1$sJmxAttribute));\n"+
- "}\n", moduleField.getName(), osgi);
- } else {
- str = format(
- "%1$sDependency = dependencyResolver.resolveInstance(%2$s.class, %1$s, %1$sJmxAttribute);\n",
- moduleField.getName(), osgi);
- }
- resolveDependenciesMap.put(moduleField, str);
- }
- }
-
- StringBuilder result = new StringBuilder("\n" +
- "protected final void resolveDependencies() {\n");
- // wrap each field resolvation statement with if !=null when dependency is not mandatory
- for (Map.Entry<ModuleField, String> entry : resolveDependenciesMap.entrySet()) {
- if (!entry.getKey().getDependency().isMandatory()) {
- checkState(entry.getValue().endsWith(";\n"));
- result.append(format("if (%s!=null) {\n%s}\n", entry.getKey().getName(), entry.getValue()));
- } else {
- result.append(entry.getValue());
- }
- }
-
- // add code to inject dependency resolver to fields that support it
- for(ModuleField moduleField: moduleFields) {
- if (moduleField.isNeedsDepResolver()) {
- result.append(format("if (%s!=null){\n", moduleField.getName()));
- if (moduleField.isList()) {
- result.append(format(
- "for(%s candidate : %s) {\n" +
- "candidate.injectDependencyResolver(dependencyResolver);\n" +
- "}\n", moduleField.getGenericInnerType(), moduleField.getName()));
- } else {
- result.append(format("%s.injectDependencyResolver(dependencyResolver);\n", moduleField.getName()));
- }
- result.append("}\n");
- }
- }
-
- // identity refs need to be injected with dependencyResolver and base class
- for (ModuleField moduleField : moduleFields) {
- if (moduleField.isIdentityRef()) {
- result.append(format("if (%s!=null) {", moduleField.getName()));
- result.append(format("set%s(%s.resolveIdentity(dependencyResolver, %s.class));",
- moduleField.getAttributeName(), moduleField.getName(),
- ((IdentityRefModuleField) moduleField).getIdentityBaseClass()));
- result.append("}\n");
- }
- }
- result.append("}\n");
- return result.toString();
- }
-
- private static String getCachesOfResolvedIdentityRefs(List<ModuleField> moduleFields) {
- StringBuilder result = new StringBuilder();
- for (ModuleField moduleField : moduleFields) {
- if (moduleField.isIdentityRef()) {
- IdentityRefModuleField field = (IdentityRefModuleField) moduleField;
- result.append(format("private %s %s;\n", field.getIdentityClassType(), field.getIdentityClassName()));
- }
- }
- return result.toString();
- }
-
- private static String getCachesOfResolvedDependencies(List<ModuleField> moduleFields) {
- StringBuilder result = new StringBuilder();
- for (ModuleField moduleField: moduleFields) {
- if (moduleField.isDependent()) {
- String osgi = moduleField.getDependency().getSie().getExportedOsgiClassName();
- if (moduleField.isList()) {
- result
- .append(format("private java.util.List<%s> %sDependency = new java.util.ArrayList<%s>();", osgi, moduleField.getName(), osgi))
- .append(format("protected final java.util.List<%s> get%sDependency(){\n", osgi, moduleField.getAttributeName()))
- .append(format("return %sDependency;\n", moduleField.getName()))
- .append("}\n");
- } else {
- result.append(format(
- "private %s %sDependency;\n"+
- "protected final %s get%sDependency(){\n"+
- "return %sDependency;\n"+
- "}",
- osgi, moduleField.getName(), osgi, moduleField.getAttributeName(), moduleField.getName()));
- }
- }
- }
- return result.toString();
- }
-
- private static String getRuntimeRegistratorCode(Optional<FullyQualifiedName> maybeRegistratorType) {
- if (maybeRegistratorType.isPresent()) {
- String registratorType = maybeRegistratorType.get().toString();
-
- return "\n"+
- format("private %s rootRuntimeBeanRegistratorWrapper;\n", registratorType)+
- "\n"+
- format("public %s getRootRuntimeBeanRegistratorWrapper(){\n", registratorType)+
- "return rootRuntimeBeanRegistratorWrapper;\n"+
- "}\n"+
- "\n"+
- "@Override\n"+
- format("public void setRuntimeBeanRegistrator(%s rootRuntimeRegistrator){\n", RootRuntimeBeanRegistrator.class.getCanonicalName())+
- format("this.rootRuntimeBeanRegistratorWrapper = new %s(rootRuntimeRegistrator);\n", registratorType)+
- "}\n";
- } else {
- return "";
- }
- }
-
- private static String getValidationMethods(List<ModuleField> moduleFields) {
- StringBuilder result = new StringBuilder("\n" +
- "@Override\n" +
- "public void validate() {\n");
- // validate each mandatory dependency
- for (ModuleField moduleField : moduleFields) {
- if (moduleField.isDependent()) {
- if (moduleField.isList()) {
- result.append(format("for(javax.management.ObjectName dep : %s) {\n", moduleField.getName()))
- .append(format(" dependencyResolver.validateDependency(%s.class, dep, %sJmxAttribute);" +
- "\n",
- moduleField.getDependency().getSie().getFullyQualifiedName(),
- moduleField.getName()))
- .append("}\n");
- } else {
- if (!moduleField.getDependency().isMandatory()) {
- result.append(format("if(%s != null) {\n", moduleField.getName()));
- }
- result.append(format("dependencyResolver.validateDependency(%s.class, %s, %sJmxAttribute);\n",
- moduleField.getDependency().getSie().getFullyQualifiedName(), moduleField.getName(),
- moduleField.getName()));
- if (!moduleField.getDependency().isMandatory()) {
- result.append("}\n");
- }
- }
- }
- }
- result.append("\n" +
- "customValidation();\n" +
- "}\n" +
- "\n" +
- "protected void customValidation() {\n" +
- "}\n");
- return result.toString();
- }
-
- private static String getLoggerDefinition(FullyQualifiedName fqn) {
- return format("private static final %s LOG = %s.getLogger(%s.class);",
- Logger.class.getCanonicalName(), LoggerFactory.class.getCanonicalName(), fqn);
- }
-
- // assumes that each parameter name corresponds to an field in this class, constructs lines setting this.field = field;
- private static String getConstructorStart(FullyQualifiedName fqn,
- LinkedHashMap<String, String> parameters, String after) {
- String paramString = Joiner.on(",").withKeyValueSeparator(" ").join(parameters);
- return format("public %s(", fqn.getTypeName()) +
- paramString +
- ") {\n" +
- after +
- "}\n";
- }
-
- private static String getNewConstructor(FullyQualifiedName abstractFQN) {
- LinkedHashMap<String, String> parameters = new LinkedHashMap<>();
- parameters.put(ModuleIdentifier.class.getCanonicalName(), "identifier");
- parameters.put(DependencyResolver.class.getCanonicalName(), "dependencyResolver");
- String init = "super(identifier, dependencyResolver);\n";
- return getConstructorStart(abstractFQN, parameters, init);
- }
-
- private static String getCopyFromOldConstructor(FullyQualifiedName abstractFQN) {
- LinkedHashMap<String, String> parameters = new LinkedHashMap<>();
- parameters.put(ModuleIdentifier.class.getCanonicalName(), "identifier");
- parameters.put(DependencyResolver.class.getCanonicalName(), "dependencyResolver");
- parameters.put(abstractFQN.getTypeName(), "oldModule");
- parameters.put(AutoCloseable.class.getCanonicalName(), "oldInstance");
- String init = "super(identifier, dependencyResolver, oldModule, oldInstance);\n";
- return getConstructorStart(abstractFQN, parameters, init);
- }
-
- public String getGetLogger() {
- return new MethodDefinition(Logger.class.getCanonicalName(), "getLogger", Collections.<Field>emptyList(), "return LOG;").toString();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory;
-
-import com.google.common.base.Joiner;
-import com.google.common.base.Optional;
-import java.util.LinkedHashMap;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.ModuleIdentifier;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObjectBuilder;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.JavaFileInputBuilder;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.TypeName;
-
-public class ConcreteModuleGeneratedObjectFactory {
-
- public GeneratedObject toGeneratedObject(ModuleMXBeanEntry mbe, Optional<String> copyright, Optional<String> header) {
- FullyQualifiedName concreteFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getStubModuleName());
- FullyQualifiedName abstractFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getAbstractModuleName());
- Optional<String> classJavaDoc = Optional.fromNullable(mbe.getNullableDescription());
- return toGeneratedObject(concreteFQN, abstractFQN, copyright, header, classJavaDoc);
- }
-
- GeneratedObject toGeneratedObject(FullyQualifiedName concreteFQN,
- FullyQualifiedName abstractFQN,
- Optional<String> copyright,
- Optional<String> header,
- Optional<String> classJavaDoc) {
- // there are two constructors and two methods
- JavaFileInputBuilder builder = new JavaFileInputBuilder();
- builder.setTypeName(TypeName.classType);
- builder.setFqn(concreteFQN);
- builder.addExtendsFQN(abstractFQN);
-
- builder.setCopyright(copyright);
- builder.setHeader(header);
- builder.setClassJavaDoc(classJavaDoc);
-
- builder.addToBody(getNewCtor(concreteFQN));
- builder.addToBody(getCopyCtor(concreteFQN));
- builder.addToBody(getCustomValidationStub());
- builder.addToBody(getCreateInstanceStub());
-
- return new GeneratedObjectBuilder(builder.build()).toGeneratedObject();
- }
-
- private static String getNewCtor(FullyQualifiedName fqn) {
- LinkedHashMap<String, String> parameters = new LinkedHashMap<>();
- parameters.put(ModuleIdentifier.class.getCanonicalName(), "identifier");
- parameters.put(DependencyResolver.class.getCanonicalName(), "dependencyResolver");
-
- StringBuilder stringBuilder = getCtor(fqn, parameters);
- return stringBuilder.toString();
- }
-
- private static StringBuilder getCtor(FullyQualifiedName fqn , LinkedHashMap<String, String> parameters) {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("public ").append(fqn.getTypeName()).append("(");
- // parameters
- stringBuilder.append(Joiner.on(", ").withKeyValueSeparator(" ").join(parameters));
- stringBuilder.append(") {\n");
- if (!parameters.isEmpty()) {
- stringBuilder.append("super(");
- stringBuilder.append(Joiner.on(", ").join(parameters.values()));
- stringBuilder.append(");\n");
- }
- stringBuilder.append("}");
- return stringBuilder;
- }
-
- private static String getCopyCtor(final FullyQualifiedName fqn) {
- LinkedHashMap<String, String> parameters = new LinkedHashMap<>();
- parameters.put(ModuleIdentifier.class.getCanonicalName(), "identifier");
- parameters.put(DependencyResolver.class.getCanonicalName(), "dependencyResolver");
- parameters.put(fqn.toString(), "oldModule");
- parameters.put(AutoCloseable.class.getCanonicalName(), "oldInstance");
- StringBuilder stringBuilder = getCtor(fqn, parameters);
- return stringBuilder.toString();
- }
-
- private static String getCustomValidationStub() {
- return "@Override\n" +
- "public void customValidation() {\n" +
- "// add custom validation form module attributes here.\n" +
- "}";
- }
-
- private static String getCreateInstanceStub() {
- return "@Override\n" +
- "public " + AutoCloseable.class.getCanonicalName() + " createInstance() {\n" +
- "// TODO:implement\n" +
- "throw new " + UnsupportedOperationException.class.getCanonicalName() + "();\n"+
- "}";
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Method;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObjectBuilder;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.JavaFileInputBuilder;
-
-public class GenericGeneratedObjectFactory {
-
- public GeneratedObject toGeneratedObject(FtlTemplate template, Optional<String> copyright) {
- JavaFileInputBuilder b = new JavaFileInputBuilder();
- b.setHeader(template.getHeaderString());
- b.setFqn(new FullyQualifiedName(template.getPackageName(), template.getTypeDeclaration().getName()));
- b.setClassJavaDoc(template.getMaybeJavadoc());
- for (Annotation annotation : template.getAnnotations()) {
- b.addClassAnnotation(annotation);
- }
- // type declaration
- for (String extended : template.getTypeDeclaration().getExtended()) {
- b.addExtendsFQN(FullyQualifiedName.fromString(extended));
- }
- for (String implemented : template.getTypeDeclaration().getImplemented()) {
- b.addImplementsFQN(FullyQualifiedName.fromString(implemented));
- }
- b.setCopyright(copyright);
- b.setTypeName(template.getTypeDeclaration().toTypeName());
- // fields
- for (Field field : template.getFields()) {
- b.addToBody(field.toString());
- }
- // constructors
- for (Constructor constructor : template.getConstructors()) {
- b.addToBody(constructor.toString());
- }
- // methods
- for (Method method : template.getMethods()) {
- b.addToBody(method.toString());
- }
- return new GeneratedObjectBuilder(b.build()).toGeneratedObject();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.io.File;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class FullyQualifiedName {
-
- private final String packageName;
- private final String typeName;
-
- public FullyQualifiedName(String packageName, String typeName) {
- this.packageName = checkNotNull(packageName);
- this.typeName = checkNotNull(typeName);
- }
-
- public FullyQualifiedName(Class<?> clazz) {
- this(clazz.getPackage().getName(), clazz.getSimpleName());
- }
-
- public static FullyQualifiedName fromString(String fqn) {
- Matcher m = Pattern.compile("(.*)\\.([^\\.]+)$").matcher(fqn);
- if (m.matches()) {
- return new FullyQualifiedName(m.group(1), m.group(2));
- } else {
- return new FullyQualifiedName("", fqn);
- }
- }
-
- public String getPackageName() {
- return packageName;
- }
-
- public String getTypeName() {
- return typeName;
- }
-
- public File toFile(File srcDirectory) {
- String directory = packageName.replace(".", File.separator);
- return new File(srcDirectory, directory + File.separator + typeName + ".java");
- }
-
-
- @Override
- public String toString() {
- if (packageName.isEmpty()){
- return typeName;
- }
- return packageName + "." + typeName;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- FullyQualifiedName that = (FullyQualifiedName) o;
-
- if (!packageName.equals(that.packageName)) {
- return false;
- }
- if (!typeName.equals(that.typeName)) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = packageName.hashCode();
- result = 31 * result + typeName.hashCode();
- return result;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.Maps;
-import com.google.common.io.Files;
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.util.Map.Entry;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil;
-
-public class GeneratedObject {
-
- private final FullyQualifiedName fqn;
- private final String content;
-
- public GeneratedObject(FullyQualifiedName fqn, String content) {
- this.fqn = checkNotNull(fqn);
- this.content = StringUtil.formatJavaSource(checkNotNull(content));
- }
-
- public FullyQualifiedName getFQN(){
- return fqn;
- }
-
- public String getContent() {
- return content;
- }
-
- public Optional<Entry<FullyQualifiedName,File>> persist(File srcDirectory, boolean overwrite) throws IOException {
- File dstFile = fqn.toFile(srcDirectory);
- if (overwrite || !dstFile.exists()) {
- Files.createParentDirs(dstFile);
- Files.touch(dstFile);
- Files.write(content, dstFile, StandardCharsets.UTF_8);
- return Optional.of(Maps.immutableEntry(fqn, dstFile));
- } else {
- return Optional.absent();
- }
- }
-
- public Optional<Entry<FullyQualifiedName,File>> persist(File srcDirectory) throws IOException {
- return persist(srcDirectory, true);
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "fqn=" + fqn +
- '}';
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- GeneratedObject that = (GeneratedObject) o;
-
- return fqn.equals(that.fqn);
-
- }
-
- @Override
- public int hashCode() {
- return fqn.hashCode();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
-
-import static org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil.prefixAndJoin;
-
-import com.google.common.base.Optional;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.StringUtil;
-
-public class GeneratedObjectBuilder {
- private final JavaFileInput input;
-
- public GeneratedObjectBuilder(JavaFileInput input) {
- this.input = input;
- }
-
-
- public GeneratedObject toGeneratedObject() {
- FullyQualifiedName fqn = input.getFQN();
- StringBuilder content = new StringBuilder();
-
-
- content.append(maybeAddComment(input.getCopyright()));
- content.append(maybeAddComment(input.getHeader()));
-
- if (!input.getFQN().getPackageName().isEmpty()) {
- content.append("package ");
- content.append(input.getFQN().getPackageName());
- content.append(";\n");
- }
-
- if (!input.getImports().isEmpty())
- content.append('\n');
- for (FullyQualifiedName importedType : input.getImports()) {
- content.append("import ");
- content.append(importedType.toString());
- content.append(";\n");
- }
- if (!input.getImports().isEmpty())
- content.append('\n');
-
- content.append(maybeAddComment(input.getClassJavaDoc(), true));
-
- for (String classAnnotation : input.getClassAnnotations()) {
- content.append(classAnnotation);
- content.append("\n");
- }
-
- content.append("public ");
- content.append(input.getType());
- content.append(" ");
- content.append(input.getFQN().getTypeName());
- content.append(prefixAndJoin(input.getExtends(), "extends"));
- content.append(prefixAndJoin(input.getImplements(), "implements"));
- content.append(" {\n");
-
- for (String method : input.getBodyElements()) {
- content.append(method);
- content.append("\n");
- }
-
- content.append("\n}\n");
-
- return new GeneratedObject(fqn, content.toString());
- }
-
- private static String maybeAddComment(Optional<String> comment) {
- return maybeAddComment(comment, false);
- }
-
- private static String maybeAddComment(Optional<String> comment, boolean isJavadoc) {
- if (comment.isPresent()) {
- String input = comment.get();
- return StringUtil.writeComment(input, isJavadoc);
- } else {
- return "";
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
-
-import com.google.common.base.Optional;
-import java.util.List;
-
-public interface JavaFileInput {
-
- FullyQualifiedName getFQN();
-
- Optional<String> getCopyright();
-
- Optional<String> getHeader();
-
- List<FullyQualifiedName> getImports();
-
- TypeName getType();
-
- Optional<String> getClassJavaDoc();
-
- List<String> getClassAnnotations();
-
- List<FullyQualifiedName> getExtends();
-
- List<FullyQualifiedName> getImplements();
-
- List<String> getBodyElements();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import com.google.common.base.Optional;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
-
-public class JavaFileInputBuilder {
-
- private Optional<String> copyright = Optional.absent(), header = Optional.absent(), classJavaDoc = Optional.absent();
-
- private TypeName typeName = TypeName.classType;
-
- private FullyQualifiedName fqn;
-
- private final List<String> classAnnotations = new ArrayList<>();
-
- private final List<FullyQualifiedName> importFQNs = new ArrayList<>();
-
- private final List<FullyQualifiedName> extendsFQNs = new ArrayList<>();
-
- private final List<FullyQualifiedName> implementsFQNs = new ArrayList<>();
-
- private final List<String> bodyElements = new ArrayList<>();
-
- public void addToBody(String element) {
- bodyElements.add(element + "\n");
- }
-
- public void addClassAnnotation(Annotation annotation) {
- addClassAnnotation(annotation.toString());
- }
-
- public void addClassAnnotation(String annotation) {
- classAnnotations.add(checkNotNull(annotation));
- }
-
- public void addImportFQN(FullyQualifiedName fqn) {
- importFQNs.add(fqn);
- }
-
- public void addExtendsFQN(FullyQualifiedName fqn) {
- extendsFQNs.add(fqn);
- }
-
- public void addImplementsFQN(FullyQualifiedName fqn) {
- implementsFQNs.add(fqn);
- }
-
- public Optional<String> getCopyright() {
- return copyright;
- }
-
- public void setCopyright(Optional<String> copyright) {
- this.copyright = checkNotNull(copyright);
- }
-
- public Optional<String> getHeader() {
- return header;
- }
-
- public void setHeader(Optional<String> header) {
- this.header = checkNotNull(header);
- }
-
-
- public Optional<String> getClassJavaDoc() {
- return classJavaDoc;
- }
-
- public void setClassJavaDoc(Optional<String> classJavaDoc) {
- this.classJavaDoc = checkNotNull(classJavaDoc);
- }
-
-
- public FullyQualifiedName getFqn() {
- return fqn;
- }
-
- public void setFqn(FullyQualifiedName fqn) {
- this.fqn = fqn;
- }
-
- public List<FullyQualifiedName> getExtendsFQNs() {
- return extendsFQNs;
- }
-
-
- public List<FullyQualifiedName> getImplementsFQNs() {
- return implementsFQNs;
- }
-
-
- public TypeName getTypeName() {
- return typeName;
- }
-
- public void setTypeName(TypeName typeName) {
- this.typeName = typeName;
- }
-
-
- public JavaFileInput build() {
- checkNotNull(copyright);
- checkNotNull(header);
- checkNotNull(classJavaDoc);
- checkNotNull(typeName);
- checkNotNull(fqn);
-
- return new JavaFileInput() {
-
- @Override
- public FullyQualifiedName getFQN() {
- return fqn;
- }
-
- @Override
- public Optional<String> getCopyright() {
- return copyright;
- }
-
- @Override
- public Optional<String> getHeader() {
- return header;
- }
-
- @Override
- public List<FullyQualifiedName> getImports() {
- return Collections.unmodifiableList(importFQNs);
- }
-
- @Override
- public Optional<String> getClassJavaDoc() {
- return classJavaDoc;
- }
-
- @Override
- public TypeName getType() {
- return typeName;
- }
-
- @Override
- public List<FullyQualifiedName> getExtends() {
- return Collections.unmodifiableList(extendsFQNs);
- }
-
- @Override
- public List<FullyQualifiedName> getImplements() {
- return Collections.unmodifiableList(implementsFQNs);
- }
-
- @Override
- public List<String> getClassAnnotations() {
- return Collections.unmodifiableList(classAnnotations);
- }
-
- @Override
- public List<String> getBodyElements() {
- return Collections.unmodifiableList(bodyElements);
- }
-
- };
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.java;
-
-public enum TypeName {
-
- classType("class"), interfaceType("interface"), enumType("enum"), absClassType("abstract class"), finalClassType("final class");
-
- private final String value;
-
- TypeName(String value) {
- this.value = value;
- }
-
- @Override
- public String toString() {
- return value;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
-
-import com.google.common.base.Joiner;
-import com.google.common.base.Optional;
-import com.google.common.base.Splitter;
-import com.google.common.base.Strings;
-import java.util.List;
-import java.util.regex.Pattern;
-import org.apache.commons.lang3.StringUtils;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
-
-public final class StringUtil {
- private StringUtil() {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @param list of strings to be joined by ','
- * @param prefix e.g. 'extends' or 'implements'
- */
- public static String prefixAndJoin(final List<FullyQualifiedName> list, final String prefix) {
- if (list.isEmpty()) {
- return "";
- }
- Joiner joiner = Joiner.on(",");
- return " " + prefix + " " + joiner.join(list);
- }
-
- public static String addAsterixAtEachLineStart(final String input) {
- String s = Pattern.compile("^", Pattern.MULTILINE).matcher(input).replaceAll("* ");
- // remove trailing spaces
- s = Pattern.compile("\\s+$", Pattern.MULTILINE).matcher(s).replaceAll("");
- s = ensureEndsWithSingleNewLine(s);
- return s;
- }
-
- private static String ensureEndsWithSingleNewLine(String s) {
- // .split Only trailing empty strings are skipped.
- String[] split = s.split("\n");
- s = Joiner.on("\n").join(split);
- s = s + "\n";
- return s;
- }
-
- public static String writeComment(final String input, final boolean isJavadoc) {
- StringBuilder content = new StringBuilder();
- content.append("/*");
- if (isJavadoc) {
- content.append("*");
- }
- content.append("\n");
-
- content.append(addAsterixAtEachLineStart(input));
- content.append("*/\n");
- return content.toString();
- }
-
-
- public static Optional<String> loadCopyright() {
- /*
- * FIXME: BUG-980: this is a nice feature, but the copyright needs to come
- * from the project being processed, not this one.
- try (InputStream in = StringUtil.class.getResourceAsStream("/copyright.txt")) {
- if (in != null) {
- return Optional.of(IOUtils.toString(in));
- }
- } catch (IOException e) {
- LOG.warn("Cannot load copyright.txt", e);
- }
-
- */
- return Optional.absent();
- }
-
- public static String formatJavaSource(final String input) {
- Iterable<String> split = Splitter.on("\n").trimResults().split(input);
-
- int basicIndent = 4;
- StringBuilder sb = new StringBuilder();
- int indents = 0, empty = 0;
- for (String line : split) {
- indents -= StringUtils.countMatches(line, "}");
- if (indents < 0) {
- indents = 0;
- }
- if (!line.isEmpty()) {
- sb.append(Strings.repeat(" ", basicIndent * indents));
- sb.append(line);
- sb.append("\n");
- empty = 0;
- } else {
- empty++; // one empty line is allowed
- if (empty < 2) {
- sb.append("\n");
- }
- }
- indents += StringUtils.countMatches(line, "{");
- }
- return ensureEndsWithSingleNewLine(sb.toString());
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import java.io.File;
-import org.junit.Before;
-import org.opendaylight.controller.config.yangjmxgenerator.AbstractYangTest;
-
-public abstract class AbstractGeneratorTest extends AbstractYangTest {
- private static final File GENERATOR_OUTPUT_PATH_ROOT = new File("target/testgen");
- protected final File generatorOutputPath;
-
- public AbstractGeneratorTest() {
- generatorOutputPath = new File(GENERATOR_OUTPUT_PATH_ROOT, getClass().getSimpleName());
- }
-
- @Before
- public void cleanUpDirectory() throws Exception {
- deleteFolder(generatorOutputPath);
- }
-
- public void deleteFolder(final File folder) {
- File[] files = folder.listFiles();
- if (files != null) {
- for (File f : files) {
- if (f.isDirectory()) {
- deleteFolder(f);
- } else {
- f.delete();
- }
- }
- }
- folder.delete();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Pantheon Technologies s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import static org.junit.Assert.assertEquals;
-import com.github.javaparser.ast.PackageDeclaration;
-import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
-import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
-import com.google.common.base.Preconditions;
-
-abstract class AbstractVerifier extends VoidVisitorAdapter<Void> {
- private final String expectedPackageName;
- private final String expectedType;
- private String packageName;
- private String type;
-
- AbstractVerifier(final String expectedPackageName, final String fileName) {
- this.expectedPackageName = Preconditions.checkNotNull(expectedPackageName);
- this.expectedType = fileName.substring(0, fileName.length() - 5);
- }
-
- @Override
- public void visit(final ClassOrInterfaceDeclaration n, final Void arg) {
- type = n.getName();
- super.visit(n, arg);
- }
-
- @Override
- public final void visit(final PackageDeclaration n, final Void arg) {
- packageName = n.getName().toString();
- super.visit(n, arg);
- }
-
- void verify() {
- assertEquals(expectedPackageName, packageName);
- assertEquals(expectedType, type);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import com.google.common.collect.ImmutableSet;
-import java.util.Optional;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants;
-import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslatorTest;
-
-public class JMXGeneratorFileNamesValidationTest extends JMXGeneratorTest {
-
- @Test
- public void test() {
- map.clear();
- map.put(JMXGenerator.NAMESPACE_TO_PACKAGE_PREFIX + "1",
- ConfigConstants.CONFIG_NAMESPACE + ":test:files1"
- + JMXGenerator.NAMESPACE_TO_PACKAGE_DIVIDER
- + PackageTranslatorTest.EXPECTED_PACKAGE_PREFIX);
- map.put(JMXGenerator.NAMESPACE_TO_PACKAGE_PREFIX + "2",
- ConfigConstants.CONFIG_NAMESPACE + ":test:files"
- + JMXGenerator.NAMESPACE_TO_PACKAGE_DIVIDER
- + PackageTranslatorTest.EXPECTED_PACKAGE_PREFIX);
-
- map.put(JMXGenerator.MODULE_FACTORY_FILE_BOOLEAN, "randomValue");
- jmxGenerator.setAdditionalConfig(map);
- try {
- jmxGenerator.generateSources(context, outputBaseDir, ImmutableSet.of(testFilesModule, testFiles1Module),
- m -> Optional.empty());
- fail();
- } catch (RuntimeException e) {
- final Throwable cause = e.getCause();
- assertNotNull(cause);
- assertTrue(cause.toString() + " is unexpected", cause instanceof IllegalStateException);
- assertThat(cause.getMessage(),
- containsString("Name conflict in generated files"));
- assertThat(cause.getMessage(), containsString("DtoA.java"));
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.File;
-import org.junit.Test;
-
-public class JMXGeneratorGeneratedFilesTrackerTest {
-
- @Test(expected = IllegalStateException.class)
- public void testGeneratedFilesTracker() throws Exception {
- JMXGenerator.GeneratedFilesTracker tracker = new JMXGenerator.GeneratedFilesTracker();
-
- tracker.addFile(new File("./a/b/c"));
- assertEquals(1, tracker.getFiles().size());
- tracker.addFile(new File("./a/b/c"));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.opendaylight.controller.config.yangjmxgenerator.PackageTranslatorTest.EXPECTED_PACKAGE_PREFIX;
-
-import com.github.javaparser.JavaParser;
-import com.github.javaparser.ParseException;
-import com.github.javaparser.ast.CompilationUnit;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.io.Files;
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Optional;
-import java.util.Set;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import org.apache.maven.project.MavenProject;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DependencyResolverFactory;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.spi.AbstractModule;
-import org.opendaylight.controller.config.spi.Module;
-import org.opendaylight.controller.config.spi.ModuleFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntryTest;
-import org.osgi.framework.BundleContext;
-import org.xml.sax.ErrorHandler;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-
-//TODO: refactor
-public class JMXGeneratorTest extends AbstractGeneratorTest {
-
- JMXGenerator jmxGenerator;
-
- protected final HashMap<String, String> map = new HashMap<>();
- protected File outputBaseDir;
- File generatedResourcesDir;
-
- private static final List<String> expectedModuleFileNames = ServiceInterfaceEntryTest
- .toFileNames("[AbstractAsyncEventBusModule.java, AbstractAsyncEventBusModuleFactory.java, AbstractDynamicThreadPoolModule.java, AbstractDynamicThreadPoolModuleFactory.java, AbstractEventBusModule.java, AbstractEventBusModuleFactory.java, AbstractNamingThreadFactoryModule.java, AbstractNamingThreadFactoryModuleFactory.java, AbstractThreadPoolRegistryImplModule.java, AbstractThreadPoolRegistryImplModuleFactory.java, AsyncEventBusModule.java, AsyncEventBusModuleFactory.java, AsyncEventBusModuleMXBean.java, AsyncEventBusRuntimeMXBean.java, AsyncEventBusRuntimeRegistration.java, AsyncEventBusRuntimeRegistrator.java, DynamicThreadPoolModule.java, DynamicThreadPoolModuleFactory.java, DynamicThreadPoolModuleMXBean.java, DynamicThreadPoolRuntimeMXBean.java, DynamicThreadPoolRuntimeRegistration.java, DynamicThreadPoolRuntimeRegistrator.java, EventBusModule.java, EventBusModuleFactory.java, EventBusModuleMXBean.java, EventRuntimeMXBean.java, EventRuntimeRegistration.java, FromGrouping.java, InnerStreamList.java, NamingThreadFactoryModule.java, NamingThreadFactoryModuleFactory.java, NamingThreadFactoryModuleMXBean.java, NamingThreadFactoryRuntimeMXBean.java, NamingThreadFactoryRuntimeRegistration.java, NamingThreadFactoryRuntimeRegistrator.java, Peer.java, StreamRuntimeMXBean.java, StreamRuntimeRegistration.java, ThreadPoolRegistryImplModule.java, ThreadPoolRegistryImplModuleFactory.java, ThreadPoolRegistryImplModuleMXBean.java, ThreadRuntimeMXBean.java, ThreadRuntimeRegistration.java, ThreadStreamRuntimeMXBean.java, ThreadStreamRuntimeRegistration.java]");
-
- private static final List<String> expectedBGPNames = ServiceInterfaceEntryTest
- .toFileNames("[AbstractBgpListenerImplModule.java, " + "AbstractBgpListenerImplModuleFactory.java, " +
- "BgpListenerImplModule.java, " + "BgpListenerImplModuleFactory.java, " +
- "BgpListenerImplModuleMXBean.java, Peers.java]");
-
- private static final List<String> expectedNetconfNames = ServiceInterfaceEntryTest
- .toFileNames("[AbstractNetconfTestImplModule.java, " + "AbstractNetconfTestImplModuleFactory.java, " +
- "AbstractTestImplModule.java, " + "AbstractTestImplModuleFactory.java, " +
- "AutoCloseableServiceInterface.java, " + "ComplexDtoBInner.java, ComplexList.java, Deep.java, " +
- "DtoA.java, DtoA1.java, DtoAInner.java, DtoAInnerInner.java, DtoB.java, DtoC.java," + "NetconfTestImplModule.java, NetconfTestImplModuleFactory.java," + "NetconfTestImplModuleMXBean.java, Peer.java, SimpleList.java, TestImplModule.java, " + "TestImplModuleFactory.java," + " TestImplModuleMXBean.java" + "]");
- private static final List<String> expectedTestFiles = ServiceInterfaceEntryTest
- .toFileNames("[AbstractNetconfTestFileImplModule.java, AbstractNetconfTestFileImplModuleFactory.java, " +
- "AbstractNetconfTestFiles1ImplModule.java, AbstractNetconfTestFiles1ImplModuleFactory.java, " +
- "AbstractTestFileImplModule.java, AbstractTestFileImplModuleFactory.java, " +
- "AbstractTestFiles1ImplModule.java, AbstractTestFiles1ImplModuleFactory.java, DtoA.java, " +
- "DtoA.java, NetconfTestFileImplModuleMXBean.java, NetconfTestFileImplRuntimeMXBean.java, " +
- "NetconfTestFileImplRuntimeRegistration.java, NetconfTestFileImplRuntimeRegistrator.java, " +
- "NetconfTestFiles1ImplModule.java, NetconfTestFiles1ImplModuleFactory.java, " +
- "NetconfTestFiles1ImplModuleMXBean.java, NetconfTestFiles1ImplRuntimeMXBean.java, " +
- "NetconfTestFiles1ImplRuntimeRegistration.java, NetconfTestFiles1ImplRuntimeRegistrator.java, TestFileImplModule.java, TestFileImplModuleFactory.java, TestFileImplModuleMXBean.java, TestFileImplRuntimeMXBean.java, TestFileImplRuntimeRegistration.java, TestFileImplRuntimeRegistrator.java, TestFiles1ImplModule.java, TestFiles1ImplModuleFactory.java, TestFiles1ImplModuleMXBean.java, TestFiles1ImplRuntimeMXBean.java, TestFiles1ImplRuntimeRegistration.java, TestFiles1ImplRuntimeRegistrator.java]");
- private static final List<String> expectedAllFileNames = ServiceInterfaceEntryTest
- .toFileNames("[AbstractAsyncEventBusModule.java, AbstractAsyncEventBusModuleFactory.java, AbstractBgpListenerImplModule.java, AbstractBgpListenerImplModuleFactory.java, AbstractDynamicThreadPoolModule.java, AbstractDynamicThreadPoolModuleFactory.java, AbstractEventBusModule.java, AbstractEventBusModuleFactory.java, AbstractNamingThreadFactoryModule.java, AbstractNamingThreadFactoryModuleFactory.java, AbstractNetconfTestFileImplModule.java, AbstractNetconfTestFileImplModuleFactory.java, AbstractNetconfTestFiles1ImplModule.java, AbstractNetconfTestFiles1ImplModuleFactory.java, AbstractNetconfTestImplModule.java, AbstractNetconfTestImplModuleFactory.java, AbstractTestFileImplModule.java, AbstractTestFileImplModuleFactory.java, AbstractTestFiles1ImplModule.java, AbstractTestFiles1ImplModuleFactory.java, AbstractTestImplModule.java, AbstractTestImplModuleFactory.java, AbstractThreadPoolRegistryImplModule.java, AbstractThreadPoolRegistryImplModuleFactory.java, AsyncEventBusModule.java, AsyncEventBusModuleFactory.java, AsyncEventBusModuleMXBean.java, AsyncEventBusRuntimeMXBean.java, AsyncEventBusRuntimeRegistration.java, AsyncEventBusRuntimeRegistrator.java, AutoCloseableServiceInterface.java, BgpListenerImplModule.java, BgpListenerImplModuleFactory.java, BgpListenerImplModuleMXBean.java, BgpListenerImplRuntimeMXBean.java, BgpListenerImplRuntimeRegistration.java, BgpListenerImplRuntimeRegistrator.java, ComplexDtoBInner.java, ComplexList.java, Deep.java, DtoA.java, DtoA.java, DtoA.java, DtoA1.java, DtoAInner.java, DtoAInnerInner.java, DtoB.java, DtoC.java, DynamicThreadPoolModule.java, DynamicThreadPoolModuleFactory.java, DynamicThreadPoolModuleMXBean.java, DynamicThreadPoolRuntimeMXBean.java, DynamicThreadPoolRuntimeRegistration.java, DynamicThreadPoolRuntimeRegistrator.java, EventBusModule.java, EventBusModuleFactory.java, EventBusModuleMXBean.java, EventBusServiceInterface.java, EventRuntimeMXBean.java, EventRuntimeRegistration.java, FromGrouping.java, InnerStreamList.java, NamingThreadFactoryModule.java, NamingThreadFactoryModuleFactory.java, NamingThreadFactoryModuleMXBean.java, NamingThreadFactoryRuntimeMXBean.java, NamingThreadFactoryRuntimeRegistration.java, NamingThreadFactoryRuntimeRegistrator.java, NetconfTestFileImplModule.java, NetconfTestFileImplModuleFactory.java, NetconfTestFileImplModuleMXBean.java, NetconfTestFileImplRuntimeMXBean.java, NetconfTestFileImplRuntimeRegistration.java, NetconfTestFileImplRuntimeRegistrator.java, NetconfTestFiles1ImplModule.java, NetconfTestFiles1ImplModuleFactory.java, NetconfTestFiles1ImplModuleMXBean.java, NetconfTestFiles1ImplRuntimeMXBean.java, NetconfTestFiles1ImplRuntimeRegistration.java, NetconfTestFiles1ImplRuntimeRegistrator.java, NetconfTestImplModule.java, NetconfTestImplModuleFactory.java, NetconfTestImplModuleMXBean.java, NetconfTestImplRuntimeMXBean.java, NetconfTestImplRuntimeRegistration.java, NetconfTestImplRuntimeRegistrator.java, Peer.java, Peer.java, PeersRuntimeMXBean.java, PeersRuntimeRegistration.java, ScheduledThreadPoolServiceInterface.java, SimpleList.java, StreamRuntimeMXBean.java, StreamRuntimeRegistration.java, TestFileImplModule.java, TestFileImplModuleFactory.java, TestFileImplModuleMXBean.java, TestFileImplRuntimeMXBean.java, TestFileImplRuntimeRegistration.java, TestFileImplRuntimeRegistrator.java, TestFiles1ImplModule.java, TestFiles1ImplModuleFactory.java, TestFiles1ImplModuleMXBean.java, TestFiles1ImplRuntimeMXBean.java, TestFiles1ImplRuntimeRegistration.java, TestFiles1ImplRuntimeRegistrator.java, TestImplModule.java, TestImplModuleFactory.java, TestImplModuleMXBean.java, TestImplRuntimeMXBean.java, TestImplRuntimeRegistration.java, TestImplRuntimeRegistrator.java, ThreadFactoryServiceInterface.java, ThreadPoolRegistryImplModule.java, ThreadPoolRegistryImplModuleFactory.java, ThreadPoolRegistryImplModuleMXBean.java, ThreadPoolServiceInterface.java, ThreadRuntimeMXBean.java, ThreadRuntimeRegistration.java, ThreadStreamRuntimeMXBean.java, ThreadStreamRuntimeRegistration.java]");
- private static final List<String> expectedGenerateMBEsListNames = ServiceInterfaceEntryTest
- .toFileNames("[AbstractBgpListenerImplModule.java, AbstractBgpListenerImplModuleFactory.java, BgpListenerImplModule.java, BgpListenerImplModuleFactory.java, BgpListenerImplModuleMXBean.java, BgpListenerImplRuntimeMXBean.java, BgpListenerImplRuntimeRegistration.java, BgpListenerImplRuntimeRegistrator.java, PeersRuntimeMXBean.java, PeersRuntimeRegistration.java]");
-
- @Before
- public void setUp() {
- map.put(JMXGenerator.NAMESPACE_TO_PACKAGE_PREFIX + "1",
- ConfigConstants.CONFIG_NAMESPACE + JMXGenerator.NAMESPACE_TO_PACKAGE_DIVIDER + EXPECTED_PACKAGE_PREFIX);
- map.put(JMXGenerator.MODULE_FACTORY_FILE_BOOLEAN, "false");
- jmxGenerator = new JMXGenerator(new CodeWriter());
- jmxGenerator.setAdditionalConfig(map);
- File targetDir = new File(generatorOutputPath, "target");
- generatedResourcesDir = new File(targetDir, "generated-resources");
- jmxGenerator.setResourceBaseDir(generatedResourcesDir);
- MavenProject project = mock(MavenProject.class);
- doReturn(generatorOutputPath).when(project).getBasedir();
- jmxGenerator.setMavenProject(project);
- outputBaseDir = JMXGenerator.concatFolders(targetDir, "generated-sources", "config");
- }
-
- @Test
- public void generateSIsMBsTest() {
- Collection<File> files = jmxGenerator.generateSources(context, outputBaseDir, context.getModules(),
- m -> Optional.empty());
- List<String> expectedFileNames = new ArrayList<>();
- expectedFileNames
- .addAll(ServiceInterfaceEntryTest.expectedSIEFileNames);
- expectedFileNames.addAll(expectedModuleFileNames);
-
- expectedFileNames.addAll(expectedBGPNames);
- expectedFileNames.addAll(expectedNetconfNames);
- expectedFileNames.addAll(expectedTestFiles);
- Collections.sort(expectedFileNames);
- // TODO: separate expectedAllFileNames into expectedBGPNames,
- // expectedNetconfNames
- assertEquals(expectedAllFileNames, toFileNames(files));
-
- verifyModuleFactoryFile(false);
- }
-
- private void verifyModuleFactoryFile(final boolean shouldBePresent) {
- File factoryFile = new File(generatedResourcesDir, "META-INF"
- + File.separator + "services" + File.separator
- + ModuleFactory.class.getName());
- if (!shouldBePresent) {
- assertFalse("Factory file should not be generated",
- factoryFile.exists());
- } else {
- assertTrue("Factory file should be generated", factoryFile.exists());
- }
- }
-
- private static List<String> toFileNames(final Collection<File> files) {
- List<String> result = new ArrayList<>();
- for (File f : files) {
- result.add(f.getName());
- }
- Collections.sort(result);
- return result;
- }
-
- @Test
- public void generateSIEsTest() throws IOException, ParseException {
- Collection<File> files = jmxGenerator.generateSources(context, outputBaseDir,
- Collections.singleton(threadsModule), m -> Optional.empty());
- assertEquals(ServiceInterfaceEntryTest.expectedSIEFileNames, toFileNames(files));
-
- for (File file : files) {
- String fileName = file.getName();
- SieASTVisitor verifier = new SieASTVisitor(EXPECTED_PACKAGE_PREFIX + ".threads", fileName);
- verifyFile(file, verifier);
-
- assertThat(verifier.extnds,
- containsString("org.opendaylight.controller.config.api.annotations.AbstractServiceInterface"));
- assertNotNull(verifier.javadoc);
-
- switch (fileName) {
- case "ThreadPoolServiceInterface.java":
- assertContains(verifier.descriptionAnotValue, "A simple pool of threads able to execute work.");
- assertContains(verifier.sieAnnotValue, "threadpool");
- assertContains(verifier.sieAnnotOsgiRegistrationType, EXPECTED_PACKAGE_PREFIX + ".threadpool.ThreadPool.class");
- break;
- case "ScheduledThreadPoolServiceInterface.java":
- assertContains(verifier.extnds,
- EXPECTED_PACKAGE_PREFIX + ".threads.ThreadPoolServiceInterface");
- assertContains(verifier.descriptionAnotValue,
- "An extension of the simple pool of threads able to schedule work to be executed at some point in time.");
- assertContains(verifier.sieAnnotValue, "scheduled-threadpool");
- assertContains(verifier.sieAnnotOsgiRegistrationType,
- EXPECTED_PACKAGE_PREFIX + ".threadpool.ScheduledThreadPool.class");
- break;
- case "EventBusServiceInterface.java":
- assertContains(verifier.descriptionAnotValue,
- "Service representing an event bus. The service acts as message router between event producers and event consumers");
- assertContains(verifier.sieAnnotValue, "eventbus");
- assertContains(verifier.sieAnnotOsgiRegistrationType, "com.google.common.eventbus.EventBus.class");
- break;
- case "ThreadFactoryServiceInterface.java":
- assertContains( verifier.descriptionAnotValue,
- "Service representing a ThreadFactory instance. It is directly useful in Java world, where various library pieces need to create threads and you may want to inject a customized thread implementation.");
- assertContains(verifier.sieAnnotValue, "threadfactory");
- assertContains(verifier.sieAnnotOsgiRegistrationType,
- "java.util.concurrent.ThreadFactory.class");
- break;
- case "ScheduledExecutorServiceServiceInterface.java":
- assertContains(verifier.sieAnnotOsgiRegistrationType,
- "java.util.concurrent.ScheduledExecutorService.class");
- break;
- default:
- fail("Unknown generated sie " + fileName);
- }
- }
- }
-
- @Test
- public void generateMBEsListTest() throws Exception {
- // default value for module factory file is true
- map.put(JMXGenerator.MODULE_FACTORY_FILE_BOOLEAN, "randomValue");
- jmxGenerator.setAdditionalConfig(map);
-
- Collection<File> files = jmxGenerator.generateSources(context, outputBaseDir,
- Collections.singleton(bgpListenerJavaModule), m -> Optional.empty());
-
- assertEquals(expectedGenerateMBEsListNames, toFileNames(files));
- }
-
- @Test
- public void generateMBEsTest() throws Exception {
- // default value for module factory file is true
- map.put(JMXGenerator.MODULE_FACTORY_FILE_BOOLEAN, "randomValue");
- jmxGenerator.setAdditionalConfig(map);
-
- Collection<File> files = jmxGenerator.generateSources(context, outputBaseDir,
- Collections.singleton(threadsJavaModule), m -> Optional.empty());
-
- assertEquals(expectedModuleFileNames, toFileNames(files));
-
- for (File file : files) {
- final String name = file.getName();
- if (!name.endsWith("java")) {
- continue;
- }
-
- MbeASTVisitor visitor = new MbeASTVisitor(EXPECTED_PACKAGE_PREFIX + ".threads.java", name);
-
- verifyFile(file, visitor);
-
- switch (name) {
- case "AbstractDynamicThreadPoolModule.java":
- assertAbstractDynamicThreadPoolModule(visitor);
- break;
- case "AsyncEventBusModuleMXBean.java":
- assertEquals("Incorrenct number of generated methods", 4, visitor.methods.size());
- break;
- case "AbstractNamingThreadFactoryModuleFactory.java":
- assertAbstractNamingThreadFactoryModuleFactory(visitor);
- break;
- case "AsyncEventBusModule.java":
- assertContains(visitor.extnds, EXPECTED_PACKAGE_PREFIX + ".threads.java.AbstractAsyncEventBusModule");
- visitor.assertFields(0);
- assertEquals("Incorrenct number of generated methods", 2, visitor.methods.size());
- visitor.assertConstructors(2);
- visitor.assertMethodDescriptions(0);
- visitor.assertMethodJavadocs(0);
- break;
- case "EventBusModuleFactory.java":
- assertContains(visitor.extnds,
- EXPECTED_PACKAGE_PREFIX + ".threads.java.AbstractEventBusModuleFactory");
- visitor.assertFields(0);
- assertEquals("Incorrenct number of generated methods", 0, visitor.methods.size());
- visitor.assertConstructors(0);
- visitor.assertMethodDescriptions(0);
- visitor.assertMethodJavadocs(0);
- break;
- }
- }
-
- verifyXmlFiles(Collections2.filter(files, input -> input.getName().endsWith("xml")));
-
- // verify ModuleFactory file
- File moduleFactoryFile = JMXGenerator.concatFolders(generatedResourcesDir, "META-INF", "services",
- ModuleFactory.class.getName());
- assertTrue(moduleFactoryFile.exists());
- Set<String> lines = ImmutableSet.copyOf(Files.readLines(moduleFactoryFile, StandardCharsets.UTF_8));
- Set<String> expectedLines = ImmutableSet.of(
- EXPECTED_PACKAGE_PREFIX + ".threads.java.EventBusModuleFactory",
- EXPECTED_PACKAGE_PREFIX + ".threads.java.AsyncEventBusModuleFactory",
- EXPECTED_PACKAGE_PREFIX + ".threads.java.DynamicThreadPoolModuleFactory",
- EXPECTED_PACKAGE_PREFIX + ".threads.java.NamingThreadFactoryModuleFactory",
- EXPECTED_PACKAGE_PREFIX + ".threads.java.ThreadPoolRegistryImplModuleFactory");
-
- assertEquals(expectedLines, lines);
- }
-
- private static void verifyXmlFiles(final Collection<File> xmlFiles) throws Exception {
- ErrorHandler errorHandler = new ErrorHandler() {
-
- @Override
- public void warning(final SAXParseException exception)
- throws SAXException {
- fail("Generated blueprint xml is not well formed " + exception.getMessage());
- }
-
- @Override
- public void fatalError(final SAXParseException exception)
- throws SAXException {
- fail("Generated blueprint xml is not well formed " + exception.getMessage());
- }
-
- @Override
- public void error(final SAXParseException exception) throws SAXException {
- fail("Generated blueprint xml is not well formed " + exception.getMessage());
- }
- };
-
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setValidating(false);
- factory.setNamespaceAware(true);
-
- for (File file : xmlFiles) {
- DocumentBuilder builder = factory.newDocumentBuilder();
- builder.setErrorHandler(errorHandler);
- builder.parse(new InputSource(file.getPath()));
- }
- }
-
- private static void assertAbstractNamingThreadFactoryModuleFactory( final MbeASTVisitor visitor) {
- assertContains(visitor.implmts, "org.opendaylight.controller.config.spi.ModuleFactory");
-
- visitor.assertFields(2);
- visitor.assertField("public static final java.lang.String NAME = \"threadfactory-naming\"");
- visitor.assertField(
- "private static final java.util.Set<Class<? extends org.opendaylight.controller.config.api.annotations.AbstractServiceInterface>> serviceIfcs");
-
- assertFactoryMethods(visitor.methods, 10);
- visitor.assertMethodDescriptions(0);
- visitor.assertMethodJavadocs(0);
- }
-
- private static void assertFactoryMethods(final Set<String> methods, final int expectedSize) {
-
- List<ArgumentAssertion> args = new ArrayList<>();
- ArgumentAssertion oldInstanceArg = new ArgumentAssertion(DynamicMBeanWithInstance.class.getCanonicalName(), "old");
- ArgumentAssertion instanceNameArg = new ArgumentAssertion(String.class.getSimpleName(), "instanceName");
- ArgumentAssertion dependencyResolverArg = new ArgumentAssertion(DependencyResolver.class.getCanonicalName(), "dependencyResolver");
- ArgumentAssertion bundleContextArg = new ArgumentAssertion(BundleContext.class.getCanonicalName(), "bundleContext");
-
- assertMethodPresent(methods, new MethodAssertion(String.class.getSimpleName(), "getImplementationName"));
-
- args.add(instanceNameArg);
- args.add(dependencyResolverArg);
- args.add(bundleContextArg);
- assertMethodPresent(methods, new MethodAssertion(Module.class.getCanonicalName(), "createModule", args));
-
- args.add(2, oldInstanceArg);
- assertMethodPresent(methods, new MethodAssertion(Module.class.getCanonicalName(), "createModule", args));
-
- args.clear();
- args.add(oldInstanceArg);
- assertMethodPresent(methods, new MethodAssertion("org.opendaylight.controller.config.threads.java.NamingThreadFactoryModule", "handleChangedClass", args));
-
- args.clear();
- args.add(instanceNameArg);
- args.add(dependencyResolverArg);
- args.add(bundleContextArg);
- assertMethodPresent(methods, new MethodAssertion("org.opendaylight.controller.config.threads.java.NamingThreadFactoryModule", "instantiateModule", args));
-
-
- args.add(2, new ArgumentAssertion("org.opendaylight.controller.config.threads.java.NamingThreadFactoryModule", "oldModule"));
- args.add(3, new ArgumentAssertion(AutoCloseable.class.getCanonicalName(), "oldInstance"));
- assertMethodPresent(methods, new MethodAssertion("org.opendaylight.controller.config.threads.java.NamingThreadFactoryModule", "instantiateModule", args));
-
- args.clear();
- args.add(new ArgumentAssertion(DependencyResolverFactory.class.getCanonicalName(), "dependencyResolverFactory"));
- args.add(bundleContextArg);
- assertMethodPresent(methods, new MethodAssertion("java.util.Set<org.opendaylight.controller.config.threads.java.NamingThreadFactoryModule>", "getDefaultModules", args));
-
- args.clear();
- args.add(new ArgumentAssertion("Class<? extends org.opendaylight.controller.config.api.annotations.AbstractServiceInterface>", "serviceInterface"));
- assertMethodPresent(methods, new MethodAssertion("boolean", "isModuleImplementingServiceInterface", args));
-
- assertEquals(expectedSize, methods.size());
- }
-
- private static void assertMethodPresent(final Set<String> methods, final MethodAssertion methodAssertion) {
- assertTrue(String.format("Generated methods did not contain %s, generated methods: %s",
- methodAssertion.toString(), methods), methods.contains(methodAssertion.toString()));
- }
-
- private static void assertAbstractDynamicThreadPoolModule(final MbeASTVisitor visitor) {
- assertNotNull(visitor.javadoc);
- assertContains(visitor.descriptionAnotValue, "threadpool-dynamic description");
- assertContains(visitor.implmts,
- EXPECTED_PACKAGE_PREFIX + ".threads.java.DynamicThreadPoolModuleMXBean",
- EXPECTED_PACKAGE_PREFIX + ".threads.ScheduledThreadPoolServiceInterface",
- EXPECTED_PACKAGE_PREFIX + ".threads.ThreadPoolServiceInterface");
- assertContains(visitor.extnds, AbstractModule.class.getCanonicalName());
- visitor.assertConstructors(2);
- visitor.assertFields(17);
- visitor.assertField("private java.lang.Long maximumSize");
- visitor.assertField("private javax.management.ObjectName threadfactory");
- visitor.assertField("private java.util.concurrent.ThreadFactory threadfactoryDependency");
- visitor.assertField("private java.lang.Long keepAlive = java.lang.Long.valueOf(\"10\")");
- visitor.assertField("private java.lang.Long coreSize");
- visitor.assertField("private byte[] binary");
-
- assertEquals(1, visitor.requireIfc.size());
- String reqIfc = visitor.requireIfc.get("setThreadfactory");
- assertNotNull("Missing generated setter for threadfactory", reqIfc);
- assertContains(reqIfc, EXPECTED_PACKAGE_PREFIX + ".threads.ThreadFactoryServiceInterface");
-
- assertEquals("Incorrenct number of generated methods", 26, visitor.methods.size());
- visitor.assertMethodDescriptions(3);
- visitor.assertMethodJavadocs(3);
- visitor.assertMethodJavadoc("setMaximumSize", "void setMaximumSize(java.lang.Long maximumSize)");
-
- }
-
- private static void assertContains(final String source, final String... contained) {
- for (String string : contained) {
- assertThat(source, containsString(string));
- }
- }
-
- private static void verifyFile(final File file, final AbstractVerifier verifier) throws ParseException, IOException {
- final CompilationUnit cu = JavaParser.parse(file);
- cu.accept(verifier, null);
- verifier.verify();
- }
-
- private static class MethodAssertion extends ArgumentAssertion {
-
- private final List<ArgumentAssertion> arguments;
-
-
- MethodAssertion(final String type, final String name, final List<ArgumentAssertion> arguments) {
- super(type, name);
- this.arguments = arguments;
- }
-
- MethodAssertion(final String type, final String name) {
- this(type, name, Collections.<ArgumentAssertion>emptyList());
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder();
- sb.append(type).append(' ');
- sb.append(name).append('(');
-
- int i = 0;
- for (ArgumentAssertion argument : arguments) {
- sb.append(argument.type).append(' ');
- sb.append(argument.name);
- if(++i != arguments.size()) {
- sb.append(", ");
- }
- }
- sb.append(')');
- return sb.toString();
- }
- }
-
- private static class ArgumentAssertion {
-
- protected final String type, name;
-
- private ArgumentAssertion(final String type, final String name) {
- this.type = type;
- this.name = name;
- }
-
- @Override
- public String toString() {
- return type + " " + name;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Pantheon Technologies s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import com.github.javaparser.ast.Node;
-import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
-import com.github.javaparser.ast.body.ConstructorDeclaration;
-import com.github.javaparser.ast.body.FieldDeclaration;
-import com.github.javaparser.ast.body.MethodDeclaration;
-import com.github.javaparser.ast.comments.Comment;
-import com.github.javaparser.ast.comments.JavadocComment;
-import com.github.javaparser.ast.expr.NormalAnnotationExpr;
-import com.github.javaparser.ast.type.ClassOrInterfaceType;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import org.opendaylight.controller.config.api.annotations.RequireInterface;
-
-class MbeASTVisitor extends SieASTVisitor {
- private final Set<String> constructors = new HashSet<>();
- private final Set<String> fieldDeclarations = new HashSet<>();
- final Set<String> methods = new HashSet<>();
- private final Map<String, String> methodJavadoc = new HashMap<>();
- final Map<String, String> requireIfc = new HashMap<>();
-
- String implmts;
-
- MbeASTVisitor(final String expectedPackageName, final String fileName) {
- super(expectedPackageName, fileName);
- }
-
- @Override
- public void visit(final NormalAnnotationExpr expr, final Void arg) {
- super.visit(expr, arg);
-
- final String fqcn = expr.getName().toString();
- if (fqcn.equals(RequireInterface.class.getCanonicalName()) && expr.getParentNode() instanceof MethodDeclaration) {
- final Node parent = expr.getParentNode();
- if (parent instanceof MethodDeclaration) {
- // remember only top level description annotation
- String reqVal = expr.getPairs().get(0).toString();
- requireIfc.put(((MethodDeclaration) parent).getName(), reqVal);
- }
- }
- }
-
- @Override
- public void visit(final ConstructorDeclaration n, final Void arg) {
- constructors.add(n.toString());
- super.visit(n, arg);
- }
-
- @Override
- public void visit(final MethodDeclaration n, final Void arg) {
- final String signature = n.getDeclarationAsString(false, false);
-
- methods.add(signature);
-
- final Comment c = n.getComment();
- if (c instanceof JavadocComment) {
- methodJavadoc.put(signature, c.toString());
- }
- super.visit(n, arg);
- }
-
- @Override
- public void visit(final FieldDeclaration n, final Void arg) {
- fieldDeclarations.add(n.toStringWithoutComments());
- super.visit(n, arg);
- }
-
- @Override
- public void visit(final ClassOrInterfaceDeclaration n, final Void arg) {
- super.visit(n, arg);
-
- List<?> superIfcs = n.getImplements();
- implmts = superIfcs != null && !superIfcs.isEmpty() ? superIfcs.toString() : null;
-
- if (!n.isInterface()) {
- final List<ClassOrInterfaceType> e = n.getExtends();
- if (!e.isEmpty()) {
- extnds = e.get(0).toString();
- }
- }
- }
-
- void assertConstructors(final int expected) {
- assertEquals("Incorrenct number of generated constructors", expected, constructors.size());
- }
-
- void assertField(final String declaration) {
- assertTrue("Missing field " + declaration + ", got: " + fieldDeclarations,
- fieldDeclarations.contains(declaration + ";"));
- }
-
- void assertFields(final int expected) {
- assertEquals("Incorrect number of generated fields", expected, fieldDeclarations.size());
- }
-
- void assertMethodJavadoc(final String method, final String signature) {
- assertNotNull("Missing javadoc for " + method + " method " + methodJavadoc, methodJavadoc.get(signature));
- }
-
- void assertMethodJavadocs(final int expected) {
- assertEquals("Incorrenct number of generated method javadoc", expected, methodJavadoc.size());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntryTest;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.GeneralClassTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.GeneralInterfaceTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Method;
-
-public class ModuleMXBeanEntryPluginTest extends ModuleMXBeanEntryTest {
-
- @Test
- public void testThreadsJavaPlugin() {
- Map<String /* identity local name */, ModuleMXBeanEntry> namesToMBEs = loadThreadsJava();
- {// check threadfactory-naming
- ModuleMXBeanEntry threadFactoryNaming = namesToMBEs
- .get(THREADFACTORY_NAMING_MXB_NAME);
- Collection<RuntimeBeanEntry> runtimeBeans = threadFactoryNaming
- .getRuntimeBeans();
- assertThat(runtimeBeans.size(), is(4));
- // first one should be root
- {
- RuntimeBeanEntry rootRB = findFirstByYangName(runtimeBeans,
- THREADFACTORY_NAMING_MXB_NAME);
- assertThat(rootRB.isRoot(), is(true));
- assertThat(rootRB.getAttributes().size(), is(1));
- JavaAttribute attribute = (JavaAttribute) rootRB
- .getAttributes().iterator().next();
- assertThat(attribute.getAttributeYangName(),
- is("created-sessions"));
- assertThat(rootRB.getYangName(),
- is(THREADFACTORY_NAMING_MXB_NAME));
- Map<String, FtlTemplate> ftlMap = TemplateFactory
- .getTOAndMXInterfaceFtlFiles(rootRB);
- assertThat(ftlMap.size(), is(1));
- GeneralInterfaceTemplate rootGeneratorInterface = (GeneralInterfaceTemplate) ftlMap
- .get("NamingThreadFactoryRuntimeMXBean.java");
- assertNotNull(rootGeneratorInterface);
- assertThat(rootGeneratorInterface.getPackageName(),
- is(PACKAGE_NAME));
- assertThat(rootGeneratorInterface.getFullyQualifiedName(),
- is(PACKAGE_NAME + ".NamingThreadFactoryRuntimeMXBean"));
- assertThat(
- rootGeneratorInterface.getTypeDeclaration()
- .getExtended(),
- is(Arrays
- .asList("org.opendaylight.controller.config.api.runtime.RuntimeBean")));
-
- assertThat(rootGeneratorInterface.getMethods().size(), is(1));
- Method getCreatedSessions = findFirstMethodByName(
- rootGeneratorInterface.getMethods(),
- "getCreatedSessions");
- assertThat(getCreatedSessions.getName(),
- is("getCreatedSessions"));
- assertThat(getCreatedSessions.getParameters().isEmpty(),
- is(true));
- assertThat(getCreatedSessions.getReturnType(),
- is(Long.class.getName()));
- }
- }
- {
- ModuleMXBeanEntry threadFactoryNaming = namesToMBEs
- .get(THREADFACTORY_NAMING_MXB_NAME);
- Collection<RuntimeBeanEntry> runtimeBeans = threadFactoryNaming
- .getRuntimeBeans();
- assertThat(runtimeBeans.size(), is(4));
-
- {
- RuntimeBeanEntry streamRB = findFirstByNamePrefix(runtimeBeans,
- "ThreadStream");
- assertNotNull(streamRB);
- assertFalse(streamRB.getKeyYangName().isPresent());
- assertFalse(streamRB.getKeyJavaName().isPresent());
- Map<String, AttributeIfc> attributeMap = streamRB
- .getYangPropertiesToTypesMap();
- assertEquals(4, attributeMap.size());
- TOAttribute toAttr = (TOAttribute) attributeMap.get("peer");
- assertNotNull(toAttr);
- JavaAttribute timestampAttr = (JavaAttribute) attributeMap
- .get("timestamp");
- assertNotNull(timestampAttr);
- JavaAttribute stateAttr = (JavaAttribute) attributeMap
- .get("state");
- assertNotNull(stateAttr);
- ListAttribute innerStreamList = (ListAttribute) attributeMap
- .get("inner-stream-list");
- assertNotNull(innerStreamList);
-
- Map<String, FtlTemplate> ftlMap = TemplateFactory
- .getTOAndMXInterfaceFtlFiles(streamRB);
- assertThat(ftlMap.size(), is(3));
- GeneralInterfaceTemplate streamGeneralInterface = (GeneralInterfaceTemplate) ftlMap
- .get("ThreadStreamRuntimeMXBean.java");
- assertThat(streamGeneralInterface.getMethods().size(), is(4));
- Method getPeer = findFirstMethodByName(
- streamGeneralInterface.getMethods(), "getPeer");
- assertNotNull(getPeer);
- assertThat(getPeer.getReturnType(), is(PACKAGE_NAME + ".Peer"));
-
- // test TO
- GeneralClassTemplate peerTO = (GeneralClassTemplate) ftlMap
- .get("pack2.Peer");
- assertThat(peerTO.getPackageName(), is(PACKAGE_NAME));
- assertThat(peerTO.getTypeDeclaration().getExtended().isEmpty(),
- is(true));
- assertThat(peerTO.getFullyQualifiedName(), is(PACKAGE_NAME
- + ".Peer"));
- assertThat(peerTO.getMethods().size(), is(5 + 2/*hashCode Equals*/));
-
- Method getPort = findFirstMethodByName(peerTO.getMethods(), "getPort");
- assertNotNull(getPort);
- Method setPort = findFirstMethodByName(peerTO.getMethods(),
- "setPort");
- assertNotNull(setPort);
- Method getCoreSize = findFirstMethodByName(peerTO.getMethods(),
- "getCoreSize");
- Method setCoreSize = findFirstMethodByName(peerTO.getMethods(),
- "setCoreSize");
- assertNotNull(setCoreSize);
- assertNotNull(getCoreSize);
-
- }
- }
- }
-
- private static Method findFirstMethodByName(final List<? extends Method> methods, final String name) {
- for (Method ms : methods) {
- if (name.equals(ms.getName())) {
- return ms;
- }
- }
- throw new IllegalArgumentException("Method with given name not found");
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import com.google.common.collect.Maps;
-import java.util.Collections;
-import java.util.Map;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.AbstractFactoryTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory;
-import org.opendaylight.mdsal.binding.model.api.Type;
-
-public class ModuleMXBeanEntryTemplatesTest {
-
- @Test
- public void test() {
- final ModuleMXBeanEntry mbe = mockMbe("package");
- final AbstractFactoryTemplate template = TemplateFactory
- .abstractFactoryTemplateFromMbe(mbe);
- assertNotNull(template);
- }
-
- public static ModuleMXBeanEntry mockMbe(final String packageName) {
- final ModuleMXBeanEntry mbe = mock(ModuleMXBeanEntry.class);
- final Map<String, AttributeIfc> a = Maps.newHashMap();
- final JavaAttribute attr = mockJavaAttr();
-
- a.put("attr1", attr);
- doReturn(a).when(mbe).getAttributes();
- doReturn(packageName).when(mbe).getPackageName();
- doReturn(Collections.emptyMap()).when(mbe).getProvidedServices();
- doReturn("yang-module").when(mbe).getYangModuleName();
- doReturn("local").when(mbe).getYangModuleLocalname();
- doReturn("AbstractType").when(mbe).getAbstractFactoryName();
- doReturn("Module").when(mbe).getStubModuleName();
- doReturn("fullA").when(mbe).getFullyQualifiedName(anyString());
- doReturn("uniq").when(mbe).getGloballyUniqueName();
- return mbe;
- }
-
- public static JavaAttribute mockJavaAttr() {
- final JavaAttribute attr = mock(JavaAttribute.class);
- final Type typeA = mock(Type.class);
- doReturn("package").when(typeA).getName();
- doReturn("type").when(typeA).getPackageName();
- doReturn("package.type").when(typeA).getFullyQualifiedName();
- doReturn(typeA).when(attr).getType();
- doReturn("Type").when(attr).getUpperCaseCammelCase();
- doReturn("new Default()").when(attr).getNullableDefault();
- return attr;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Map;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeRegistratorTest;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.FtlTemplate;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.RuntimeRegistratorFtlTemplate;
-
-public class RuntimeRegistratorFtlFileTest extends RuntimeRegistratorTest {
-
- @Test
- public void testRootWithoutAnything() {
- RuntimeBeanEntry rootRB = prepareRootRB(Collections
- .<RuntimeBeanEntry> emptyList());
- Map<String, FtlTemplate> createdFtls = RuntimeRegistratorFtlTemplate
- .create(rootRB);
- assertThat(createdFtls.size(), is(2));
- String rootRegistratorName = RuntimeRegistratorFtlTemplate
- .getJavaNameOfRuntimeRegistration(rootRB.getJavaNamePrefix());
- FtlTemplate rootFtlFile = createdFtls.get(rootRegistratorName);
- assertNotNull(rootFtlFile);
-
- assertThat(createdFtls.values().size(), is(2));
- }
-
- @Test
- public void testHierarchy2() {
- RuntimeBeanEntry grandChildRB = prepareChildRB(
- Collections.<RuntimeBeanEntry> emptyList(), "grand");
- RuntimeBeanEntry childRB = prepareChildRB(Arrays.asList(grandChildRB),
- "");
- RuntimeBeanEntry rootRB = prepareRootRB(Arrays.asList(childRB));
-
- Map<String, FtlTemplate> createdFtls = RuntimeRegistratorFtlTemplate
- .create(rootRB);
- assertThat(createdFtls.values().size(), is(4));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Pantheon Technologies s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin;
-
-import static org.junit.Assert.assertEquals;
-import com.github.javaparser.ast.Node;
-import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
-import com.github.javaparser.ast.body.MethodDeclaration;
-import com.github.javaparser.ast.comments.Comment;
-import com.github.javaparser.ast.comments.JavadocComment;
-import com.github.javaparser.ast.expr.NormalAnnotationExpr;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.controller.config.api.annotations.Description;
-import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
-
-class SieASTVisitor extends AbstractVerifier {
- private final Map<String, String> methodDescriptions = new HashMap<>();
- protected String descriptionAnotValue;
- protected String extnds;
- protected String javadoc;
- protected String sieAnnotValue;
- protected String sieAnnotOsgiRegistrationType;
-
- SieASTVisitor(final String expectedPackageName, final String fileName) {
- super(expectedPackageName, fileName);
- }
-
- @Override
- public void visit(final ClassOrInterfaceDeclaration n, final Void arg) {
- extnds = n.getExtends().toString();
-
- final Comment c = n.getComment();
- if (c instanceof JavadocComment) {
- javadoc = c.toString();
- }
-
- super.visit(n, arg);
- }
-
- @Override
- public void visit(final NormalAnnotationExpr expr, final Void arg) {
- final String fqcn = expr.getName().toString();
- if (fqcn.equals(Description.class.getCanonicalName())) {
- final Node parent = expr.getParentNode();
- final String value = expr.getPairs().get(0).toString();
- if (parent instanceof ClassOrInterfaceDeclaration) {
- descriptionAnotValue = value;
- } else if (parent instanceof MethodDeclaration) {
- methodDescriptions.put(((MethodDeclaration) parent).getName(), value);
- }
- } else if (fqcn.equals(ServiceInterfaceAnnotation.class.getCanonicalName())) {
- String text1 = expr.getPairs().get(0).toString();
- String text2 = expr.getPairs().get(1).toString();
- if (text1.contains("value")) {
- sieAnnotValue = text1;
- sieAnnotOsgiRegistrationType = text2;
- } else {
- sieAnnotValue = text2;
- sieAnnotOsgiRegistrationType = text1;
- }
- }
-
- super.visit(expr, arg);
- }
-
- final void assertMethodDescriptions(final int expected) {
- assertEquals("Incorrenct number of generated method descriptions", expected, methodDescriptions.size());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.module;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import com.google.common.io.Files;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import net.sourceforge.pmd.lang.Parser;
-import net.sourceforge.pmd.lang.ParserOptions;
-import net.sourceforge.pmd.lang.ast.Node;
-import net.sourceforge.pmd.lang.java.Java17Parser;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.AbstractGeneratorTest;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AbstractGeneratedObjectTest extends AbstractGeneratorTest {
- private static final Logger LOG = LoggerFactory.getLogger(AbstractGeneratedObjectTest.class);
-
- protected void assertHasMethodNamed(Node c, String method) {
- assertTrue(c.hasDescendantMatchingXPath("//MethodDeclaration[MethodDeclarator[@Image='" +
- method +
- "']]"));
- }
-
- protected Node parse(File dstFile) throws IOException {
- assertNotNull(dstFile);
- LOG.debug(Files.toString(dstFile, StandardCharsets.UTF_8));
- Parser parser = new Java17Parser(new ParserOptions());
- return parser.parse(dstFile.toString(), new FileReader(dstFile));
- }
-
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.module.abs;
-
-import com.google.common.base.Optional;
-import java.io.File;
-import java.io.IOException;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.AbsModuleGeneratedObjectFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.module.AbstractGeneratedObjectTest;
-import org.opendaylight.yangtools.yang.common.QName;
-
-public class AbsModuleGeneratedObjectFactoryTest extends AbstractGeneratedObjectTest {
-
- @Test
- public void test() throws IOException {
- Map<QName,ServiceInterfaceEntry> serviceInterfaceEntryMap = loadThreadsServiceInterfaceEntries("packages.sis");
- Map<String, ModuleMXBeanEntry> namesToMBEs = loadThreadsJava(serviceInterfaceEntryMap, "packages.pack2");
- ModuleMXBeanEntry dynamicThreadPool = namesToMBEs.get(THREADPOOL_DYNAMIC_MXB_NAME);
- parseGeneratedFile(dynamicThreadPool);
-
- }
-
- private void parseGeneratedFile(ModuleMXBeanEntry moduleMXBeanEntry) throws IOException {
- Optional<String> copyright = Optional.absent();
- GeneratedObject generatedObject = new AbsModuleGeneratedObjectFactory().toGeneratedObject(moduleMXBeanEntry, copyright);
- Entry<FullyQualifiedName,File> entry = generatedObject.persist(generatorOutputPath).get();
-
- File dstFile = entry.getValue();
- parse(dstFile);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.module.concrete;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import com.google.common.base.Optional;
-import java.io.File;
-import java.util.Map.Entry;
-import net.sourceforge.pmd.lang.ast.Node;
-import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
-import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory.ConcreteModuleGeneratedObjectFactory;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.GeneratedObject;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.module.AbstractGeneratedObjectTest;
-
-public class ConcreteModuleGeneratedObjectFactoryTest extends AbstractGeneratedObjectTest {
-
- @Test
- public void test() throws Exception {
- FullyQualifiedName fqn = new FullyQualifiedName("foo.bar", "Baz");
- FullyQualifiedName abstractFQN = new FullyQualifiedName("foo.bar", "AbstractBaz");
- String nullableDescription = null;
-
- ModuleMXBeanEntry moduleMXBeanEntry = mockModuleMXBeanEntry(fqn, abstractFQN, nullableDescription);
- Optional<String> copyright = Optional.absent();
- Optional<String> header = Optional.absent();
- GeneratedObject go = new ConcreteModuleGeneratedObjectFactory().toGeneratedObject(moduleMXBeanEntry, copyright, header);
- Entry<FullyQualifiedName, File> entry = go.persist(generatorOutputPath).get();
-
- File dstFile = entry.getValue();
- Node c = parse(dstFile);
- assertEquals(fqn.getPackageName(), ((ASTCompilationUnit) c).getPackageDeclaration().getPackageNameImage());
- assertEquals(fqn.getTypeName(), c.getFirstDescendantOfType(ASTClassOrInterfaceDeclaration.class).getImage());
- assertHasMethodNamed(c, "customValidation");
- assertHasMethodNamed(c, "createInstance");
- }
-
- static ModuleMXBeanEntry mockModuleMXBeanEntry(FullyQualifiedName fqn, FullyQualifiedName abstractFQN, String nullableDescription) {
- ModuleMXBeanEntry mock = mock(ModuleMXBeanEntry.class);
- assertEquals(fqn.getPackageName(), abstractFQN.getPackageName());
- doReturn(fqn.getPackageName()).when(mock).getPackageName();
- doReturn(fqn.getTypeName()).when(mock).getStubModuleName();
- doReturn(nullableDescription).when(mock).getNullableDescription();
- doReturn(abstractFQN.getTypeName()).when(mock).getAbstractModuleName();
- return mock;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
-
-import static java.util.Arrays.asList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.java.FullyQualifiedName;
-
-public class StringUtilTest {
- @Test
- public void testPrefixAndJoin() {
- assertEquals(" extends p1.Foo,Bar", StringUtil.prefixAndJoin(asList(
- new FullyQualifiedName("p1", "Foo"), new FullyQualifiedName("", "Bar")), "extends"));
- }
-
- @Test
- public void testAddAsterixAtEachLineStart() {
- String input = "foo \nbar";
- String expectedOutput = "* foo\n* bar\n";
- assertEquals(expectedOutput, StringUtil.addAsterixAtEachLineStart(input));
- }
-
- @Test
- @Ignore
- public void testCopyright() throws IOException {
- assertTrue(StringUtil.loadCopyright().isPresent());
- }
-
- @Test
- public void testFormatting() {
- {
- String input = " \tpack;\n" +
- "class Bar{ \n" +
- " method() {\n" +
- " body\n" +
- "}\n" +
- " }";
- String expected = "pack;\n" +
- "class Bar{\n" +
- " method() {\n" +
- " body\n" +
- " }\n" +
- "}\n";
- assertEquals(expected, StringUtil.formatJavaSource(input));
- }
- {
- String input = "{\n" +
- "bar\n" +
- "}\n" +
- "\n\nbaz\n\n\n\n";
- String expected = "{\n" +
- " bar\n" +
- "}\n\n" +
- "baz\n";
- assertEquals(expected, StringUtil.formatJavaSource(input));
- }
- }
-}
+++ /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>config-subsystem</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>../</relativePath>
- </parent>
-
- <artifactId>yang-jmx-generator</artifactId>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>config-api</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-binding-generator-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-model-util</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-test-util</artifactId>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Private-Package>org.opendaylight.controller.config.yangjmxgenerator.plugin.util,</Private-Package>
- <Export-Package>org.opendaylight.controller.config.yangjmxgenerator,
- org.opendaylight.controller.config.yangjmxgenerator.attribute,</Export-Package>
- </instructions>
- </configuration>
- </plugin>
- <!-- test jar -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- <phase>package</phase>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-/**
- * Base for entries that provides information about their yang source.
- */
-public class AbstractEntry {
-
- private String yangModuleName;
- private String yangModuleLocalname;
-
- public AbstractEntry() {
- }
-
- protected void setYangModuleName(String name) {
- this.yangModuleName = name;
- }
-
- public String getYangModuleLocalname() {
- return yangModuleLocalname;
- }
-
- protected void setYangModuleLocalname(String yangModuleLocalname) {
- this.yangModuleLocalname = yangModuleLocalname;
- }
-
- public String getYangModuleName() {
- return yangModuleName;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.QNameModule;
-
-public final class ConfigConstants {
-
- private ConfigConstants() {
- }
-
- private static final QName DUMMY_CONFIG_QNAME = QName.create(
- "urn:opendaylight:params:xml:ns:yang:controller:config", "2013-04-05", "dummy").intern();
- private static final QName DUMM_RPC_QNAME = QName.create(
- "urn:ietf:params:xml:ns:yang:rpc-context", "2013-06-17", "dummy").intern();
- private static final QNameModule CONFIG_MOD = DUMMY_CONFIG_QNAME.getModule();
- private static final QNameModule RPC_MOD = DUMM_RPC_QNAME.getModule();
-
- public static final String CONFIG_NAMESPACE = CONFIG_MOD.getNamespace().toString();
- public static final String CONFIG_MODULE = "config";
- public static final String CONFIG_THREADS_MODULE = "config-threads";
- public static final String IETF_INET_TYPES = "ietf-inet-types";
-
- public static final QName SERVICE_TYPE_Q_NAME = createConfigQName("service-type").intern();
- public static final QName MODULE_TYPE_Q_NAME = createConfigQName("module-type").intern();
- public static final QName JAVA_CLASS_EXTENSION_QNAME = createConfigQName("java-class").intern();
- public static final QName DISABLE_OSGI_SERVICE_REG_QNAME = createConfigQName("disable-osgi-service-registration").intern();
- public static final QName REQUIRED_IDENTITY_EXTENSION_QNAME = createConfigQName("required-identity").intern();
- public static final QName INNER_STATE_BEAN_EXTENSION_QNAME = createConfigQName("inner-state-bean").intern();
- public static final QName PROVIDED_SERVICE_EXTENSION_QNAME = createConfigQName("provided-service").intern();
- public static final QName JAVA_NAME_PREFIX_EXTENSION_QNAME = createConfigQName("java-name-prefix").intern();
- public static final QName RPC_CONTEXT_REF_GROUPING_QNAME = createRpcXQName("rpc-context-ref").intern();
- public static final QName RPC_CONTEXT_REF_GROUPING_LEAF = createRpcXQName("context-instance").intern();
- public static final QName RPC_CONTEXT_INSTANCE_EXTENSION_QNAME = createRpcXQName("rpc-context-instance").intern();
-
- public static QName createConfigQName(final String localName) {
- return QName.create(CONFIG_MOD, localName);
- }
-
- public static QName createRpcXQName(final String localName) {
- return QName.create(RPC_MOD, localName);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Map;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-
-/**
- * Represents part of yang model that describes a module.
- *
- * Example:
- * <p>
- * <blockquote>
- *
- * <pre>
- * identity threadpool-dynamic {
- * base config:module-type;
- * description "threadpool-dynamic description";
- * config:provided-service "th2:threadpool";
- * config:provided-service "th2:scheduled-threadpool";
- * config:java-name-prefix DynamicThreadPool
- * }
- * augment "/config:modules/config:module/config:module-type" {
- * case threadpool-dynamic {
- * when "/config:modules/config:module/config:module-type = 'threadpool-dynamic'";
- *
- * container "configuration" {
- * // regular java attribute
- * leaf core-size {
- * type uint32;
- * }
- *
- * ...
- * // dependency
- * container threadfactory {
- * uses config:service-ref {
- * refine type {
- * config:required-identity th:threadfactory;
- * }
- * }
- * }
- * }
- * }
- * </pre>
- *
- * </blockquote>
- */
-public class ModuleMXBeanEntry extends AbstractEntry {
-
- private static final String MODULE_SUFFIX = "Module";
- private static final String FACTORY_SUFFIX = MODULE_SUFFIX + "Factory";
- private static final String CLASS_NAME_SUFFIX = MODULE_SUFFIX + "MXBean";
- private static final String ABSTRACT_PREFIX = "Abstract";
-
- private final ModuleMXBeanEntryInitial initial;
-
- private Map<String, AttributeIfc> yangToAttributes;
-
- private final Map<String, QName> providedServices;
-
- private Collection<RuntimeBeanEntry> runtimeBeans;
- private String nullableDummyContainerName;
-
- ModuleMXBeanEntry(final ModuleMXBeanEntryInitial initials, final Map<String, AttributeIfc> yangToAttributes,
- final Map<String, QName> providedServices2, final Collection<RuntimeBeanEntry> runtimeBeans) {
- this.yangToAttributes = yangToAttributes;
- this.providedServices = Collections.unmodifiableMap(providedServices2);
- this.runtimeBeans = runtimeBeans;
- this.initial = initials;
- }
-
- public String getMXBeanInterfaceName() {
- return initial.javaNamePrefix + CLASS_NAME_SUFFIX;
- }
-
- public String getStubFactoryName() {
- return initial.javaNamePrefix + FACTORY_SUFFIX;
- }
-
- public String getAbstractFactoryName() {
- return ABSTRACT_PREFIX + getStubFactoryName();
- }
-
- public String getStubModuleName() {
- return initial.javaNamePrefix + MODULE_SUFFIX;
- }
-
- public String getAbstractModuleName() {
- return ABSTRACT_PREFIX + getStubModuleName();
- }
-
- public String getFullyQualifiedName(final String typeName) {
- return FullyQualifiedNameHelper.getFullyQualifiedName(initial.packageName,
- typeName);
- }
-
- public String getGloballyUniqueName() {
- return initial.localName;
- }
-
- public String getPackageName() {
- return initial.packageName;
- }
-
- /**
- * @return services implemented by this module. Keys are fully qualified
- * java names of generated ServiceInterface classes, values are
- * identity local names.
- */
- public Map<String, QName> getProvidedServices() {
- return providedServices;
- }
-
- public void setRuntimeBeans(final Collection<RuntimeBeanEntry> newRuntimeBeans) {
- runtimeBeans = newRuntimeBeans;
- }
-
- public Collection<RuntimeBeanEntry> getRuntimeBeans() {
- return runtimeBeans;
- }
-
- public String getJavaNamePrefix() {
- return initial.javaNamePrefix;
- }
-
- public String getNamespace() {
- return initial.namespace;
- }
-
- /**
- * Transform module to zero or more ModuleMXBeanEntry instances. Each
- * instance must have a globally unique local name.
- *
- * @return Map of identity local names as keys, and ModuleMXBeanEntry
- * instances as values
- */
- public static Map<String/* identity local name */, ModuleMXBeanEntry> create(
- final Module currentModule,
- final Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
- final SchemaContext schemaContext,
- final TypeProviderWrapper typeProviderWrapper, final String packageName) {
-
- ModuleMXBeanEntryBuilder builder = new ModuleMXBeanEntryBuilder().setModule(currentModule).setqNamesToSIEs(qNamesToSIEs)
- .setSchemaContext(schemaContext).setTypeProviderWrapper(typeProviderWrapper)
- .setPackageName(packageName);
-
- return builder.build();
- }
-
- public Map<String, AttributeIfc> getAttributes() {
- return yangToAttributes;
- }
-
- void setYangToAttributes(final Map<String, AttributeIfc> newAttributes) {
- this.yangToAttributes = newAttributes;
- }
-
- public String getNullableDescription() {
- return initial.description;
- }
-
- public QName getYangModuleQName() {
- return initial.qName;
- }
-
- @Override
- public String toString() {
- return "ModuleMXBeanEntry{" + "globallyUniqueName='"
- + initial.localName + '\'' + ", packageName='" + initial.packageName
- + '\'' + '}';
- }
-
- public String getNullableDummyContainerName() {
- return nullableDummyContainerName;
- }
-
- public void setNullableDummyContainerName(final String nullableDummyContainerName) {
- this.nullableDummyContainerName = nullableDummyContainerName;
- }
-
-
- static final class ModuleMXBeanEntryInitial {
-
- private final String localName;
- private final String description;
- private final String packageName;
- private final String javaNamePrefix;
- private final String namespace;
- private final QName qName;
-
- ModuleMXBeanEntryInitial(final String localName, final String description, final String packageName, final String javaNamePrefix, final String namespace, final QName qName) {
- this.localName = localName;
- this.description = description;
- this.packageName = packageName;
- this.javaNamePrefix = javaNamePrefix;
- this.namespace = namespace;
- this.qName = qName;
- }
- }
-
- static final class ModuleMXBeanEntryInitialBuilder {
- private String localName;
- private String description;
- private String packageName;
- private String javaNamePrefix;
- private String namespace;
- private QName qName;
-
- public ModuleMXBeanEntryInitialBuilder setPackageName(final String packageName) {
- this.packageName = packageName;
- return this;
- }
-
- public ModuleMXBeanEntryInitialBuilder setJavaNamePrefix(final String javaNamePrefix) {
- this.javaNamePrefix = javaNamePrefix;
- return this;
- }
-
- public ModuleMXBeanEntryInitialBuilder setNamespace(final String namespace) {
- this.namespace = namespace;
- return this;
- }
-
- public ModuleMXBeanEntryInitialBuilder setqName(final QName qName) {
- this.qName = qName;
- return this;
- }
-
- public ModuleMXBeanEntry.ModuleMXBeanEntryInitial build() {
- return new ModuleMXBeanEntry.ModuleMXBeanEntryInitial(localName, description, packageName, javaNamePrefix, namespace, qName);
- }
-
- public ModuleMXBeanEntryInitialBuilder setIdSchemaNode(final IdentitySchemaNode idSchemaNode) {
- this.localName = idSchemaNode.getQName().getLocalName();
- this.description = idSchemaNode.getDescription().orElse(null);
- return this;
- }
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Preconditions.checkState;
-import static java.lang.String.format;
-import static org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants.createConfigQName;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.annotation.Nullable;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AbstractDependencyAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.DependencyAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.NameConflictException;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.ServiceRef;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
-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.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.ModuleImport;
-import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
-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.UnknownSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.UsesNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-final class ModuleMXBeanEntryBuilder {
-
- private static final String TYPE = "type";
-
- private Module currentModule;
- private Map<QName, ServiceInterfaceEntry> qNamesToSIEs;
- private SchemaContext schemaContext;
- private TypeProviderWrapper typeProviderWrapper;
- private String packageName;
-
- public ModuleMXBeanEntryBuilder setModule(final Module module) {
- this.currentModule = module;
- return this;
- }
-
- public ModuleMXBeanEntryBuilder setqNamesToSIEs(final Map<QName, ServiceInterfaceEntry> qNamesToSIEs) {
- this.qNamesToSIEs = qNamesToSIEs;
- return this;
- }
-
- public ModuleMXBeanEntryBuilder setSchemaContext(final SchemaContext schemaContext) {
- this.schemaContext = schemaContext;
- return this;
- }
-
- public ModuleMXBeanEntryBuilder setTypeProviderWrapper(final TypeProviderWrapper typeProviderWrapper) {
- this.typeProviderWrapper = typeProviderWrapper;
- return this;
- }
-
- public ModuleMXBeanEntryBuilder setPackageName(final String packageName) {
- this.packageName = packageName;
- return this;
- }
-
- private static final Logger LOG = LoggerFactory
- .getLogger(ModuleMXBeanEntryBuilder.class);
-
- // TODO: the XPath should be parsed by code generator IMO
- private static final String MAGIC_STRING = "MAGIC_STRING";
- private static final String MODULE_CONDITION_XPATH_TEMPLATE = "^/MAGIC_STRING:modules/MAGIC_STRING:module/MAGIC_STRING:type\\s*=\\s*['\"](.+)['\"]$";
-
- private static final SchemaPath AUGMENT_SCHEMAPATH = SchemaPath.create(true,
- createConfigQName("modules"), createConfigQName("module"));
-
- private static final SchemaPath EXPECTED_CONFIGURATION_AUGMENTATION_SCHEMA_PATH =
- AUGMENT_SCHEMAPATH.createChild(createConfigQName("configuration"));
- private static final SchemaPath EXPECTED_STATE_AUGMENTATION_SCHEMA_PATH =
- AUGMENT_SCHEMAPATH.createChild(createConfigQName("state"));
- private static final Pattern PREFIX_COLON_LOCAL_NAME = Pattern.compile("^(.+):(.+)$");
-
- public Map<String, ModuleMXBeanEntry> build() {
- LOG.debug("Generating ModuleMXBeans of {} to package {}",
- currentModule.getNamespace(), packageName);
-
- String configModulePrefix;
- try {
- configModulePrefix = getConfigModulePrefixFromImport(currentModule);
- } catch (IllegalArgumentException e) {
- // this currentModule does not import config currentModule
- return Collections.emptyMap();
- }
-
- // get identities of base config:currentModule-type
- Map<String, IdentitySchemaNode> moduleIdentities = getIdentityMap();
-
- Map<String, QName> uniqueGeneratedClassesNames = new HashMap<>();
-
- // each currentModule name should have an augmentation defined
- Map<String, IdentitySchemaNode> unaugmentedModuleIdentities = new HashMap<>(
- moduleIdentities);
-
- Map<String, ModuleMXBeanEntry> result = new HashMap<>();
-
- for (AugmentationSchemaNode augmentation : currentModule.getAugmentations()) {
- Collection<DataSchemaNode> childNodes = augmentation.getChildNodes();
- if (areAllChildrenCaseSchemaNodes(childNodes)) {
- for (CaseSchemaNode childCase : castChildNodesToChoiceCases(childNodes)) {
- // TODO refactor, extract to standalone builder class
- processCaseSchemaNode(result, uniqueGeneratedClassesNames, configModulePrefix, moduleIdentities,
- unaugmentedModuleIdentities, augmentation, childCase);
- }
- } // skip if child nodes are not all cases
- }
- // clean up nulls
- cleanUpNulls(result);
- // check attributes name uniqueness
- checkAttributeNamesUniqueness(uniqueGeneratedClassesNames, result);
- checkUnaugumentedIdentities(unaugmentedModuleIdentities);
-
- LOG.debug("Number of ModuleMXBeans to be generated: {}", result.size());
-
- return result;
- }
-
- private static void cleanUpNulls(final Map<String, ModuleMXBeanEntry> result) {
- for (Map.Entry<String, ModuleMXBeanEntry> entry : result.entrySet()) {
- ModuleMXBeanEntry module = entry.getValue();
- if (module.getAttributes() == null) {
- module.setYangToAttributes(Collections
- .<String, AttributeIfc> emptyMap());
- } else if (module.getRuntimeBeans() == null) {
- module.setRuntimeBeans(Collections
- .<RuntimeBeanEntry> emptyList());
- }
- }
- }
-
- private static void checkUnaugumentedIdentities(final Map<String, IdentitySchemaNode> unaugmentedModuleIdentities) {
- if (unaugmentedModuleIdentities.size() > 0) {
- LOG.warn("Augmentation not found for all currentModule identities: {}",
- unaugmentedModuleIdentities.keySet());
- }
- }
-
- private static void checkAttributeNamesUniqueness(final Map<String, QName> uniqueGeneratedClassesNames,
- final Map<String, ModuleMXBeanEntry> result) {
- for (Map.Entry<String, ModuleMXBeanEntry> entry : result.entrySet()) {
- checkUniqueRuntimeBeanAttributesName(entry.getValue(),
- uniqueGeneratedClassesNames);
- }
- }
-
- private Map<String, IdentitySchemaNode> getIdentityMap() {
- Map<String, IdentitySchemaNode> moduleIdentities = Maps.newHashMap();
-
- for (IdentitySchemaNode id : currentModule.getIdentities()) {
- if (!id.getBaseIdentities().isEmpty()
- && ConfigConstants.MODULE_TYPE_Q_NAME.equals(id.getBaseIdentities().iterator().next().getQName())) {
- String identityLocalName = id.getQName().getLocalName();
- if (moduleIdentities.containsKey(identityLocalName)) {
- throw new IllegalStateException("Module name already defined in this currentModule: "
- + identityLocalName);
- } else {
- moduleIdentities.put(identityLocalName, id);
- LOG.debug("Found identity {}", identityLocalName);
- }
- // validation check on unknown schema nodes
- boolean providedServiceWasSet = false;
- for (UnknownSchemaNode unknownNode : id.getUnknownSchemaNodes()) {
- // TODO: test this
- boolean unknownNodeIsProvidedServiceExtension = ConfigConstants.PROVIDED_SERVICE_EXTENSION_QNAME.equals(unknownNode.getNodeType());
- // true => no op: 0 or more provided identities are allowed
-
- if (ConfigConstants.JAVA_NAME_PREFIX_EXTENSION_QNAME.equals(unknownNode.getNodeType())) {
- // 0..1 allowed
- checkState(
- providedServiceWasSet == false,
- format("More than one language extension %s is not allowed here: %s",
- ConfigConstants.JAVA_NAME_PREFIX_EXTENSION_QNAME, id));
- providedServiceWasSet = true;
- } else if (unknownNodeIsProvidedServiceExtension == false) {
- throw new IllegalStateException("Unexpected language extension " + unknownNode.getNodeType());
- }
- }
- }
- }
-
- return moduleIdentities;
- }
-
- private static Collection<CaseSchemaNode> castChildNodesToChoiceCases(final Collection<DataSchemaNode> childNodes) {
- return Collections2.transform(childNodes, new Function<DataSchemaNode, CaseSchemaNode>() {
- @Nullable
- @Override
- public CaseSchemaNode apply(@Nullable final DataSchemaNode input) {
- return (CaseSchemaNode) input;
- }
- });
- }
-
- private static boolean areAllChildrenCaseSchemaNodes(final Iterable<DataSchemaNode> childNodes) {
- for (DataSchemaNode childNode : childNodes) {
- if (childNode instanceof CaseSchemaNode == false) {
- return false;
- }
- }
- return true;
- }
-
- private <HAS_CHILDREN_AND_QNAME extends DataNodeContainer & SchemaNode> void processCaseSchemaNode(
- final Map<String, ModuleMXBeanEntry> result,
- final Map<String, QName> uniqueGeneratedClassesNames, final String configModulePrefix,
- final Map<String, IdentitySchemaNode> moduleIdentities,
- final Map<String, IdentitySchemaNode> unaugmentedModuleIdentities,
- final AugmentationSchemaNode augmentation, final DataSchemaNode when) {
-
- CaseSchemaNode choiceCaseNode = (CaseSchemaNode) when;
- if (!choiceCaseNode.getWhenCondition().isPresent()) {
- return;
- }
- java.util.Optional<RevisionAwareXPath> xPath = choiceCaseNode.getWhenCondition();
- checkState(xPath.isPresent(), "Choice node %s does not have a when condition", choiceCaseNode);
- Matcher matcher = getWhenConditionMatcher(configModulePrefix, xPath.get());
- if (matcher.matches() == false) {
- return;
- }
- String moduleLocalNameFromXPath = matcher.group(1);
- IdentitySchemaNode moduleIdentity = moduleIdentities.get(moduleLocalNameFromXPath);
- unaugmentedModuleIdentities.remove(moduleLocalNameFromXPath);
- checkState(moduleIdentity != null, "Cannot find identity %s matching augmentation %s", moduleLocalNameFromXPath, augmentation);
- Map<String, QName> providedServices = findProvidedServices(moduleIdentity, currentModule, qNamesToSIEs,
- schemaContext);
-
- String javaNamePrefix = TypeProviderWrapper.findJavaNamePrefix(moduleIdentity);
-
- Map<String, AttributeIfc> yangToAttributes = null;
- // runtime-data
- Collection<RuntimeBeanEntry> runtimeBeans = null;
-
- HAS_CHILDREN_AND_QNAME dataNodeContainer = getDataNodeContainer(choiceCaseNode);
-
- if (EXPECTED_CONFIGURATION_AUGMENTATION_SCHEMA_PATH.equals(augmentation.getTargetPath())) {
- LOG.debug("Parsing configuration of {}", moduleLocalNameFromXPath);
- yangToAttributes = fillConfiguration(dataNodeContainer, currentModule, typeProviderWrapper, qNamesToSIEs,
- schemaContext, packageName);
- checkUniqueAttributesWithGeneratedClass(uniqueGeneratedClassesNames, when.getQName(), yangToAttributes);
- } else if (EXPECTED_STATE_AUGMENTATION_SCHEMA_PATH.equals(augmentation.getTargetPath())) {
- LOG.debug("Parsing state of {}", moduleLocalNameFromXPath);
- try {
- runtimeBeans = fillRuntimeBeans(dataNodeContainer, currentModule, typeProviderWrapper, packageName,
- moduleLocalNameFromXPath, javaNamePrefix);
- } catch (NameConflictException e) {
- throw new NameConflictException(e.getConflictingName(), when.getQName(), when.getQName());
- }
- checkUniqueRuntimeBeansGeneratedClasses(uniqueGeneratedClassesNames, when, runtimeBeans);
- Set<RuntimeBeanEntry> runtimeBeanEntryValues = Sets.newHashSet(runtimeBeans);
- for (RuntimeBeanEntry entry : runtimeBeanEntryValues) {
- checkUniqueAttributesWithGeneratedClass(uniqueGeneratedClassesNames, when.getQName(),
- entry.getYangPropertiesToTypesMap());
- }
-
- } else {
- throw new IllegalArgumentException("Cannot parse augmentation " + augmentation);
- }
- boolean hasDummyContainer = choiceCaseNode.equals(dataNodeContainer) == false;
-
- String nullableDummyContainerName = hasDummyContainer ? dataNodeContainer.getQName().getLocalName() : null;
- if (result.containsKey(moduleLocalNameFromXPath)) {
- // either fill runtimeBeans or yangToAttributes, merge
- ModuleMXBeanEntry moduleMXBeanEntry = result.get(moduleLocalNameFromXPath);
- if (yangToAttributes != null && moduleMXBeanEntry.getAttributes() == null) {
- moduleMXBeanEntry.setYangToAttributes(yangToAttributes);
- } else if (runtimeBeans != null && moduleMXBeanEntry.getRuntimeBeans() == null) {
- moduleMXBeanEntry.setRuntimeBeans(runtimeBeans);
- }
- checkState(Objects.equals(nullableDummyContainerName, moduleMXBeanEntry.getNullableDummyContainerName()),
- "Mismatch in module " + moduleMXBeanEntry.toString() + " - dummy container must be present/missing in" +
- " both state and configuration");
- } else {
- ModuleMXBeanEntry.ModuleMXBeanEntryInitial initial = new ModuleMXBeanEntry.ModuleMXBeanEntryInitialBuilder()
- .setIdSchemaNode(moduleIdentity).setPackageName(packageName).setJavaNamePrefix(javaNamePrefix)
- .setNamespace(currentModule.getNamespace().toString()).setqName(ModuleUtil.getQName(currentModule))
- .build();
-
- // construct ModuleMXBeanEntry
- ModuleMXBeanEntry moduleMXBeanEntry = new ModuleMXBeanEntry(initial, yangToAttributes, providedServices,
- runtimeBeans);
-
- moduleMXBeanEntry.setYangModuleName(currentModule.getName());
- moduleMXBeanEntry.setYangModuleLocalname(moduleLocalNameFromXPath);
- moduleMXBeanEntry.setNullableDummyContainerName(nullableDummyContainerName);
- result.put(moduleLocalNameFromXPath, moduleMXBeanEntry);
- }
- }
-
- private static void checkUniqueRuntimeBeansGeneratedClasses(final Map<String, QName> uniqueGeneratedClassesNames,
- final DataSchemaNode when, final Collection<RuntimeBeanEntry> runtimeBeans) {
- for (RuntimeBeanEntry runtimeBean : runtimeBeans) {
- final String javaNameOfRuntimeMXBean = runtimeBean.getJavaNameOfRuntimeMXBean();
- if (uniqueGeneratedClassesNames.containsKey(javaNameOfRuntimeMXBean)) {
- QName firstDefinedQName = uniqueGeneratedClassesNames.get(javaNameOfRuntimeMXBean);
- throw new NameConflictException(javaNameOfRuntimeMXBean, firstDefinedQName, when.getQName());
- }
- uniqueGeneratedClassesNames.put(javaNameOfRuntimeMXBean, when.getQName());
- }
- }
-
- private static void checkUniqueRuntimeBeanAttributesName(final ModuleMXBeanEntry mxBeanEntry,
- final Map<String, QName> uniqueGeneratedClassesNames) {
- for (RuntimeBeanEntry runtimeBeanEntry : mxBeanEntry.getRuntimeBeans()) {
- for (String runtimeAttName : runtimeBeanEntry.getYangPropertiesToTypesMap().keySet()) {
- if (mxBeanEntry.getAttributes().keySet().contains(runtimeAttName)) {
- QName qName1 = uniqueGeneratedClassesNames.get(runtimeBeanEntry.getJavaNameOfRuntimeMXBean());
- QName qName2 = uniqueGeneratedClassesNames.get(mxBeanEntry.getGloballyUniqueName());
- throw new NameConflictException(runtimeAttName, qName1, qName2);
- }
- }
- }
- }
-
- private static void checkUniqueAttributesWithGeneratedClass(final Map<String, QName> uniqueGeneratedClassNames,
- final QName parentQName, final Map<String, AttributeIfc> yangToAttributes) {
- for (Map.Entry<String, AttributeIfc> attr : yangToAttributes.entrySet()) {
- if (attr.getValue() instanceof TOAttribute) {
- checkUniqueTOAttr(uniqueGeneratedClassNames, parentQName, (TOAttribute) attr.getValue());
- } else if (attr.getValue() instanceof ListAttribute
- && ((ListAttribute) attr.getValue()).getInnerAttribute() instanceof TOAttribute) {
- checkUniqueTOAttr(uniqueGeneratedClassNames, parentQName,
- (TOAttribute) ((ListAttribute) attr.getValue()).getInnerAttribute());
- }
- }
- }
-
- private static void checkUniqueTOAttr(final Map<String, QName> uniqueGeneratedClassNames, final QName parentQName, final TOAttribute attr) {
- final String upperCaseCamelCase = attr.getUpperCaseCammelCase();
- if (uniqueGeneratedClassNames.containsKey(upperCaseCamelCase)) {
- QName firstDefinedQName = uniqueGeneratedClassNames.get(upperCaseCamelCase);
- throw new NameConflictException(upperCaseCamelCase, firstDefinedQName, parentQName);
- } else {
- uniqueGeneratedClassNames.put(upperCaseCamelCase, parentQName);
- }
- }
-
- private Collection<RuntimeBeanEntry> fillRuntimeBeans(final DataNodeContainer dataNodeContainer, final Module currentModule,
- final TypeProviderWrapper typeProviderWrapper, final String packageName, final String moduleLocalNameFromXPath,
- final String javaNamePrefix) {
-
- return RuntimeBeanEntry.extractClassNameToRuntimeBeanMap(packageName, dataNodeContainer, moduleLocalNameFromXPath,
- typeProviderWrapper, javaNamePrefix, currentModule, schemaContext).values();
-
- }
-
- /**
- * Since each case statement within a module must provide unique child nodes, it is allowed to wrap
- * the actual configuration with a container node with name equal to case name.
- *
- * @param choiceCaseNode state or configuration case statement
- * @return either choiceCaseNode or its only child container
- */
- private static <HAS_CHILDREN_AND_QNAME extends DataNodeContainer & SchemaNode> HAS_CHILDREN_AND_QNAME getDataNodeContainer(final CaseSchemaNode choiceCaseNode) {
- Collection<DataSchemaNode> childNodes = choiceCaseNode.getChildNodes();
- if (childNodes.size() == 1) {
- DataSchemaNode onlyChild = childNodes.iterator().next();
- if (onlyChild instanceof ContainerSchemaNode) {
- ContainerSchemaNode onlyContainer = (ContainerSchemaNode) onlyChild;
- if (Objects.equals(onlyContainer.getQName().getLocalName(), choiceCaseNode.getQName().getLocalName())) {
- // the actual configuration is inside dummy container
- return (HAS_CHILDREN_AND_QNAME) onlyContainer;
- }
- }
- }
- return (HAS_CHILDREN_AND_QNAME) choiceCaseNode;
- }
-
- private static Map<String, AttributeIfc> fillConfiguration(final DataNodeContainer dataNodeContainer, final Module currentModule,
- final TypeProviderWrapper typeProviderWrapper, final Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
- final SchemaContext schemaContext, final String packageName) {
- Map<String, AttributeIfc> yangToAttributes = new HashMap<>();
- for (DataSchemaNode attrNode : dataNodeContainer.getChildNodes()) {
- AttributeIfc attributeValue = getAttributeValue(attrNode, currentModule, qNamesToSIEs, typeProviderWrapper,
- schemaContext, packageName);
- yangToAttributes.put(attributeValue.getAttributeYangName(), attributeValue);
- }
- return yangToAttributes;
- }
-
- private static Map<String, QName> findProvidedServices(final IdentitySchemaNode moduleIdentity, final Module currentModule,
- final Map<QName, ServiceInterfaceEntry> qNamesToSIEs, final SchemaContext schemaContext) {
- Map<String, QName> result = new HashMap<>();
- for (UnknownSchemaNode unknownNode : moduleIdentity.getUnknownSchemaNodes()) {
- if (ConfigConstants.PROVIDED_SERVICE_EXTENSION_QNAME.equals(unknownNode.getNodeType())) {
- String prefixAndIdentityLocalName = unknownNode.getNodeParameter();
- ServiceInterfaceEntry sie = findSIE(prefixAndIdentityLocalName, currentModule, qNamesToSIEs,
- schemaContext);
- result.put(sie.getFullyQualifiedName(), sie.getQName());
- }
- }
- return result;
- }
-
- private static AttributeIfc getAttributeValue(final DataSchemaNode attrNode, final Module currentModule,
- final Map<QName, ServiceInterfaceEntry> qNamesToSIEs, final TypeProviderWrapper typeProviderWrapper,
- final SchemaContext schemaContext, final String packageName) {
-
- if (attrNode instanceof LeafSchemaNode) {
- // simple type
- LeafSchemaNode leaf = (LeafSchemaNode) attrNode;
- return new JavaAttribute(leaf, typeProviderWrapper);
- } else if (attrNode instanceof ContainerSchemaNode) {
- // reference or TO
- ContainerSchemaNode containerSchemaNode = (ContainerSchemaNode) attrNode;
- Optional<? extends AbstractDependencyAttribute> dependencyAttributeOptional = extractDependency(
- containerSchemaNode, attrNode, currentModule, qNamesToSIEs, schemaContext);
- if (dependencyAttributeOptional.isPresent()) {
- return dependencyAttributeOptional.get();
- } else {
- return TOAttribute.create(containerSchemaNode, typeProviderWrapper, packageName);
- }
-
- } else if (attrNode instanceof LeafListSchemaNode) {
- return ListAttribute.create((LeafListSchemaNode) attrNode, typeProviderWrapper);
- } else if (attrNode instanceof ListSchemaNode) {
- ListSchemaNode listSchemaNode = (ListSchemaNode) attrNode;
- Optional<? extends AbstractDependencyAttribute> dependencyAttributeOptional = extractDependency(
- listSchemaNode, attrNode, currentModule, qNamesToSIEs, schemaContext);
- if (dependencyAttributeOptional.isPresent()) {
- return dependencyAttributeOptional.get();
- } else {
- return ListAttribute.create(listSchemaNode, typeProviderWrapper, packageName);
- }
- } else {
- throw new UnsupportedOperationException("Unknown configuration node " + attrNode.toString());
- }
- }
-
- private static Optional<? extends AbstractDependencyAttribute> extractDependency(final DataNodeContainer dataNodeContainer,
- final DataSchemaNode attrNode, final Module currentModule, final Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
- final SchemaContext schemaContext) {
- if (isDependencyContainer(dataNodeContainer)) {
- // reference
- UsesNode usesNode = dataNodeContainer.getUses().iterator().next();
- for (SchemaNode refineNode : usesNode.getRefines().values()) {
- // this will ignore name nodes, since they are not needed here
- if (TYPE.equals(refineNode.getQName().getLocalName())){
- checkState(refineNode.getUnknownSchemaNodes().size() == 1, "Unexpected unknown schema node size of " + refineNode);
- UnknownSchemaNode requiredIdentity = refineNode.getUnknownSchemaNodes().iterator().next();
- checkState(ConfigConstants.REQUIRED_IDENTITY_EXTENSION_QNAME.equals(requiredIdentity.getNodeType()),
- "Unexpected language extension " + requiredIdentity);
- String prefixAndIdentityLocalName = requiredIdentity.getNodeParameter();
- // import should point to a module
- ServiceInterfaceEntry serviceInterfaceEntry = findSIE(prefixAndIdentityLocalName, currentModule,
- qNamesToSIEs, schemaContext);
- LeafSchemaNode refine = (LeafSchemaNode) usesNode.getRefines().values().iterator().next();
-
- boolean mandatory = refine.isMandatory();
- AbstractDependencyAttribute reference;
- if (dataNodeContainer instanceof ContainerSchemaNode) {
- reference = new DependencyAttribute(attrNode, serviceInterfaceEntry, mandatory,
- attrNode.getDescription().orElse(null));
- } else {
- reference = new ListDependenciesAttribute(attrNode, serviceInterfaceEntry, mandatory,
- attrNode.getDescription().orElse(null));
- }
- return Optional.of(reference);
- }
- }
- }
- return Optional.absent();
- }
-
- private static boolean isDependencyContainer(final DataNodeContainer dataNodeContainer) {
- if(dataNodeContainer.getUses().size() != 1) {
- return false;
- }
- UsesNode onlyUses = dataNodeContainer.getUses().iterator().next();
- if(onlyUses.getGroupingPath().getLastComponent().equals(ServiceRef.QNAME) == false) {
- return false;
- }
-
- return getChildNodeSizeWithoutUses(dataNodeContainer) == 0;
- }
-
- private static int getChildNodeSizeWithoutUses(final DataNodeContainer csn) {
- int result = 0;
- for (DataSchemaNode dsn : csn.getChildNodes()) {
- if (dsn.isAddedByUses() == false) {
- result++;
- }
- }
- return result;
- }
-
- private static ServiceInterfaceEntry findSIE(final String prefixAndIdentityLocalName, final Module currentModule,
- final Map<QName, ServiceInterfaceEntry> qNamesToSIEs, final SchemaContext schemaContext) {
-
- Matcher m = PREFIX_COLON_LOCAL_NAME.matcher(prefixAndIdentityLocalName);
- Module foundModule;
- String localSIName;
- if (m.matches()) {
- // if there is a prefix, look for ModuleImport with this prefix. Get
- // Module from SchemaContext
- String prefix = m.group(1);
- ModuleImport moduleImport = findModuleImport(currentModule, prefix);
- foundModule = schemaContext.findModule(moduleImport.getModuleName(), moduleImport.getRevision()).orElse(null);
- checkNotNull(foundModule, format("Module not found in SchemaContext by %s", moduleImport));
- localSIName = m.group(2);
- } else {
- foundModule = currentModule; // no prefix => SIE is in currentModule
- localSIName = prefixAndIdentityLocalName;
- }
- QName siQName = QName.create(foundModule.getNamespace(), foundModule.getRevision(), localSIName);
- ServiceInterfaceEntry sie = qNamesToSIEs.get(siQName);
- checkState(sie != null, "Cannot find referenced Service Interface by " + prefixAndIdentityLocalName);
- return sie;
- }
-
- private static ModuleImport findModuleImport(final Module module, final String prefix) {
- for (ModuleImport moduleImport : module.getImports()) {
- if (moduleImport.getPrefix().equals(prefix)) {
- return moduleImport;
- }
- }
- throw new IllegalStateException(format("Import not found with prefix %s in %s", prefix, module));
- }
-
- @VisibleForTesting
- static Matcher getWhenConditionMatcher(final String prefix, final RevisionAwareXPath whenConstraint) {
- String xpathRegex = MODULE_CONDITION_XPATH_TEMPLATE.replace(MAGIC_STRING, prefix);
- Pattern pattern = Pattern.compile(xpathRegex);
- return pattern.matcher(whenConstraint.toString());
- }
-
- private static String getConfigModulePrefixFromImport(final Module currentModule) {
- for (ModuleImport currentImport : currentModule.getImports()) {
- if (currentImport.getModuleName().equals(ConfigConstants.CONFIG_MODULE)) {
- return currentImport.getPrefix();
- }
- }
- throw new IllegalArgumentException("Cannot find import " + ConfigConstants.CONFIG_MODULE + " in "
- + currentModule);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-public class ModuleUtil {
-
- private ModuleUtil() {
- }
-
- public static QName getQName(final Module currentModule) {
- return QName.create(currentModule.getNamespace(), currentModule.getRevision(), currentModule.getName());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import java.util.Map;
-import java.util.Map.Entry;
-import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-/**
- * Maps from module namespaces to java package names using a Map<String, String>,
- * where key is namespace prefix and value is package that replaces matched prefix.
- */
-public class PackageTranslator {
- private final Map<String, String> namespacePrefixToPackageMap;
-
- public PackageTranslator(final Map<String, String> namespacePrefixToPackageMap) {
- this.namespacePrefixToPackageMap = namespacePrefixToPackageMap;
- }
-
- /**
- * Based on mapping, find longest matching key and return value plus the
- * remaining part of namespace, with colons replaced by dots. Example:
- * Mapping [ 'urn:opendaylight:params:xml:ns:yang:controller' :
- * 'org.opendaylight.controller'] and module with namespace
- * 'urn:opendaylight:params:xml:ns:yang:controller:threads:api' will result
- * in 'org.opendaylight.controller.threads.api' .
- *
- * @throws IllegalStateException
- * if there is no mapping found.
- */
- public String getPackageName(final Module module) {
- Entry<String, String> longestMatch = null;
- int longestMatchLength = 0;
- final String namespace = module.getNamespace().toString();
- for (final Entry<String, String> entry : this.namespacePrefixToPackageMap
- .entrySet()) {
- if (namespace.startsWith(entry.getKey())
- && (entry.getKey().length() > longestMatchLength)) {
- longestMatch = entry;
- longestMatchLength = entry.getKey().length();
- }
- }
- if (longestMatch != null) {
- return longestMatch.getValue()
- + sanitizePackage(namespace.substring(longestMatchLength));
- } else {
- return BindingGeneratorUtil.moduleNamespaceToPackageName(module);
- }
- }
-
- // TODO add to PackageTranslator
- private static String sanitizePackage(final String namespace) {
- String newNamespace = namespace;
- newNamespace = newNamespace.replace("://", ".");
- newNamespace = newNamespace.replace("/", ".");
- newNamespace = newNamespace.replace(":", ".");
- newNamespace = newNamespace.replace("-", "_");
- newNamespace = newNamespace.replace("@", ".");
- newNamespace = newNamespace.replace("$", ".");
- newNamespace = newNamespace.replace("#", ".");
- newNamespace = newNamespace.replace("'", ".");
- newNamespace = newNamespace.replace("*", ".");
- newNamespace = newNamespace.replace("+", ".");
- newNamespace = newNamespace.replace(",", ".");
- newNamespace = newNamespace.replace(";", ".");
- newNamespace = newNamespace.replace("=", ".");
- return newNamespace;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkState;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Multimap;
-import com.google.common.collect.Sets;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.VoidAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.NameConflictException;
-import org.opendaylight.yangtools.yang.common.QName;
-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.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.UsesNode;
-import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
-
-/**
- * Holds information about runtime bean to be generated. There are two kinds of
- * RuntimeBeanEntry instances: if isRoot flag is set to true, this bean
- * represents state that must be present at time of configuration module
- * instantiation. Root RB must have depthLevel set to 0 and cannot have
- * children. There might be other RBs defined in yang, but no other RB can have
- * isRoot set to true. At least one RB must be root and all other RBs must be
- * lined via children so that a tree with all beans can be created.
- */
-public class RuntimeBeanEntry {
-
- private static final Function<UnknownSchemaNode, String> UNKNOWN_NODE_TO_STRING =
- input -> input.getQName().getLocalName() + input.getNodeParameter();
-
- private final String packageName;
- private final String yangName, javaNamePrefix;
- private final boolean isRoot;
- private final Optional<String> keyYangName, keyJavaName;
- private final Map<String, AttributeIfc> attributeMap;
- private final List<RuntimeBeanEntry> children;
- private final Set<Rpc> rpcs;
-
- @VisibleForTesting
- RuntimeBeanEntry(final String packageName,
- final DataNodeContainer nodeForReporting, final String yangName,
- final String javaNamePrefix, final boolean isRoot,
- final Optional<String> keyYangName, final List<AttributeIfc> attributes,
- final List<RuntimeBeanEntry> children, final Set<Rpc> rpcs) {
-
- checkArgument(isRoot == false || keyYangName.isPresent() == false,
- "Root RuntimeBeanEntry must not have key set");
- this.packageName = packageName;
- this.isRoot = isRoot;
- this.yangName = yangName;
- this.javaNamePrefix = javaNamePrefix;
- this.children = Collections.unmodifiableList(children);
- this.rpcs = Collections.unmodifiableSet(rpcs);
-
- this.keyYangName = keyYangName;
- Map<String, AttributeIfc> map = new HashMap<>();
-
- for (AttributeIfc a : attributes) {
- checkState(map.containsKey(a.getAttributeYangName()) == false,
- "Attribute already defined: %s in %s", a.getAttributeYangName(), nodeForReporting);
- map.put(a.getAttributeYangName(), a);
- }
-
- if (keyYangName.isPresent()) {
- AttributeIfc keyJavaName = map.get(keyYangName.get());
- checkArgument(keyJavaName != null, "Key %s not found in attribute list %s in %s", keyYangName.get(),
- attributes, nodeForReporting);
- this.keyJavaName = Optional
- .of(keyJavaName.getUpperCaseCammelCase());
- } else {
- keyJavaName = Optional.absent();
- }
- attributeMap = Collections.unmodifiableMap(map);
- }
-
- /**
- * @return map containing all class names as key, extracted RuntimeBeans as
- * values. If more than zero values is returned, exactly one
- * RuntimeBeanEntry will have isRoot set to true, even if yang does
- * not contain special configuration for it.
- */
- public static Map<String, RuntimeBeanEntry> extractClassNameToRuntimeBeanMap(
- final String packageName, final DataNodeContainer container,
- final String moduleYangName, final TypeProviderWrapper typeProviderWrapper,
- final String javaNamePrefix, final Module currentModule, final SchemaContext schemaContext) {
-
-
- AttributesRpcsAndRuntimeBeans attributesRpcsAndRuntimeBeans = extractSubtree(
- packageName, container, typeProviderWrapper, currentModule,
- schemaContext);
- Map<String, RuntimeBeanEntry> result = new HashMap<>();
-
- List<AttributeIfc> attributes;
- Set<Rpc> rpcs;
- if (attributesRpcsAndRuntimeBeans.isEmpty() == false) {
- attributes = attributesRpcsAndRuntimeBeans.getAttributes();
- rpcs = attributesRpcsAndRuntimeBeans.getRpcs();
- } else {
- // create artificial root if not defined in yang
- attributes = Collections.emptyList();
- rpcs = Collections.emptySet();
- }
- RuntimeBeanEntry rootRuntimeBeanEntry = createRoot(packageName,
- container, moduleYangName, attributes, javaNamePrefix,
- attributesRpcsAndRuntimeBeans.getRuntimeBeanEntries(), rpcs);
-
- Deque<RuntimeBeanEntry> stack = new LinkedList<>();
- stack.add(rootRuntimeBeanEntry);
-
- while (stack.isEmpty() == false) {
- RuntimeBeanEntry first = stack.pollFirst();
- if (result.containsKey(first.getJavaNameOfRuntimeMXBean())) {
- throw new NameConflictException(
- first.getJavaNameOfRuntimeMXBean(), null, null);
- }
- result.put(first.getJavaNameOfRuntimeMXBean(), first);
- stack.addAll(first.getChildren());
- }
- return result;
- }
-
- private static Multimap<QName/* of identity */, RpcDefinition> getIdentitiesToRpcs(
- final SchemaContext schemaCtx) {
- Multimap<QName, RpcDefinition> result = HashMultimap.create();
- for (Module currentModule : schemaCtx.getModules()) {
-
- // Find all identities in current module for later identity->rpc mapping
- Set<QName> allIdentitiesInModule =
- Sets.newHashSet(Collections2.transform(currentModule.getIdentities(), SchemaNode::getQName));
-
- for (RpcDefinition rpc : currentModule.getRpcs()) {
- ContainerSchemaNode input = rpc.getInput();
- if (input != null) {
- for (UsesNode uses : input.getUses()) {
-
- // Check if the rpc is config rpc by looking for input argument rpc-context-ref
- Iterator<QName> pathFromRoot = uses.getGroupingPath().getPathFromRoot().iterator();
- if (!pathFromRoot.hasNext() ||
- !pathFromRoot.next().equals(ConfigConstants.RPC_CONTEXT_REF_GROUPING_QNAME)) {
- continue;
- }
-
- for (SchemaNode refinedNode : uses.getRefines().values()) {
- for (UnknownSchemaNode unknownSchemaNode : refinedNode
- .getUnknownSchemaNodes()) {
- if (ConfigConstants.RPC_CONTEXT_INSTANCE_EXTENSION_QNAME
- .equals(unknownSchemaNode.getNodeType())) {
- String localIdentityName = unknownSchemaNode
- .getNodeParameter();
- QName identityQName = QName.create(
- currentModule.getNamespace(),
- currentModule.getRevision(),
- localIdentityName);
- Preconditions.checkArgument(allIdentitiesInModule.contains(identityQName),
- "Identity referenced by rpc not found. Identity: %s, rpc: %s", localIdentityName, rpc);
- result.put(identityQName, rpc);
- }
- }
- }
- }
- }
- }
- }
- return result;
- }
-
- /**
- * Get direct descendants of this subtree, together with attributes defined
- * in subtree.
- */
- private static AttributesRpcsAndRuntimeBeans extractSubtree(
- final String packageName, final DataNodeContainer subtree,
- final TypeProviderWrapper typeProviderWrapper, final Module currentModule,
- final SchemaContext ctx) {
-
- Multimap<QName, RpcDefinition> identitiesToRpcs = getIdentitiesToRpcs(ctx);
-
- List<AttributeIfc> attributes = Lists.newArrayList();
- List<RuntimeBeanEntry> runtimeBeanEntries = new ArrayList<>();
- for (DataSchemaNode child : subtree.getChildNodes()) {
- // child leaves can be java attributes, TO attributes, or child
- // runtime beans
- if (child instanceof LeafSchemaNode) {
- // just save the attribute
- LeafSchemaNode leaf = (LeafSchemaNode) child;
- attributes.add(new JavaAttribute(leaf, typeProviderWrapper));
- } else if (child instanceof ContainerSchemaNode) {
- ContainerSchemaNode container = (ContainerSchemaNode) child;
- // this can be either TO or hierarchical RB
- TOAttribute toAttribute = TOAttribute.create(container,
- typeProviderWrapper, packageName);
- attributes.add(toAttribute);
- } else if (child instanceof ListSchemaNode) {
- if (isInnerStateBean(child)) {
- ListSchemaNode listSchemaNode = (ListSchemaNode) child;
- RuntimeBeanEntry hierarchicalChild = createHierarchical(
- packageName, listSchemaNode, typeProviderWrapper,
- currentModule, ctx);
- runtimeBeanEntries.add(hierarchicalChild);
- } else /* ordinary list attribute */{
- ListAttribute listAttribute = ListAttribute.create(
- (ListSchemaNode) child, typeProviderWrapper, packageName);
- attributes.add(listAttribute);
- }
-
- } else if (child instanceof LeafListSchemaNode) {
- ListAttribute listAttribute = ListAttribute.create(
- (LeafListSchemaNode) child, typeProviderWrapper);
- attributes.add(listAttribute);
- } else {
- throw new IllegalStateException("Unexpected running-data node "
- + child);
- }
- }
- Set<Rpc> rpcs = new HashSet<>();
- SchemaNode subtreeSchemaNode = (SchemaNode) subtree;
- for (UnknownSchemaNode unknownSchemaNode : subtreeSchemaNode
- .getUnknownSchemaNodes()) {
- if (ConfigConstants.RPC_CONTEXT_INSTANCE_EXTENSION_QNAME
- .equals(unknownSchemaNode.getNodeType())) {
- String localIdentityName = unknownSchemaNode.getNodeParameter();
- QName identityQName = unknownSchemaNode.isAddedByUses() ?
- findQNameFromGrouping(subtree, ctx, unknownSchemaNode, localIdentityName) :
- QName.create(currentModule.getNamespace(), currentModule.getRevision(), localIdentityName);
- // convert RpcDefinition to Rpc
- for (RpcDefinition rpcDefinition : identitiesToRpcs.get(identityQName)) {
- String name = TypeProviderWrapper
- .findJavaParameter(rpcDefinition);
- AttributeIfc returnType;
- if (rpcDefinition.getOutput() == null
- || rpcDefinition.getOutput().getChildNodes().isEmpty()) {
- returnType = VoidAttribute.getInstance();
- } else if (rpcDefinition.getOutput().getChildNodes().size() == 1) {
- DataSchemaNode returnDSN = rpcDefinition.getOutput()
- .getChildNodes().iterator().next();
- returnType = getReturnTypeAttribute(returnDSN, typeProviderWrapper, packageName);
-
- } else {
- throw new IllegalArgumentException(
- "More than one child node in rpc output is not supported. "
- + "Error occured in " + rpcDefinition);
- }
- List<JavaAttribute> parameters = new ArrayList<>();
- for (DataSchemaNode childNode : sortAttributes(rpcDefinition.getInput()
- .getChildNodes())) {
- if (childNode.isAddedByUses() == false) { // skip
- // refined
- // context-instance
- checkArgument(childNode instanceof LeafSchemaNode, "Unexpected type of rpc input type. "
- + "Currently only leafs and empty output nodes are supported, got " + childNode);
- JavaAttribute javaAttribute = new JavaAttribute(
- (LeafSchemaNode) childNode,
- typeProviderWrapper);
- parameters.add(javaAttribute);
- }
- }
- Rpc newRpc = new Rpc(returnType, name, rpcDefinition
- .getQName().getLocalName(), parameters);
- rpcs.add(newRpc);
- }
- }
- }
- return new AttributesRpcsAndRuntimeBeans(runtimeBeanEntries,
- attributes, rpcs);
- }
-
- /**
- * Find "proper" qname of unknown node in case it comes from a grouping
- */
- private static QName findQNameFromGrouping(final DataNodeContainer subtree, final SchemaContext ctx, final UnknownSchemaNode unknownSchemaNode, final String localIdentityName) {
- QName identityQName = null;
- for (UsesNode usesNode : subtree.getUses()) {
- SchemaNode dataChildByName = SchemaContextUtil.findDataSchemaNode(ctx, usesNode.getGroupingPath());
- Module m = SchemaContextUtil.findParentModule(ctx, dataChildByName);
- List<UnknownSchemaNode> unknownSchemaNodes = dataChildByName.getUnknownSchemaNodes();
- if(Collections2.transform(unknownSchemaNodes, UNKNOWN_NODE_TO_STRING).contains(UNKNOWN_NODE_TO_STRING.apply(unknownSchemaNode))) {
- identityQName = QName.create(dataChildByName.getQName(), localIdentityName);
- }
- }
- return identityQName;
- }
-
- private static AttributeIfc getReturnTypeAttribute(final DataSchemaNode child, final TypeProviderWrapper typeProviderWrapper,
- final String packageName) {
- if (child instanceof LeafSchemaNode) {
- LeafSchemaNode leaf = (LeafSchemaNode) child;
- return new JavaAttribute(leaf, typeProviderWrapper);
- } else if (child instanceof ContainerSchemaNode) {
- ContainerSchemaNode container = (ContainerSchemaNode) child;
- TOAttribute toAttribute = TOAttribute.create(container, typeProviderWrapper, packageName);
- return toAttribute;
- } else if (child instanceof ListSchemaNode) {
- return ListAttribute.create((ListSchemaNode) child, typeProviderWrapper, packageName);
- } else if (child instanceof LeafListSchemaNode) {
- return ListAttribute.create((LeafListSchemaNode) child, typeProviderWrapper);
- } else {
- throw new IllegalStateException("Unknown output data node " + child + " for rpc");
- }
- }
-
- private static Collection<DataSchemaNode> sortAttributes(final Collection<DataSchemaNode> childNodes) {
- final TreeSet<DataSchemaNode> dataSchemaNodes =
- new TreeSet<>(Comparator.comparing(o -> o.getQName().getLocalName()));
- dataSchemaNodes.addAll(childNodes);
- return dataSchemaNodes;
- }
-
- private static boolean isInnerStateBean(final DataSchemaNode child) {
- for (UnknownSchemaNode unknownSchemaNode : child
- .getUnknownSchemaNodes()) {
- if (unknownSchemaNode.getNodeType().equals(
- ConfigConstants.INNER_STATE_BEAN_EXTENSION_QNAME)) {
- return true;
- }
- }
- return false;
- }
-
- private static RuntimeBeanEntry createHierarchical(final String packageName,
- final ListSchemaNode listSchemaNode,
- final TypeProviderWrapper typeProviderWrapper, final Module currentModule,
- final SchemaContext ctx) {
-
- // supported are numeric types, strings, enums
- // get all attributes
- AttributesRpcsAndRuntimeBeans attributesRpcsAndRuntimeBeans = extractSubtree(
- packageName, listSchemaNode, typeProviderWrapper,
- currentModule, ctx);
-
- Optional<String> keyYangName;
- if (listSchemaNode.getKeyDefinition().isEmpty()) {
- keyYangName = Optional.absent();
- } else if (listSchemaNode.getKeyDefinition().size() == 1) {
- // key must be either null or one of supported key types
- QName keyQName = listSchemaNode.getKeyDefinition().iterator()
- .next();
- keyYangName = Optional.of(keyQName.getLocalName());
-
- } else {
- throw new IllegalArgumentException(
- "More than one key is not supported in " + listSchemaNode);
- }
-
- String javaNamePrefix = TypeProviderWrapper
- .findJavaNamePrefix(listSchemaNode);
-
- RuntimeBeanEntry rbFromAttributes = new RuntimeBeanEntry(packageName,
- listSchemaNode, listSchemaNode.getQName().getLocalName(),
- javaNamePrefix, false, keyYangName,
- attributesRpcsAndRuntimeBeans.getAttributes(),
- attributesRpcsAndRuntimeBeans.getRuntimeBeanEntries(),
- attributesRpcsAndRuntimeBeans.getRpcs());
-
- return rbFromAttributes;
- }
-
- private static RuntimeBeanEntry createRoot(final String packageName,
- final DataNodeContainer nodeForReporting, final String attributeYangName,
- final List<AttributeIfc> attributes, final String javaNamePrefix,
- final List<RuntimeBeanEntry> children, final Set<Rpc> rpcs) {
- return new RuntimeBeanEntry(packageName, nodeForReporting,
- attributeYangName, javaNamePrefix, true,
- Optional.<String> absent(), attributes, children, rpcs);
- }
-
- public boolean isRoot() {
- return isRoot;
- }
-
- public Optional<String> getKeyYangName() {
- return keyYangName;
- }
-
- public Optional<String> getKeyJavaName() {
- return keyJavaName;
- }
-
- public Collection<AttributeIfc> getAttributes() {
- return attributeMap.values();
- }
-
- public Map<String, AttributeIfc> getYangPropertiesToTypesMap() {
- return attributeMap;
- }
-
- public String getYangName() {
- return yangName;
- }
-
- public String getPackageName() {
- return packageName;
- }
-
- public String getJavaNamePrefix() {
- return javaNamePrefix;
- }
-
- public List<RuntimeBeanEntry> getChildren() {
- return children;
- }
-
- public Set<Rpc> getRpcs() {
- return rpcs;
- }
-
- private static class AttributesRpcsAndRuntimeBeans {
- private final List<RuntimeBeanEntry> runtimeBeanEntries;
- private final List<AttributeIfc> attributes;
- private final Set<Rpc> rpcs;
-
- public AttributesRpcsAndRuntimeBeans(
- final List<RuntimeBeanEntry> runtimeBeanEntries,
- final List<AttributeIfc> attributes, final Set<Rpc> rpcs) {
- this.runtimeBeanEntries = runtimeBeanEntries;
- this.attributes = attributes;
- this.rpcs = rpcs;
- }
-
- private List<AttributeIfc> getAttributes() {
- return attributes;
- }
-
- public List<RuntimeBeanEntry> getRuntimeBeanEntries() {
- return runtimeBeanEntries;
- }
-
- public boolean isEmpty() {
- return attributes.isEmpty() && rpcs.isEmpty();
- }
-
- private Set<Rpc> getRpcs() {
- return rpcs;
- }
- }
-
- public static class Rpc {
- private final String name;
- private final List<JavaAttribute> parameters;
- private final AttributeIfc returnType;
- private final String yangName;
-
- Rpc(final AttributeIfc returnType, final String name, final String yangName,
- final List<JavaAttribute> parameters) {
- this.returnType = returnType;
- this.name = name;
- this.parameters = parameters;
- this.yangName = yangName;
- }
-
- public String getYangName() {
- return yangName;
- }
-
- public String getName() {
- return name;
- }
-
- public List<JavaAttribute> getParameters() {
- return parameters;
- }
-
- public AttributeIfc getReturnType() {
- return returnType;
- }
- }
-
- private static final String MXBEAN_SUFFIX = "RuntimeMXBean";
-
- public String getJavaNameOfRuntimeMXBean() {
- return getJavaNameOfRuntimeMXBean(javaNamePrefix);
- }
-
- public String getFullyQualifiedName(final String typeName) {
- return FullyQualifiedNameHelper.getFullyQualifiedName(packageName,
- typeName);
- }
-
- private static String getJavaNameOfRuntimeMXBean(final String javaNamePrefix) {
- return javaNamePrefix + MXBEAN_SUFFIX;
- }
-
- @Override
- public String toString() {
- return "RuntimeBeanEntry{" + "isRoot=" + isRoot + ", yangName='"
- + yangName + '\'' + ", packageName='" + packageName + '\''
- + ", keyYangName=" + keyYangName + '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static java.lang.String.format;
-import static org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants.SERVICE_TYPE_Q_NAME;
-
-import com.google.common.base.Optional;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Represents identity derived from {@link ConfigConstants#SERVICE_TYPE_Q_NAME}.
- * Example:
- * <p>
- * <blockquote>
- *
- * <pre>
- * identity eventbus {
- * description
- * "Service representing an event bus. The service acts as message
- * router between event producers and event consumers";
- *
- * base "config:service-type";
- * config:java-class "com.google.common.eventbus.EventBus";
- * }
- * </pre>
- *
- * </blockquote>
- */
-public class ServiceInterfaceEntry extends AbstractEntry {
- private static final Logger LOG = LoggerFactory
- .getLogger(ServiceInterfaceEntry.class);
-
- private static final String CLASS_NAME_SUFFIX = "ServiceInterface";
- private final Optional<ServiceInterfaceEntry> maybeBaseCache;
- private final String exportedOsgiClassName;
- private final QName qName;
- private final String nullableDescription, packageName, typeName;
- private final QName yangModuleQName;
- private final boolean registerToOsgi;
-
- private ServiceInterfaceEntry(final IdentitySchemaNode id, final String packageName, final QName yangModuleQName) {
- this(Optional.<ServiceInterfaceEntry> absent(), id, packageName, yangModuleQName);
- }
-
- private ServiceInterfaceEntry(final Optional<ServiceInterfaceEntry> base,
- final IdentitySchemaNode id, final String packageName, final QName yangModuleQName) {
- checkNotNull(base);
- this.maybeBaseCache = base;
- List<UnknownSchemaNode> unknownSchemaNodes = id.getUnknownSchemaNodes();
- List<String> exportedOsgiClassNames = new ArrayList<>(
- unknownSchemaNodes.size());
-
- boolean disableOsgiServiceRegistration = false;
- for (UnknownSchemaNode usn : unknownSchemaNodes) {
- if (ConfigConstants.JAVA_CLASS_EXTENSION_QNAME.equals(usn.getNodeType())) {
- String localName = usn.getNodeParameter();
- exportedOsgiClassNames.add(localName);
- } else if (ConfigConstants.DISABLE_OSGI_SERVICE_REG_QNAME.equals(usn.getNodeType())) {
- disableOsgiServiceRegistration = true;
- } else {
- throw new IllegalStateException(format(
- "Unexpected unknown schema node. Expected %s, got %s",
- ConfigConstants.JAVA_CLASS_EXTENSION_QNAME,
- usn.getNodeType()));
- }
- }
- if (exportedOsgiClassNames.size() != 1) {
- throw new IllegalArgumentException(
- format("Cannot find one to one mapping from %s to "
- + "java class defined by %s language extension in %s",
- getClass(),
- ConfigConstants.JAVA_CLASS_EXTENSION_QNAME, id));
- }
-
- this.registerToOsgi = !disableOsgiServiceRegistration;
- this.exportedOsgiClassName = exportedOsgiClassNames.get(0);
- qName = id.getQName();
- nullableDescription = id.getDescription().orElse(null);
- typeName = getSimpleName(exportedOsgiClassName) + CLASS_NAME_SUFFIX;
- this.packageName = packageName;
- this.yangModuleQName = yangModuleQName;
- }
-
- private static final String getSimpleName(final String fullyQualifiedName) {
- int lastDotPosition = fullyQualifiedName.lastIndexOf(".");
- return fullyQualifiedName.substring(lastDotPosition + 1);
- }
-
- public String getNullableDescription() {
- return nullableDescription;
- }
-
- public Optional<ServiceInterfaceEntry> getBase() {
- return maybeBaseCache;
- }
-
- public String getExportedOsgiClassName() {
- return exportedOsgiClassName;
- }
-
- public QName getQName() {
- return qName;
- }
-
- public boolean isRegisterToOsgi() {
- return registerToOsgi;
- }
-
- /**
- * @return Map of QNames as keys and ServiceInterfaceEntry instances as
- * values
- */
- public static Map<QName, ServiceInterfaceEntry> create(final Module currentModule,
- final String packageName,final Map<IdentitySchemaNode, ServiceInterfaceEntry> definedSEItracker) {
- LOG.debug("Generating ServiceInterfaces from {} to package {}",
- currentModule.getNamespace(), packageName);
-
- Map<IdentitySchemaNode, ServiceInterfaceEntry> identitiesToSIs = new HashMap<>();
- Set<IdentitySchemaNode> notVisited = new HashSet<>(
- currentModule.getIdentities());
- int lastSize = notVisited.size() + 1;
- while (!notVisited.isEmpty()) {
- if (notVisited.size() == lastSize) {
- LOG.debug(
- "Following identities will be ignored while generating ServiceInterfaces, as they are not derived from {} : {}",
- SERVICE_TYPE_Q_NAME, notVisited);
- break;
- }
- lastSize = notVisited.size();
- for (Iterator<IdentitySchemaNode> iterator = notVisited.iterator(); iterator
- .hasNext();) {
- IdentitySchemaNode identity = iterator.next();
- ServiceInterfaceEntry created = null;
- if (identity.getBaseIdentities().isEmpty()) {
- // this can happen while loading config module, just skip
- // the identity
- continue;
- } else if (identity.getBaseIdentities().iterator().next().getQName()
- .equals(SERVICE_TYPE_Q_NAME)) {
- // this is a base type
- created = new ServiceInterfaceEntry(identity, packageName, ModuleUtil.getQName(currentModule));
- } else {
- ServiceInterfaceEntry foundBase = definedSEItracker
- .get(identity.getBaseIdentities().iterator().next());
- // derived type, did we convert the parent?
- if (foundBase != null) {
- created = new ServiceInterfaceEntry(
- Optional.of(foundBase), identity, packageName, ModuleUtil.getQName(currentModule));
- }
- }
-
-
- if (created != null) {
- created.setYangModuleName(currentModule.getName());
- // TODO how to get local name
- created.setYangModuleLocalname(identity.getQName()
- .getLocalName());
- identitiesToSIs.put(identity, created);
- definedSEItracker.put(identity, created);
- iterator.remove();
- }
- }
- }
- // create result map
- Map<QName, ServiceInterfaceEntry> resultMap = new HashMap<>();
- for (ServiceInterfaceEntry sie : identitiesToSIs.values()) {
- resultMap.put(sie.getQName(), sie);
- }
- LOG.debug("Number of ServiceInterfaces to be generated: {}",
- resultMap.size());
- return resultMap;
- }
-
- public String getFullyQualifiedName() {
- return packageName + "." + typeName;
- }
-
- public String getPackageName() {
- return packageName;
- }
-
- public String getTypeName() {
- return typeName;
- }
-
- public QName getYangModuleQName() {
- return yangModuleQName;
- }
-
- @Override
- public boolean equals(final Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- ServiceInterfaceEntry that = (ServiceInterfaceEntry) o;
-
- if (!maybeBaseCache.equals(that.maybeBaseCache)) {
- return false;
- }
- if (!nullableDescription.equals(that.nullableDescription)) {
- return false;
- }
- if (!exportedOsgiClassName.equals(that.exportedOsgiClassName)) {
- return false;
- }
- if (!qName.equals(that.qName)) {
- return false;
- }
- if (!packageName.equals(that.packageName)) {
- return false;
- }
- if (!typeName.equals(that.typeName)) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = maybeBaseCache.hashCode();
- result = 31 * result + exportedOsgiClassName.hashCode();
- result = 31 * result + nullableDescription.hashCode();
- result = 31 * result + typeName.hashCode();
- result = 31 * result + packageName.hashCode();
- result = 31 * result + qName.hashCode();
- return result;
- }
-
- @Override
- public String toString() {
- return "ServiceInterfaceEntry{" + "maybeBaseCache=" + maybeBaseCache
- + ", qName='" + qName + '\'' + ", fullyQualifiedName='"
- + getFullyQualifiedName() + '\'' + ", exportedOsgiClassName="
- + exportedOsgiClassName + ", nullableDescription='"
- + nullableDescription + '\'' + '}';
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
-import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
-import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
-
-public class TypeProviderWrapper {
- private final TypeProvider typeProvider;
-
- public TypeProviderWrapper(final TypeProvider typeProvider) {
- this.typeProvider = typeProvider;
- }
-
- /**
- * For input node, find if it contains config:java-name-prefix extension. If
- * not found, convert local name of node converted to cammel case.
- */
- public static String findJavaNamePrefix(final SchemaNode schemaNode) {
- return convertToJavaName(schemaNode, true);
- }
-
- public static String findJavaParameter(final SchemaNode schemaNode) {
- return convertToJavaName(schemaNode, false);
- }
-
- public static String convertToJavaName(final SchemaNode schemaNode,
- final boolean capitalizeFirstLetter) {
- for (final UnknownSchemaNode unknownNode : schemaNode.getUnknownSchemaNodes()) {
- if (ConfigConstants.JAVA_NAME_PREFIX_EXTENSION_QNAME
- .equals(unknownNode.getNodeType())) {
- final String value = unknownNode.getNodeParameter();
- return convertToJavaName(value, capitalizeFirstLetter);
- }
- }
- return convertToJavaName(schemaNode.getQName().getLocalName(),
- capitalizeFirstLetter);
- }
-
- public static String convertToJavaName(final String localName,
- final boolean capitalizeFirstLetter) {
- if (capitalizeFirstLetter) {
- return BindingGeneratorUtil.parseToClassName(localName);
- } else {
- return BindingGeneratorUtil.parseToValidParamName(localName);
- }
- }
-
- public Type getType(final LeafSchemaNode leaf) {
- final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
- return getType(leaf, type);
- }
-
- public String getDefault(final LeafSchemaNode node) {
- return this.typeProvider.getTypeDefaultConstruction(node);
- }
-
- public Type getType(final SchemaNode leaf, final TypeDefinition<?> type) {
- Type javaType;
- try {
- javaType = this.typeProvider.javaTypeForSchemaDefinitionType(
- type, leaf);
- if (javaType == null) {
- throw new IllegalArgumentException("Unknown type received for "
- + leaf.toString());
- }
- } catch (final IllegalArgumentException e) {
- throw new IllegalArgumentException("Error while resolving type of "
- + leaf, e);
- }
- return javaType;
- }
-
- // there is no getType in common interface
- public Type getType(final LeafListSchemaNode leaf) {
- Type javaType;
- try {
- javaType = this.typeProvider.javaTypeForSchemaDefinitionType(
- leaf.getType(), leaf);
- if (javaType == null) {
- throw new IllegalArgumentException(
- "Unknown type received for " + leaf.toString());
- }
- } catch (final IllegalArgumentException e) {
- throw new IllegalArgumentException("Error while resolving type of "
- + leaf, e);
- }
- return javaType;
- }
-
- public String getJMXParamForBaseType(final TypeDefinition<?> baseType) {
- return this.typeProvider.getConstructorPropertyName(baseType);
- }
-
- public String getJMXParamForUnionInnerType(final TypeDefinition<?> unionInnerType) {
- return this.typeProvider.getParamNameFromType(unionInnerType);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-public abstract class AbstractAttribute implements AttributeIfc {
- private final String attributeYangName, upperCaseCammelCase,
- lowerCaseCammelCase;
- protected final DataSchemaNode node;
-
- private static String getLocalName(DataSchemaNode attrNode) {
- return attrNode.getQName().getLocalName();
- }
-
- AbstractAttribute(DataSchemaNode attrNode) {
- this.attributeYangName = getLocalName(attrNode);
- this.node = attrNode;
- this.upperCaseCammelCase = TypeProviderWrapper.findJavaNamePrefix(node);
- this.lowerCaseCammelCase = TypeProviderWrapper.findJavaParameter(node);
- }
-
- @Override
- public String getAttributeYangName() {
- return attributeYangName;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (!(o instanceof AbstractAttribute)) {
- return false;
- }
-
- AbstractAttribute that = (AbstractAttribute) o;
-
- if (attributeYangName != null ? !attributeYangName
- .equals(that.attributeYangName)
- : that.attributeYangName != null) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- return attributeYangName != null ? attributeYangName.hashCode() : 0;
- }
-
- /**
- *
- * @return Yang name converted to cammel case, starting with a capital
- * letter. For details see
- * {@link org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry#getJavaNamePrefix()}
- */
- @Override
- public String getUpperCaseCammelCase() {
- return upperCaseCammelCase;
- }
-
- public String getLowerCaseCammelCase() {
- return lowerCaseCammelCase;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-public abstract class AbstractDependencyAttribute extends AbstractAttribute implements TypedAttribute {
-
- protected final Dependency dependency;
- protected final String nullableDescription, nullableDefault;
-
- public AbstractDependencyAttribute(DataSchemaNode attrNode,
- ServiceInterfaceEntry sie, boolean mandatory,
- String nullableDescription) {
- super(attrNode);
- dependency = new Dependency(sie, mandatory);
- this.nullableDescription = nullableDescription;
- nullableDefault = null;
- }
-
- public Dependency getDependency() {
- return dependency;
- }
-
- @Override
- public String getNullableDescription() {
- return nullableDescription;
- }
-
- @Override
- public String getNullableDefault() {
- return nullableDefault;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- if (!super.equals(o)) {
- return false;
- }
-
- AbstractDependencyAttribute that = (AbstractDependencyAttribute) o;
-
- if (dependency != null ? !dependency.equals(that.dependency)
- : that.dependency != null) {
- return false;
- }
- if (nullableDefault != null ? !nullableDefault
- .equals(that.nullableDefault) : that.nullableDefault != null) {
- return false;
- }
- if (nullableDescription != null ? !nullableDescription
- .equals(that.nullableDescription)
- : that.nullableDescription != null) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = super.hashCode();
- result = 31 * result + (dependency != null ? dependency.hashCode() : 0);
- result = 31
- * result
- + (nullableDescription != null ? nullableDescription.hashCode()
- : 0);
- result = 31 * result
- + (nullableDefault != null ? nullableDefault.hashCode() : 0);
- return result;
- }
-
- @Override
- public String toString() {
- return getClass().getName() + "{" + getAttributeYangName() + ","
- + "dependency=" + dependency + '}';
- }
-
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import javax.management.openmbean.OpenType;
-
-public interface AttributeIfc {
-
- /**
- * Name of attribute, starting with low case
- */
- String getAttributeYangName();
-
- String getNullableDescription();
-
- String getNullableDefault();
-
- String getUpperCaseCammelCase();
-
- String getLowerCaseCammelCase();
-
- OpenType<?> getOpenType();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-
-public class Dependency {
- private final ServiceInterfaceEntry sie;
- private final boolean mandatory;
-
- public Dependency(ServiceInterfaceEntry sie, boolean mandatory) {
- this.sie = sie;
- this.mandatory = mandatory;
- }
-
- public ServiceInterfaceEntry getSie() {
- return sie;
- }
-
- public boolean isMandatory() {
- return mandatory;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- Dependency that = (Dependency) o;
-
- if (mandatory != that.mandatory) {
- return false;
- }
- if (!sie.equals(that.sie)) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = sie.hashCode();
- result = 31 * result + (mandatory ? 1 : 0);
- return result;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import javax.management.ObjectName;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.mdsal.binding.model.util.Types;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-public class DependencyAttribute extends AbstractDependencyAttribute {
-
-
- public DependencyAttribute(final DataSchemaNode attrNode,
- final ServiceInterfaceEntry sie, final boolean mandatory,
- final String nullableDescription) {
- super(attrNode, sie, mandatory, nullableDescription);
- }
-
- @Override
- public Type getType() {
- return Types.typeForClass(ObjectName.class);
- }
-
- @Override
- public SimpleType<?> getOpenType() {
- return SimpleType.OBJECTNAME;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import com.google.common.base.Preconditions;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.api.IdentityAttributeRef;
-import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
-import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
-
-public class JavaAttribute extends AbstractAttribute implements TypedAttribute {
-
- public static final String DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION = "valueOfArtificialUnionProperty";
-
- private final Type type;
- private final String nullableDescription, nullableDefault, nullableDefaultWrappedForCode;
- private final TypeProviderWrapper typeProviderWrapper;
- private final TypeDefinition<?> typeDefinition;
-
- public JavaAttribute(final LeafSchemaNode leaf,
- final TypeProviderWrapper typeProviderWrapper) {
- super(leaf);
- this.type = typeProviderWrapper.getType(leaf);
-
- this.typeDefinition = CompatUtils.compatLeafType(leaf);
- this.typeProviderWrapper = typeProviderWrapper;
-
- final Optional<? extends Object> typeDefault = leaf.getType().getDefaultValue();
- if (typeDefault.isPresent()) {
- nullableDefault = (String) typeDefault.get();
- nullableDefaultWrappedForCode = typeProviderWrapper.getDefault(leaf);
- } else {
- nullableDefault = null;
- nullableDefaultWrappedForCode = null;
- }
-
- this.nullableDescription = leaf.getDescription().orElse(null);
- }
-
- public JavaAttribute(final LeafListSchemaNode leaf,
- final TypeProviderWrapper typeProviderWrapper) {
- super(leaf);
- this.type = typeProviderWrapper.getType(leaf);
- this.typeDefinition = leaf.getType();
- this.typeProviderWrapper = typeProviderWrapper;
- this.nullableDefault = this.nullableDefaultWrappedForCode = null;
- this.nullableDescription = leaf.getDescription().orElse(null);
- }
-
- public boolean isUnion() {
- final TypeDefinition<?> base = getBaseType(this.typeProviderWrapper, this.typeDefinition);
- return base instanceof UnionTypeDefinition;
- }
-
- public boolean isEnum() {
- final TypeDefinition<?> base = getBaseType(this.typeProviderWrapper, this.typeDefinition);
- return base instanceof EnumTypeDefinition;
- }
-
- public TypeDefinition<?> getTypeDefinition() {
- return this.typeDefinition;
- }
-
- /**
- * Returns the most base type
- */
- private TypeDefinition<?> getBaseType(final TypeProviderWrapper typeProviderWrapper, TypeDefinition<?> baseType) {
- while(baseType.getBaseType()!=null) {
- baseType = baseType.getBaseType();
- }
- return baseType;
- }
-
- public String getNullableDefaultWrappedForCode() {
- return this.nullableDefaultWrappedForCode;
- }
-
- @Override
- public Type getType() {
- return this.type;
- }
-
- @Override
- public String getNullableDescription() {
- return this.nullableDescription;
- }
-
- @Override
- public String getNullableDefault() {
- return this.nullableDefault;
- }
-
- @Override
- public boolean equals(final Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- if (!super.equals(o)) {
- return false;
- }
-
- final JavaAttribute that = (JavaAttribute) o;
-
- if (this.nullableDefault != null ? !this.nullableDefault
- .equals(that.nullableDefault) : that.nullableDefault != null) {
- return false;
- }
- if (this.nullableDescription != null ? !this.nullableDescription
- .equals(that.nullableDescription)
- : that.nullableDescription != null) {
- return false;
- }
- if (this.type != null ? !this.type.equals(that.type) : that.type != null) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = super.hashCode();
- result = 31 * result + (this.type != null ? this.type.hashCode() : 0);
- result = 31
- * result
- + (this.nullableDescription != null ? this.nullableDescription.hashCode()
- : 0);
- result = 31 * result
- + (this.nullableDefault != null ? this.nullableDefault.hashCode() : 0);
- return result;
- }
-
- @Override
- public String toString() {
- return "JavaAttribute{" + getAttributeYangName() + "," + "type=" + this.type
- + '}';
- }
-
- @Override
- public OpenType<?> getOpenType() {
- final TypeDefinition<?> baseTypeDefinition = getBaseType(this.typeProviderWrapper, this.typeDefinition);
- final Type baseType = this.typeProviderWrapper.getType(baseTypeDefinition, baseTypeDefinition);
-
- if (isArray()) {
- return getArrayType();
- } else if (isEnum()) {
- return getEnumType(baseTypeDefinition);
- } else if (isUnion()) {
- return getCompositeTypeForUnion(baseTypeDefinition);
- } else if (isDerivedType(baseType, getType())) {
- return getCompositeType(baseType, baseTypeDefinition);
- } else if (isIdentityRef()) {
- return getCompositeTypeForIdentity();
- }
-
- return getSimpleType(getType());
- }
-
- private OpenType<?> getEnumType(final TypeDefinition<?> baseType) {
- final String fullyQualifiedName = this.typeProviderWrapper.getType(this.node, getTypeDefinition()).getFullyQualifiedName();
- final String[] items = {"instance"};
- final String description = getNullableDescription() == null ? getAttributeYangName() : getNullableDescription();
-
- try {
- return new CompositeType(fullyQualifiedName, description, items, items, new OpenType[]{SimpleType.STRING});
- } catch (final OpenDataException e) {
- throw new RuntimeException("Unable to create enum type" + fullyQualifiedName + " as open type", e);
- }
- }
-
- public boolean isIdentityRef() {
- return this.typeDefinition instanceof IdentityrefTypeDefinition;
- }
-
- private OpenType<?> getCompositeTypeForUnion(final TypeDefinition<?> baseTypeDefinition) {
- Preconditions.checkArgument(baseTypeDefinition instanceof UnionTypeDefinition,
- "Expected %s instance but was %s", UnionTypeDefinition.class, baseTypeDefinition);
-
- final List<TypeDefinition<?>> types = ((UnionTypeDefinition) baseTypeDefinition).getTypes();
-
- final String[] itemNames = new String[types.size()+1];
- final OpenType<?>[] itemTypes = new OpenType[itemNames.length];
-
- addArtificialPropertyToUnionCompositeType(baseTypeDefinition, itemNames, itemTypes);
-
- final String description = getNullableDescription() == null ? getAttributeYangName() : getNullableDescription();
-
- int i = 1;
- for (final TypeDefinition<?> innerTypeDefinition : types) {
-
- final Type innerType = this.typeProviderWrapper.getType(innerTypeDefinition, innerTypeDefinition);
-
- final TypeDefinition<?> baseInnerTypeDefinition = getBaseType(this.typeProviderWrapper, innerTypeDefinition);
- final Type innerTypeBaseType = this.typeProviderWrapper.getType(baseInnerTypeDefinition, baseInnerTypeDefinition);
-
- OpenType<?> innerCompositeType;
-
- if(isDerivedType(innerTypeBaseType, innerType)) {
- innerCompositeType = baseInnerTypeDefinition instanceof UnionTypeDefinition ?
- getCompositeTypeForUnion(baseInnerTypeDefinition) :
- getCompositeType(innerTypeBaseType, baseInnerTypeDefinition);
- } else {
- innerCompositeType = SimpleTypeResolver.getSimpleType(innerType);
- }
-
- itemNames[i] = this.typeProviderWrapper.getJMXParamForUnionInnerType(innerTypeDefinition);
- itemTypes[i++] = innerCompositeType;
- }
-
- final String[] descriptions = itemNames.clone();
- descriptions[0] = DESCRIPTION_OF_VALUE_ATTRIBUTE_FOR_UNION;
-
- try {
- return new CompositeType(getUpperCaseCammelCase(), description, itemNames, descriptions, itemTypes);
- } catch (final OpenDataException e) {
- throw new RuntimeException("Unable to create " + CompositeType.class + " with inner elements "
- + Arrays.toString(itemTypes), e);
- }
- }
-
- public static final Class<Character> TYPE_OF_ARTIFICIAL_UNION_PROPERTY = char.class;
-
- private void addArtificialPropertyToUnionCompositeType(final TypeDefinition<?> baseTypeDefinition, final String[] itemNames, final OpenType<?>[] itemTypes) {
- final String artificialPropertyName = this.typeProviderWrapper.getJMXParamForBaseType(baseTypeDefinition);
- itemNames[0] = artificialPropertyName;
-
- final OpenType<?> artificialPropertyType = getArrayOpenTypeForSimpleType(TYPE_OF_ARTIFICIAL_UNION_PROPERTY.getName(),
- SimpleTypeResolver.getSimpleType(TYPE_OF_ARTIFICIAL_UNION_PROPERTY.getName()));
- itemTypes[0] = artificialPropertyType;
- }
-
- private OpenType<?> getSimpleType(final Type type) {
- final SimpleType<?> simpleType = SimpleTypeResolver.getSimpleType(type);
- return simpleType;
- }
-
- private OpenType<?> getCompositeType(final Type baseType, final TypeDefinition<?> baseTypeDefinition) {
-
- final SimpleType<?> innerItemType = SimpleTypeResolver.getSimpleType(baseType);
- final String innerItemName = this.typeProviderWrapper.getJMXParamForBaseType(baseTypeDefinition);
-
- final String[] itemNames = new String[]{innerItemName};
- final String description = getNullableDescription() == null ? getAttributeYangName() : getNullableDescription();
-
- final OpenType<?>[] itemTypes = new OpenType[]{innerItemType};
- try {
- return new CompositeType(getUpperCaseCammelCase(), description, itemNames, itemNames, itemTypes);
- } catch (final OpenDataException e) {
- throw new RuntimeException("Unable to create " + CompositeType.class + " with inner element of type "
- + itemTypes, e);
- }
- }
-
- public OpenType<?> getCompositeTypeForIdentity() {
- final String[] itemNames = new String[]{IdentityAttributeRef.QNAME_ATTR_NAME};
- final String description = getNullableDescription() == null ? getAttributeYangName() : getNullableDescription();
- final OpenType<?>[] itemTypes = new OpenType[]{SimpleType.STRING};
-
- try {
- return new CompositeType(getUpperCaseCammelCase(), description, itemNames, itemNames, itemTypes);
- } catch (final OpenDataException e) {
- throw new RuntimeException("Unable to create " + CompositeType.class + " with inner element of type "
- + itemTypes, e);
- }
- }
-
- private OpenType<?> getArrayType() {
- final String innerTypeFullyQName = getInnerType(getType());
- final SimpleType<?> innerSimpleType = SimpleTypeResolver.getSimpleType(innerTypeFullyQName);
- return getArrayOpenTypeForSimpleType(innerTypeFullyQName, innerSimpleType);
- }
-
- private OpenType<?> getArrayOpenTypeForSimpleType(final String innerTypeFullyQName, final SimpleType<?> innerSimpleType) {
- try {
- final ArrayType<Object> arrayType = isPrimitive(innerTypeFullyQName) ? new ArrayType<>(innerSimpleType, true)
- : new ArrayType<>(1, innerSimpleType);
- return arrayType;
- } catch (final OpenDataException e) {
- throw new RuntimeException("Unable to create " + ArrayType.class + " with inner element of type "
- + innerSimpleType, e);
- }
- }
-
- // TODO verify
- private boolean isPrimitive(final String innerTypeFullyQName) {
- if (innerTypeFullyQName.contains(".")) {
- return false;
- }
-
- return true;
- }
-
- private boolean isArray() {
- return this.type.getName().endsWith("[]");
- }
-
- private boolean isDerivedType(final Type baseType, final Type currentType) {
- return baseType.equals(currentType) == false;
- }
-
- private static String getInnerType(final Type type) {
- final String fullyQualifiedName = type.getFullyQualifiedName();
- return fullyQualifiedName.substring(0, fullyQualifiedName.length() - 2);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import java.util.List;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
-import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.mdsal.binding.model.util.Types;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-public class ListAttribute extends AbstractAttribute implements TypedAttribute {
-
- private final String nullableDescription, nullableDefault;
- private final TypedAttribute innerAttribute;
-
- public static ListAttribute create(final ListSchemaNode node,
- final TypeProviderWrapper typeProvider, final String packageName) {
-
- final TOAttribute innerAttribute = TOAttribute.create(node, typeProvider, packageName);
-
- return new ListAttribute(node, innerAttribute, node.getDescription().orElse(null));
- }
-
- public static ListAttribute create(final LeafListSchemaNode node,
- final TypeProviderWrapper typeProvider) {
-
- final JavaAttribute innerAttribute = new JavaAttribute(node, typeProvider);
-
- return new ListAttribute(node, innerAttribute, node.getDescription().orElse(null));
- }
-
- ListAttribute(final DataSchemaNode attrNode, final TypedAttribute innerAttribute,
- final String description) {
- super(attrNode);
- this.nullableDescription = description;
- this.innerAttribute = innerAttribute;
- this.nullableDefault = null;
- }
-
- @Override
- public String getNullableDescription() {
- return this.nullableDescription;
- }
-
- @Override
- public String getNullableDefault() {
- return this.nullableDefault;
- }
-
- public AttributeIfc getInnerAttribute() {
- return this.innerAttribute;
- }
-
- @Override
- public String toString() {
- return "ListAttribute{" + getAttributeYangName() + "," + "to="
- + this.innerAttribute + '}';
- }
-
- @Override
- public int hashCode() {
- int result = super.hashCode();
- result = 31
- * result
- + (this.nullableDescription != null ? this.nullableDescription.hashCode()
- : 0);
- result = 31 * result
- + (this.nullableDefault != null ? this.nullableDefault.hashCode() : 0);
- return result;
- }
-
- @Override
- public boolean equals(final Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- if (!super.equals(o)) {
- return false;
- }
-
- final ListAttribute that = (ListAttribute) o;
-
- if (this.nullableDefault != null ? !this.nullableDefault
- .equals(that.nullableDefault) : that.nullableDefault != null) {
- return false;
- }
- if (this.nullableDescription != null ? !this.nullableDescription
- .equals(that.nullableDescription)
- : that.nullableDescription != null) {
- return false;
- }
-
- return true;
- }
-
-
- @Override
- public Type getType() {
- return Types.parameterizedTypeFor(Types.typeForClass(List.class), this.innerAttribute.getType());
- }
-
- @Override
- public ArrayType<?> getOpenType() {
- final OpenType<?> innerOpenType = this.innerAttribute.getOpenType();
- return constructArrayType(innerOpenType);
- }
-
- static ArrayType<?> constructArrayType(final OpenType<?> innerOpenType){
- try {
- return new ArrayType<>(1, innerOpenType);
- } catch (final OpenDataException e) {
- throw new RuntimeException("Unable to create " + ArrayType.class
- + " with inner element of type " + innerOpenType, e);
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import java.util.List;
-import javax.management.ObjectName;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
-import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.mdsal.binding.model.util.Types;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-public class ListDependenciesAttribute extends AbstractDependencyAttribute {
-
- public ListDependenciesAttribute(final DataSchemaNode attrNode, final ServiceInterfaceEntry sie, final boolean mandatory, final String nullableDescription) {
- super(attrNode, sie, mandatory, nullableDescription);
- }
-
- @Override
- public Type getType() {
- return Types.parameterizedTypeFor(Types.typeForClass(List.class), Types.typeForClass(ObjectName.class));
- }
-
- @Override
- public ArrayType<?> getOpenType() {
- final OpenType<?> innerOpenType = SimpleType.OBJECTNAME;
- return ListAttribute.constructArrayType(innerOpenType);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.Date;
-import java.util.Map;
-import javax.management.openmbean.SimpleType;
-import org.opendaylight.mdsal.binding.model.api.Type;
-
-public class SimpleTypeResolver {
-
- private SimpleTypeResolver() {
- }
-
- public static SimpleType<?> getSimpleType(final Type type) {
- final SimpleType<?> expectedSimpleType = JAVA_TYPE_TO_SIMPLE_TYPE.get(type
- .getFullyQualifiedName());
- Preconditions.checkState(expectedSimpleType != null,
- "Cannot find simple type for " + type.getFullyQualifiedName());
- return expectedSimpleType;
- }
-
- public static boolean canResolve(final Type type) {
- return JAVA_TYPE_TO_SIMPLE_TYPE.containsKey(type.getFullyQualifiedName());
- }
-
- public static SimpleType<?> getSimpleType(final String fullyQualifiedName) {
- final SimpleType<?> expectedSimpleType = JAVA_TYPE_TO_SIMPLE_TYPE
- .get(fullyQualifiedName);
- Preconditions.checkState(expectedSimpleType != null,
- "Cannot find simple type for " + fullyQualifiedName);
- return expectedSimpleType;
- }
-
- private static final Map<String, SimpleType<?>> JAVA_TYPE_TO_SIMPLE_TYPE = Maps.newHashMap();
- static {
- // TODO add all
- JAVA_TYPE_TO_SIMPLE_TYPE.put(Integer.class.getName(), SimpleType.INTEGER);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(int.class.getName(), SimpleType.INTEGER);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(Short.class.getName(), SimpleType.SHORT);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(short.class.getName(), SimpleType.SHORT);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(Long.class.getName(), SimpleType.LONG);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(long.class.getName(), SimpleType.LONG);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(String.class.getName(), SimpleType.STRING);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(Boolean.class.getName(), SimpleType.BOOLEAN);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(boolean.class.getName(), SimpleType.BOOLEAN);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(BigInteger.class.getName(), SimpleType.BIGINTEGER);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(BigDecimal.class.getName(), SimpleType.BIGDECIMAL);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(Byte.class.getName(), SimpleType.BYTE);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(byte.class.getName(), SimpleType.BYTE);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(Date.class.getName(), SimpleType.DATE);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(Double.class.getName(), SimpleType.DOUBLE);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(double.class.getName(), SimpleType.DOUBLE);
- JAVA_TYPE_TO_SIMPLE_TYPE.put(char.class.getName(), SimpleType.CHARACTER);
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import com.google.common.base.Function;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
-import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
-import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
-import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-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.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-public class TOAttribute extends AbstractAttribute implements TypedAttribute {
-
- private final String nullableDescription, nullableDefault;
- private final Map<String, AttributeIfc> yangNameToAttributeMap;
- private final Map<String, String> attributeNameMap;
- private final String packageName;
-
- private static final Set<Class<? extends DataSchemaNode>> ALLOWED_CHILDREN = Sets
- .newHashSet();
- static {
- ALLOWED_CHILDREN.add(LeafListSchemaNode.class);
- ALLOWED_CHILDREN.add(ListSchemaNode.class);
- ALLOWED_CHILDREN.add(LeafSchemaNode.class);
- ALLOWED_CHILDREN.add(ContainerSchemaNode.class);
- }
-
- public static <T extends DataNodeContainer & AugmentationTarget & DataSchemaNode> TOAttribute create(
- final T containerSchemaNode, final TypeProviderWrapper typeProviderWrapper, final String packageName) {
- // Transfer Object: get the leaves
- final Map<String, AttributeIfc> map = new HashMap<>();
- final Map<String, String> attributeNameMap = new HashMap<>();
- for (final DataSchemaNode dataSchemaNode : containerSchemaNode.getChildNodes()) {
- try {
- final String yangName = dataSchemaNode.getQName().getLocalName();
- map.put(yangName, createInnerAttribute(dataSchemaNode, typeProviderWrapper, packageName));
- } catch (final IllegalArgumentException e) {
- throw new IllegalStateException("Unable to create TO", e);
- }
- }
- return new TOAttribute(containerSchemaNode, map, attributeNameMap,
- containerSchemaNode.getDescription().orElse(null), packageName);
- }
-
- private static AttributeIfc createInnerAttribute(
- final DataSchemaNode dataSchemaNode,
- final TypeProviderWrapper typeProviderWrapper, final String packageName) {
- final Class<? extends DataSchemaNode> type = isAllowedType(dataSchemaNode);
-
- if (type.equals(LeafSchemaNode.class)) {
- return new JavaAttribute((LeafSchemaNode) dataSchemaNode, typeProviderWrapper);
- } else if (type.equals(ListSchemaNode.class)) {
- return ListAttribute.create((ListSchemaNode) dataSchemaNode, typeProviderWrapper, packageName);
- } else if (type.equals(LeafListSchemaNode.class)) {
- return ListAttribute.create((LeafListSchemaNode) dataSchemaNode, typeProviderWrapper);
- } else if (type.equals(ContainerSchemaNode.class)) {
- return TOAttribute.create((ContainerSchemaNode) dataSchemaNode, typeProviderWrapper, packageName);
- }
-
- throw new IllegalStateException("This should never happen");
- }
-
- private static Class<? extends DataSchemaNode> isAllowedType(
- final DataSchemaNode dataSchemaNode) {
- for (final Class<? extends DataSchemaNode> allowedType : ALLOWED_CHILDREN) {
- if (allowedType.isAssignableFrom(dataSchemaNode.getClass())) {
- return allowedType;
- }
- }
- throw new IllegalArgumentException("Illegal child node for TO: "
- + dataSchemaNode.getClass() + " allowed node types: "
- + ALLOWED_CHILDREN);
- }
-
- private TOAttribute(final DataSchemaNode attrNode,
- final Map<String, AttributeIfc> transferObject,
- final Map<String, String> attributeNameMap, final String nullableDescription, final String packageName) {
- super(attrNode);
- this.yangNameToAttributeMap = transferObject;
- this.attributeNameMap = attributeNameMap;
- this.nullableDescription = nullableDescription;
- this.nullableDefault = null;
- this.packageName = packageName;
- }
-
- public Map<String, String> getAttributeNameMap() {
- return this.attributeNameMap;
- }
-
- public Map<String, AttributeIfc> getCapitalizedPropertiesToTypesMap() {
- final Map<String, AttributeIfc> capitalizedPropertiesToTypesMap = Maps
- .newHashMap();
- for (final Entry<String, AttributeIfc> entry : this.yangNameToAttributeMap
- .entrySet()) {
-
- capitalizedPropertiesToTypesMap.put(
- TypeProviderWrapper.convertToJavaName(entry.getKey(), true),
- entry.getValue());
- }
- return capitalizedPropertiesToTypesMap;
- }
-
- public Map<String, AttributeIfc> getJmxPropertiesToTypesMap() {
- final Map<String, AttributeIfc> jmxPropertiesToTypesMap = Maps.newHashMap();
- for (final Entry<String, AttributeIfc> entry : this.yangNameToAttributeMap
- .entrySet()) {
-
- jmxPropertiesToTypesMap.put(
- TypeProviderWrapper.convertToJavaName(entry.getKey(), false),
- entry.getValue());
- }
- return jmxPropertiesToTypesMap;
- }
-
- public Map<String, AttributeIfc> getYangPropertiesToTypesMap() {
- return this.yangNameToAttributeMap;
- }
-
- @Override
- public String getNullableDescription() {
- return this.nullableDescription;
- }
-
- @Override
- public String getNullableDefault() {
- return this.nullableDefault;
- }
-
- @Override
- public boolean equals(final Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- if (!super.equals(o)) {
- return false;
- }
-
- final TOAttribute that = (TOAttribute) o;
-
- if (this.nullableDefault != null ? !this.nullableDefault
- .equals(that.nullableDefault) : that.nullableDefault != null) {
- return false;
- }
- if (this.nullableDescription != null ? !this.nullableDescription
- .equals(that.nullableDescription)
- : that.nullableDescription != null) {
- return false;
- }
- if (this.yangNameToAttributeMap != null ? !this.yangNameToAttributeMap
- .equals(that.yangNameToAttributeMap)
- : that.yangNameToAttributeMap != null) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = super.hashCode();
- result = 31
- * result
- + (this.nullableDescription != null ? this.nullableDescription.hashCode()
- : 0);
- result = 31 * result
- + (this.nullableDefault != null ? this.nullableDefault.hashCode() : 0);
- result = 31
- * result
- + (this.yangNameToAttributeMap != null ? this.yangNameToAttributeMap
- .hashCode() : 0);
- return result;
- }
-
- @Override
- public String toString() {
- return "TOAttribute{" + getAttributeYangName() + "," + "to="
- + this.yangNameToAttributeMap + '}';
- }
-
- @Override
- public Type getType() {
- // TODO: ReferencedTypeImpl from Types
- return new ReferencedTypeImpl(JavaTypeName.create(this.packageName, getUpperCaseCammelCase()));
- }
-
- @Override
- public CompositeType getOpenType() {
- final String description = getNullableDescription() == null ? getAttributeYangName() : getNullableDescription();
-
- final FunctionImpl functionImpl = new FunctionImpl();
- final Map<String, AttributeIfc> jmxPropertiesToTypesMap = getJmxPropertiesToTypesMap();
- final OpenType<?>[] itemTypes = Collections2.transform(
- jmxPropertiesToTypesMap.entrySet(), functionImpl).toArray(
- new OpenType<?>[] {});
- final String[] itemNames = functionImpl.getItemNames();
- try {
- // TODO add package name to create fully qualified name for this
- // type
- final CompositeType compositeType = new CompositeType(
- getUpperCaseCammelCase(), description, itemNames,
- itemNames, itemTypes);
- return compositeType;
- } catch (final OpenDataException e) {
- throw new RuntimeException("Unable to create CompositeType for "
- + this, e);
- }
- }
-
- public String getPackageName() {
- return this.packageName;
- }
-
-}
-
-class FunctionImpl implements
- Function<Entry<String, AttributeIfc>, OpenType<?>> {
- private final List<String> itemNames = new ArrayList<>();
-
- @Override
- public OpenType<?> apply(final Entry<String, AttributeIfc> input) {
- final AttributeIfc innerType = input.getValue();
- this.itemNames.add(input.getKey());
- return innerType.getOpenType();
- }
-
- public String[] getItemNames(){
- return this.itemNames.toArray(new String[this.itemNames.size()]);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import org.opendaylight.mdsal.binding.model.api.Type;
-
-public interface TypedAttribute extends AttributeIfc {
-
- Type getType();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-final class Util {
-
- private Util() {
- }
- /**
- * Used for date <-> xml serialization
- */
- private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
- "yyyy-MM-dd");
-
- public static String writeDate(Date date) {
- return DATE_FORMAT.format(date);
- }
-
- public static Date readDate(String s) throws ParseException {
- return DATE_FORMAT.parse(s);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.attribute;
-
-import javax.management.openmbean.OpenType;
-
-public class VoidAttribute implements AttributeIfc {
-
- private static VoidAttribute instance = new VoidAttribute();
-
- public static VoidAttribute getInstance() {
- return instance;
- }
-
- private VoidAttribute() {
- }
-
- @Override
- public String getAttributeYangName() {
- return null;
- }
-
- @Override
- public String getNullableDescription() {
- return null;
- }
-
- @Override
- public String getNullableDefault() {
- return null;
- }
-
- @Override
- public String getUpperCaseCammelCase() {
- return null;
- }
-
- @Override
- public String getLowerCaseCammelCase() {
- return null;
- }
-
- @Override
- public OpenType<?> getOpenType() {
- return null;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
-
-public class FullyQualifiedNameHelper {
-
- private FullyQualifiedNameHelper() {
- }
-
- public static String getFullyQualifiedName(String packageName,
- String className) {
- if (packageName.isEmpty()) {
- return className;
- }
- return packageName + "." + className;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
-
-import org.opendaylight.yangtools.yang.common.QName;
-
-public class NameConflictException extends RuntimeException {
- private static final long serialVersionUID = 1L;
- private static final String messageBlueprint = "Name conflict for name: %s, first defined in: %s, then defined in: %s";
- private final String conflictingName;
- private final QName secondParentQName;
- private final QName firstParentQName;
-
- public NameConflictException(String conflictingName,
- QName firstDefinedParentQName, QName secondDefinedParentQName) {
- super(String.format(messageBlueprint, conflictingName,
- firstDefinedParentQName, secondDefinedParentQName));
- this.conflictingName = conflictingName;
- this.firstParentQName = firstDefinedParentQName;
- this.secondParentQName = secondDefinedParentQName;
- }
-
- // TODO add yang local names
-
- public String getConflictingName() {
- return conflictingName;
- }
-
- public QName getSecondParentQName() {
- return secondParentQName;
- }
-
- public QName getFirstParentQName() {
- return firstParentQName;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Sets;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import org.junit.Assert;
-import org.junit.Before;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.YangModelSearchUtils;
-import org.opendaylight.mdsal.binding.yang.types.TypeProviderImpl;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-
-public abstract class AbstractYangTest {
- protected SchemaContext context;
- protected Map<String, Module> namesToModules; // are module names globally
- // unique?
- protected Module configModule, rpcContextModule, threadsModule,
- threadsJavaModule, bgpListenerJavaModule, ietfInetTypesModule,
- jmxModule, jmxImplModule, testFilesModule, testFiles1Module;
-
- public static final String EVENTBUS_MXB_NAME = "eventbus";
- public static final String ASYNC_EVENTBUS_MXB_NAME = "async-eventbus";
- public static final String THREADFACTORY_NAMING_MXB_NAME = "threadfactory-naming";
- public static final String THREADPOOL_DYNAMIC_MXB_NAME = "threadpool-dynamic";
- public static final String THREADPOOL_REGISTRY_IMPL_NAME = "threadpool-registry-impl";
-
- public static final String BGP_LISTENER_IMPL_MXB_NAME = "bgp-listener-impl";
-
- @Before
- public void loadYangFiles() throws Exception {
- final List<String> yangResources = new ArrayList<>();
- yangResources.add("/test-config-threads.yang");
- yangResources.add("/test-config-threads-java.yang");
- yangResources.add("/config-bgp-listener-impl.yang");
- yangResources.add("/ietf-inet-types.yang");
- yangResources.add("/config-jmx-it.yang");
- yangResources.add("/config-jmx-it-impl.yang");
- yangResources.add("/test-config-files.yang");
- yangResources.add("/test-config-files1.yang");
-
- yangResources.addAll(getConfigApiYangs());
-
- this.context = YangParserTestUtils.parseYangResources(AbstractYangTest.class, yangResources);
-
- this.namesToModules = YangModelSearchUtils.mapModulesByNames(this.context
- .getModules());
- this.configModule = this.namesToModules.get(ConfigConstants.CONFIG_MODULE);
- this.rpcContextModule = this.namesToModules.get(ConfigConstants.CONFIG_MODULE);
- this.threadsModule = this.namesToModules
- .get(ConfigConstants.CONFIG_THREADS_MODULE);
- this.threadsJavaModule = this.namesToModules.get("config-threads-java");
- this.bgpListenerJavaModule = this.namesToModules.get("config-bgp-listener-impl");
- this.ietfInetTypesModule = this.namesToModules
- .get(ConfigConstants.IETF_INET_TYPES);
- this.jmxModule = this.namesToModules.get("config-jmx-it");
- this.jmxImplModule = this.namesToModules.get("config-jmx-it-impl");
- this.testFilesModule = this.namesToModules.get("test-config-files");
- this.testFiles1Module = this.namesToModules.get("test-config-files1");
- }
-
- public static List<String> getConfigApiYangs() {
- return ImmutableList.of("/META-INF/yang/config@2013-04-05.yang", "/META-INF/yang/rpc-context@2013-06-17.yang");
- }
-
- public Map<QName, IdentitySchemaNode> mapIdentitiesByQNames(final Module module) {
- final Map<QName, IdentitySchemaNode> result = new HashMap<>();
- for (final IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
- final QName qName = identitySchemaNode.getQName();
- Preconditions.checkArgument(
- result.containsKey(qName) == false,
- "Two identities of %s contain same qname %s",
- module, qName);
- result.put(qName, identitySchemaNode);
- }
- return result;
- }
-
- protected static List<InputStream> getStreams(final String... paths) {
- final List<InputStream> result = new ArrayList<>();
- for (final String path : paths) {
- final InputStream is = AbstractYangTest.class.getResourceAsStream(path);
- assertNotNull(path + " is null", is);
- result.add(is);
- }
- return result;
- }
-
- protected Map<QName, ServiceInterfaceEntry> loadThreadsServiceInterfaceEntries(final String packageName) {
- final Map<IdentitySchemaNode, ServiceInterfaceEntry> identitiesToSIs = new HashMap<>();
- return ServiceInterfaceEntry.create(this.threadsModule, packageName,identitiesToSIs);
- }
-
- protected Map<String /* identity local name */, ModuleMXBeanEntry> loadThreadsJava(
- final Map<QName, ServiceInterfaceEntry> modulesToSIEs, final String packageName) {
- final Map<String /* identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
- .create(this.threadsJavaModule, modulesToSIEs, this.context, new TypeProviderWrapper(new TypeProviderImpl
- (this.context)), packageName);
- Assert.assertNotNull(namesToMBEs);
- final Set<String> expectedMXBeanNames = Sets.newHashSet(EVENTBUS_MXB_NAME,
- ASYNC_EVENTBUS_MXB_NAME, THREADFACTORY_NAMING_MXB_NAME,
- THREADPOOL_DYNAMIC_MXB_NAME, THREADPOOL_REGISTRY_IMPL_NAME);
- assertThat(namesToMBEs.keySet(), is(expectedMXBeanNames));
- return namesToMBEs;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.NameConflictException;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.YangModelSearchUtils;
-import org.opendaylight.mdsal.binding.yang.types.TypeProviderImpl;
-import org.opendaylight.yangtools.yang.common.YangConstants;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ModuleMXBeanEntryNameConflictTest extends AbstractYangTest {
-
- private static final Logger LOG = LoggerFactory.getLogger(ModuleMXBeanEntryNameConflictTest.class);
-
- public static final String PACKAGE_NAME = "pack2";
-
- private final List<String> testedModules = ImmutableList.of(
- "config-test-duplicate-attribute-in-list",
- "config-test-duplicate-attribute-in-runtime-and-mxbean",
- "config-test-duplicate-attribute-runtime-bean",
- "config-test-duplicate-attribute",
- "config-test-generated-attributes-name-conflict",
- "config-test-runtime-bean-list-name-conflict2",
- "config-test-runtime-bean-list-name-conflict",
- "config-test-runtime-bean-name-conflict2",
- "config-test-runtime-bean-name-conflict");
- private final Map<String, String> testedYangModulesToExpectedConflictingName = new HashMap<>();
-
- @Before
- public void setup() {
- testedYangModulesToExpectedConflictingName.put("config-test-duplicate-attribute", "DtoA");
- testedYangModulesToExpectedConflictingName.put("config-test-duplicate-attribute-in-list", "DtoA");
- testedYangModulesToExpectedConflictingName.put("config-test-duplicate-attribute-runtime-bean", "DtoA");
- testedYangModulesToExpectedConflictingName.put("config-test-generated-attributes-name-conflict", "StateB");
- testedYangModulesToExpectedConflictingName.put("config-test-runtime-bean-list-name-conflict",
- "StateARuntimeMXBean");
- testedYangModulesToExpectedConflictingName.put("config-test-runtime-bean-list-name-conflict2",
- "StateARuntimeMXBean");
- testedYangModulesToExpectedConflictingName.put("config-test-runtime-bean-name-conflict",
- "StateARuntimeMXBean");
- testedYangModulesToExpectedConflictingName.put("config-test-runtime-bean-name-conflict2",
- "StateARuntimeMXBean");
- testedYangModulesToExpectedConflictingName.put("config-test-duplicate-attribute-in-runtime-and-mxbean", "port");
- }
-
- private Module loadYangs(final String testedModule, final String moduleName) {
- final List<String> yangs = new ArrayList<>();
- yangs.add("/ietf-inet-types.yang");
- yangs.add("/duplicates/" + testedModule + YangConstants.RFC6020_YANG_FILE_EXTENSION);
- yangs.addAll(getConfigApiYangs());
-
- this.context = YangParserTestUtils.parseYangResources(ModuleMXBeanEntryNameConflictTest.class, yangs);
- this.namesToModules = YangModelSearchUtils.mapModulesByNames(this.context.getModules());
- this.configModule = this.namesToModules.get(ConfigConstants.CONFIG_MODULE);
- final Module module = this.namesToModules.get(moduleName);
- Preconditions.checkNotNull(module, "Cannot get module %s from %s", moduleName, this.namesToModules.keySet());
- return module;
- }
-
- @Ignore
- @Test
- public void testNameConflicts() {
- for (final String moduleName : testedModules) {
- final Module testedModule = loadYangs(moduleName, moduleName);
-
- try {
- LOG.debug("Testing {}", moduleName);
- ModuleMXBeanEntry.create(testedModule, new HashMap<>(), this.context,
- new TypeProviderWrapper(new TypeProviderImpl(this.context)), PACKAGE_NAME);
- fail(moduleName + " did not cause a name conflict and should");
- } catch (final NameConflictException e) {
- assertEquals(this.testedYangModulesToExpectedConflictingName.get(moduleName), e.getConflictingName());
- }
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.isA;
-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.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import com.google.common.collect.Sets;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Matcher;
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.SimpleType;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.DependencyAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.TypedAttribute;
-import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.mdsal.binding.model.util.Types;
-import org.opendaylight.mdsal.binding.yang.types.TypeProviderImpl;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
-
-public class ModuleMXBeanEntryTest extends AbstractYangTest {
-
- public static final String PACKAGE_NAME = "pack2";
-
- protected static final URI THREADS_NAMESPACE;
- protected static final Revision THREADS_REVISION_DATE = Revision.of("2013-04-09");
-
- static {
- try {
- THREADS_NAMESPACE = new URI(ConfigConstants.CONFIG_NAMESPACE + ":threads");
- } catch (final URISyntaxException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
-
- protected Map<QName, ServiceInterfaceEntry> modulesToSIEs;
-
-
- @Before
- public void setUp() {
- this.modulesToSIEs = loadThreadsServiceInterfaceEntries("packages.sis");
- }
-
-
- protected Map<String /* identity local name */, ModuleMXBeanEntry> loadThreadsJava() {
- return loadThreadsJava(this.modulesToSIEs, PACKAGE_NAME);
- }
-
- @Test
- public void test_jmxImplModule() {
- final Map<IdentitySchemaNode, ServiceInterfaceEntry> identitiesToSIs = new HashMap<>();
- final Map<QName, ServiceInterfaceEntry> modulesToSIEs = ServiceInterfaceEntry
- .create(this.threadsModule, PACKAGE_NAME,identitiesToSIs);
- modulesToSIEs.putAll(ServiceInterfaceEntry.create(this.jmxModule,
- PACKAGE_NAME,identitiesToSIs));
- final Map<String /* identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
- .create(this.jmxImplModule, modulesToSIEs, this.context, new TypeProviderWrapper(new TypeProviderImpl(this.context))
- , PACKAGE_NAME);
- final Map<String, AttributeIfc> attributes = namesToMBEs.get("impl-netconf")
- .getAttributes();
-
- assertCorrectAttributesSize(namesToMBEs, attributes);
-
- //
- final DependencyAttribute threadFactoryAttribute = (DependencyAttribute) attributes
- .get("thread-factory");
- assertNotNull(threadFactoryAttribute);
- assertFalse(threadFactoryAttribute.getDependency().isMandatory());
- assertThat(threadFactoryAttribute.getDependency().getSie()
- .getTypeName(), is("ThreadFactoryServiceInterface"));
- assertThat(threadFactoryAttribute.getAttributeYangName(),
- is("thread-factory"));
- assertThat(threadFactoryAttribute.getLowerCaseCammelCase(),
- is("threadFactory"));
- assertThat(threadFactoryAttribute.getUpperCaseCammelCase(),
- is("ThreadFactory"));
- assertThat(threadFactoryAttribute.getOpenType(), isA(SimpleType.class));
- assertNull(threadFactoryAttribute.getNullableDefault());
- assertNull(threadFactoryAttribute.getNullableDescription());
- assertThat(threadFactoryAttribute.getType().getName(), is("ObjectName"));
- }
-
- private void assertCorrectAttributesSize(final Map<String, ModuleMXBeanEntry> namesToMBEs, final Map<String, AttributeIfc> attributes) {
- assertEquals(14, attributes.size());
- assertEquals(1, namesToMBEs.get("impl-netconf").getRuntimeBeans().size());
- assertEquals(2, namesToMBEs.get("impl-netconf").getRuntimeBeans().iterator().next().getAttributes().size());
-
- assertEquals(4, namesToMBEs.get("impl").getAttributes().size());
- assertEquals(1, namesToMBEs.get("impl").getRuntimeBeans().size());
- assertEquals(1, namesToMBEs.get("impl").getRuntimeBeans().iterator().next().getAttributes().size());
- }
-
- protected RuntimeBeanEntry findFirstByYangName(
- final Collection<RuntimeBeanEntry> runtimeBeans, final String yangName) {
- for (final RuntimeBeanEntry rb : runtimeBeans) {
- if (yangName.equals(rb.getYangName())) {
- return rb;
- }
- }
- throw new IllegalArgumentException("Yang name not found:" + yangName
- + " in " + runtimeBeans);
- }
-
- protected RuntimeBeanEntry findFirstByNamePrefix(final Collection<RuntimeBeanEntry> runtimeBeans, final String namePrefix) {
- for (final RuntimeBeanEntry rb : runtimeBeans) {
- if (namePrefix.equals(rb.getJavaNamePrefix())) {
- return rb;
- }
- }
-
- throw new IllegalArgumentException("Name prefix not found:" + namePrefix
- + " in " + runtimeBeans);
- }
-
- @Test
- public void testGetWhenConditionMatcher() {
- assertMatches("config",
- "/config:modules/config:module/config:type = 'threadpool-dynamic'");
- assertMatches("ns",
- "/ns:modules/ns:module/ns:type = 'threadpool-dynamic'");
- assertMatches("config",
- "/config:modules/config:module/config:type=\"threadpool-dynamic\"");
- }
-
- private void assertMatches(final String prefix, final String input) {
- final RevisionAwareXPath whenConstraint = mock(RevisionAwareXPath.class);
- doReturn(input).when(whenConstraint).toString();
- final Matcher output = ModuleMXBeanEntryBuilder.getWhenConditionMatcher(prefix,
- whenConstraint);
- assertTrue(output.matches());
- assertEquals("threadpool-dynamic", output.group(1));
- }
-
- @Test
- public void testThreadsJava() {
- final Map<String /* identity local name */, ModuleMXBeanEntry> namesToMBEs = loadThreadsJava();
-
- { // check threadpool-dynamic
- final ModuleMXBeanEntry dynamicThreadPool = namesToMBEs
- .get(THREADPOOL_DYNAMIC_MXB_NAME);
- final Map<String, AttributeIfc> attributes = dynamicThreadPool
- .getAttributes();
- // core-size, keepalive, maximum-size
- // threadfactory
- final Set<String> longAttribs = Sets.newHashSet("core-size",
- "maximum-size");
- for (final String longAttrib : longAttribs) {
-
- final TypedAttribute attribute = (TypedAttribute) attributes
- .get(longAttrib);
- assertThat("Failed to check " + longAttrib,
- attribute.getType(),
- is((Type) Types.typeForClass(Long.class)));
- }
- // check dependency on thread factory
- final QName threadfactoryQName = QName.create(THREADS_NAMESPACE,
- THREADS_REVISION_DATE, "threadfactory");
- final ServiceInterfaceEntry threadFactorySIEntry = this.modulesToSIEs
- .get(threadfactoryQName);
- assertNotNull(threadFactorySIEntry);
- final boolean expectedMandatory = true;
- final TypedAttribute actualThreadFactory = (TypedAttribute) attributes
- .get("threadfactory");
-
- final DataSchemaNode mockedDataSchemaNode = mock(DataSchemaNode.class);
- doReturn(Collections.emptyList()).when(mockedDataSchemaNode)
- .getUnknownSchemaNodes();
- doReturn(threadfactoryQName).when(mockedDataSchemaNode).getQName();
- final AttributeIfc expectedDependencyAttribute = new DependencyAttribute(
- mockedDataSchemaNode, threadFactorySIEntry,
- expectedMandatory, "threadfactory description");
- assertThat(actualThreadFactory, is(expectedDependencyAttribute));
- assertThat(
- dynamicThreadPool
- .getFullyQualifiedName("DynamicThreadPoolModuleMXBean"),
- is(PACKAGE_NAME + ".DynamicThreadPoolModuleMXBean"));
- assertThat(dynamicThreadPool.getNullableDescription(),
- is("threadpool-dynamic description"));
- assertThat(dynamicThreadPool.getYangModuleName(),
- is("config-threads-java"));
- assertThat(dynamicThreadPool.getYangModuleLocalname(),
- is(THREADPOOL_DYNAMIC_MXB_NAME));
-
- // check root runtime bean
- final Collection<RuntimeBeanEntry> runtimeBeans = dynamicThreadPool
- .getRuntimeBeans();
- assertThat(runtimeBeans.size(), is(1));
- final RuntimeBeanEntry rootRB = findFirstByYangName(runtimeBeans,
- THREADPOOL_DYNAMIC_MXB_NAME);
- assertThat(rootRB.isRoot(), is(true));
- assertThat(rootRB.getAttributes().size(), is(1));
- final JavaAttribute attribute = (JavaAttribute) rootRB.getAttributes()
- .iterator().next();
- assertThat(attribute.getAttributeYangName(), is("created-sessions"));
- assertThat(rootRB.getYangName(), is(THREADPOOL_DYNAMIC_MXB_NAME));
- assertThat(attribute.getType().getFullyQualifiedName(),
- is(Long.class.getName()));
- }
- {// check threadfactory-naming
- final ModuleMXBeanEntry threadFactoryNaming = namesToMBEs
- .get(THREADFACTORY_NAMING_MXB_NAME);
- final Collection<RuntimeBeanEntry> runtimeBeans = threadFactoryNaming
- .getRuntimeBeans();
- assertThat(runtimeBeans.size(), is(4));
- {
- final RuntimeBeanEntry threadRB = findFirstByYangName(runtimeBeans,
- "thread");
- assertNotNull(threadRB);
- assertFalse(threadRB.isRoot());
- assertEquals("name", threadRB.getKeyYangName().get());
- assertEquals("Name", threadRB.getKeyJavaName().get());
- assertThat(threadRB.getAttributes().size(), is(1));
- final AttributeIfc threadNameAttr = threadRB.getAttributes()
- .iterator().next();
- assertThat(threadNameAttr.getAttributeYangName(), is("name"));
- assertTrue(threadNameAttr instanceof JavaAttribute);
- assertThat(((JavaAttribute) threadNameAttr).getType()
- .getFullyQualifiedName(), is(String.class.getName()));
- assertThat(threadRB.getRpcs().size(), is(2));
- }
- {
- final RuntimeBeanEntry streamRB = findFirstByNamePrefix(runtimeBeans,
- "ThreadStream");
- assertNotNull(streamRB);
- assertFalse(streamRB.getKeyYangName().isPresent());
- assertFalse(streamRB.getKeyJavaName().isPresent());
- final Map<String, AttributeIfc> attributeMap = streamRB
- .getYangPropertiesToTypesMap();
- assertEquals(4, attributeMap.size());
-
- final TOAttribute toAttr = (TOAttribute) attributeMap.get("peer");
- assertNotNull(toAttr);
- assertThat(toAttr.getAttributeYangName(), is("peer"));
- assertThat(toAttr.getLowerCaseCammelCase(), is("peer"));
- assertThat(toAttr.getUpperCaseCammelCase(), is("Peer"));
- assertThat(toAttr.getOpenType(), isA(CompositeType.class));
- Set<String> propsExpected = new HashSet<>(2);
- propsExpected.add("port");
- propsExpected.add("core-size");
- assertThat(toAttr.getYangPropertiesToTypesMap().keySet(),
- is(propsExpected));
- propsExpected = new HashSet<>(2);
- propsExpected.add("Port");
- propsExpected.add("CoreSize");
- assertThat(
- toAttr.getCapitalizedPropertiesToTypesMap().keySet(),
- is(propsExpected));
- propsExpected = new HashSet<>(2);
- propsExpected.add("port");
- propsExpected.add("coreSize");
- assertThat(toAttr.getJmxPropertiesToTypesMap().keySet(),
- is(propsExpected));
-
- final JavaAttribute timestampAttr = (JavaAttribute) attributeMap
- .get("timestamp");
- assertNotNull(timestampAttr);
-
- final JavaAttribute stateAttr = (JavaAttribute) attributeMap
- .get("state");
- assertNotNull(stateAttr);
-
- final ListAttribute innerStream = (ListAttribute) attributeMap
- .get("inner-stream-list");
- assertNotNull(innerStream);
- assertThat(innerStream.getAttributeYangName(),
- is("inner-stream-list"));
- assertThat(innerStream.getLowerCaseCammelCase(),
- is("innerStreamList"));
- assertThat(innerStream.getUpperCaseCammelCase(),
- is("InnerStreamList"));
- assertThat(innerStream.getOpenType(), isA(ArrayType.class));
-
- }
-
- }
- { // test multiple dependencies
- final ModuleMXBeanEntry threadPoolRegistry = namesToMBEs.get(THREADPOOL_REGISTRY_IMPL_NAME);
- final Map<String, AttributeIfc> attributes = threadPoolRegistry.getAttributes();
- assertEquals(1, attributes.size());
- final AttributeIfc threadpoolsAttr = attributes.get("threadpools");
- assertNotNull(threadpoolsAttr);
- assertTrue(threadpoolsAttr instanceof ListDependenciesAttribute);
- final ListDependenciesAttribute threadpools = (ListDependenciesAttribute) threadpoolsAttr;
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import com.google.common.collect.Maps;
-import java.net.URI;
-import java.util.Map;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-public class PackageTranslatorTest {
- public static final String EXPECTED_PACKAGE_PREFIX = "org.opendaylight.controller.config";
-
- @Test
- public void test() throws Exception {
- Map<String, String> map = Maps.newHashMap();
- map.put(ConfigConstants.CONFIG_NAMESPACE, EXPECTED_PACKAGE_PREFIX);
- PackageTranslator tested = new PackageTranslator(map);
- Module module = mock(Module.class);
- doReturn(new URI(ConfigConstants.CONFIG_NAMESPACE + ":threads:api"))
- .when(module).getNamespace();
- assertEquals(EXPECTED_PACKAGE_PREFIX + ".threads.api",
- tested.getPackageName(module));
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-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 static org.mockito.Mockito.doReturn;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import javax.management.openmbean.SimpleType;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.mdsal.binding.yang.types.TypeProviderImpl;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
-
-public class RuntimeBeanEntryTest extends AbstractYangTest {
-
- public static final String PACKAGE_NAME = "packages.sis";
- public static final String THREADFACTORY_NAMING_MXB_NAME = "threadfactory-naming";
- public static final String THREAD_RUNTIME_BEAN_JAVA_NAME = "ThreadRuntimeMXBean";
- public static final String THREAD_RUNTIME_BEAN_JAVA_PREFIX = "Thread";
- public static final String THREAD_RUNTIME_BEAN_YANG_NAME = "thread";
- public static final String SLEEP_RPC_NAME = "sleep";
- public static final String SLEEP_RPC_OUTPUT = "ThreadState";
- public static final String SLEEP_RPC_INPUT_NAME = "millis";
- public static final String SLEEP_RPC_INPUT_TYPE = "Long";
- private static final Map<IdentitySchemaNode, ServiceInterfaceEntry> identitiesToSIs = new HashMap<>();
-
- @Test
- public void createRuntimeBean() {
- final CaseSchemaNode caseNode = Mockito.mock(CaseSchemaNode.class);
- doReturn(new HashSet<LeafSchemaNode>()).when(caseNode).getChildNodes();
- doReturn(new ArrayList<UnknownSchemaNode>()).when(caseNode)
- .getUnknownSchemaNodes();
- final Map<String, RuntimeBeanEntry> runtimeBeans = RuntimeBeanEntry
- .extractClassNameToRuntimeBeanMap(PACKAGE_NAME, caseNode, "test-name", new TypeProviderWrapper(new
- TypeProviderImpl(this.context)), "test", this.jmxImplModule, this.context);
- assertEquals(1, runtimeBeans.size());
- final RuntimeBeanEntry runtimeMXBean = runtimeBeans.get("testRuntimeMXBean");
- assertTrue(runtimeMXBean.isRoot());
- assertEquals("test-name", runtimeMXBean.getYangName());
- }
-
- @Test
- public void runtimeBeanRPCTest() {
- // create service interfaces
- final Map<QName, ServiceInterfaceEntry> modulesToSIEs = ServiceInterfaceEntry
- .create(this.threadsModule, "packages.sis",identitiesToSIs);
- assertNotNull(modulesToSIEs);
-
- // create MXBeans map
- final Map<String, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry.create(
- this.threadsJavaModule, modulesToSIEs, this.context,
- new TypeProviderWrapper(new TypeProviderImpl(this.context)),
- PACKAGE_NAME);
- assertFalse(namesToMBEs.isEmpty());
-
- // get threadfactory-naming bean
- final ModuleMXBeanEntry threadfactoryNamingMXBean = namesToMBEs
- .get(THREADFACTORY_NAMING_MXB_NAME);
- assertNotNull(threadfactoryNamingMXBean);
-
- // get runtime beans
- final Collection<RuntimeBeanEntry> runtimeBeanEntries = threadfactoryNamingMXBean
- .getRuntimeBeans();
- assertFalse(runtimeBeanEntries.isEmpty());
-
- // get root runtime bean
- final RuntimeBeanEntry threadfactoryRuntimeBeanEntry = getRuntimeBeanEntryByJavaName(
- runtimeBeanEntries, "NamingThreadFactoryRuntimeMXBean");
- assertNotNull(threadfactoryRuntimeBeanEntry);
- assertTrue(threadfactoryRuntimeBeanEntry.isRoot());
-
- // get thread runtime bean
- final RuntimeBeanEntry runtimeBeanEntry = getRuntimeBeanEntryByJavaName(
- runtimeBeanEntries, THREAD_RUNTIME_BEAN_JAVA_NAME);
- assertNotNull(runtimeBeanEntry);
-
- // test thread runtime bean properties
- assertEquals(THREAD_RUNTIME_BEAN_JAVA_PREFIX, runtimeBeanEntry.getJavaNamePrefix());
- assertEquals(PACKAGE_NAME, runtimeBeanEntry.getPackageName());
- assertEquals(PACKAGE_NAME + "." + THREAD_RUNTIME_BEAN_JAVA_NAME,
- runtimeBeanEntry.getFullyQualifiedName(runtimeBeanEntry
- .getJavaNameOfRuntimeMXBean()));
- assertEquals(THREAD_RUNTIME_BEAN_YANG_NAME, runtimeBeanEntry.getYangName());
-
- // get thread runtime bean rpcs
- final List<RuntimeBeanEntry.Rpc> rpcs = new ArrayList<>(
- runtimeBeanEntry.getRpcs());
- assertEquals(2, rpcs.size());
-
- // get sleep rpc and test it
- final RuntimeBeanEntry.Rpc rpc = getRpcByName(rpcs, SLEEP_RPC_NAME);
- assertNotNull(rpc);
- assertEquals(SLEEP_RPC_NAME, rpc.getYangName());
-
- assertTrue(((JavaAttribute)rpc.getReturnType()).getType().getFullyQualifiedName().endsWith(SLEEP_RPC_OUTPUT));
-
- // get sleep rpc input attribute and test it
- final List<JavaAttribute> attributes = rpc.getParameters();
- assertEquals(1, attributes.size());
- final JavaAttribute attribute = attributes.get(0);
- assertEquals(SLEEP_RPC_INPUT_NAME, attribute.getAttributeYangName());
- assertEquals(SLEEP_RPC_INPUT_TYPE, attribute.getType().getName());
- assertEquals(SLEEP_RPC_INPUT_NAME, attribute.getLowerCaseCammelCase());
- assertEquals("Millis", attribute.getUpperCaseCammelCase());
- assertNull(attribute.getNullableDefault());
- assertNull(attribute.getNullableDescription());
- assertTrue(attribute.getOpenType() instanceof SimpleType);
- }
-
- private RuntimeBeanEntry getRuntimeBeanEntryByJavaName(
- final Collection<RuntimeBeanEntry> runtimeBeanEntries,
- final String javaName) {
- if ((runtimeBeanEntries != null) && !runtimeBeanEntries.isEmpty()) {
- for (final RuntimeBeanEntry runtimeBeanEntry : runtimeBeanEntries) {
- if (runtimeBeanEntry.getJavaNameOfRuntimeMXBean().equals(
- javaName)) {
- return runtimeBeanEntry;
- }
- }
- }
- return null;
- }
-
- private RuntimeBeanEntry.Rpc getRpcByName(
- final List<RuntimeBeanEntry.Rpc> rpcs, final String name) {
- if ((rpcs != null) && !rpcs.isEmpty()) {
- for (final RuntimeBeanEntry.Rpc rpc : rpcs) {
- if (rpc.getName().equals(name)) {
- return rpc;
- }
- }
- }
- return null;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import static org.apache.commons.lang3.StringUtils.capitalize;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import com.google.common.base.Optional;
-import java.net.URI;
-import java.util.Collections;
-import java.util.List;
-import org.junit.Test;
-import org.opendaylight.mdsal.binding.model.api.Type;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
-
-public class RuntimeRegistratorTest {
- // TODO add more tests
- protected RuntimeBeanEntry prepareRootRB(final List<RuntimeBeanEntry> children) {
-
- final DataNodeContainer nodeContainer = mock(DataNodeContainer.class);
- doReturn("DataSchemaNode").when(nodeContainer).toString();
- return new RuntimeBeanEntry("pa.cka.ge", nodeContainer,
- "module-name", "ModuleName", true, Optional.absent(),
- Collections.emptyList(), children, Collections.emptySet());
- }
-
- protected RuntimeBeanEntry prepareChildRB(final List<RuntimeBeanEntry> children,
- final String prefix) {
- final DataNodeContainer nodeContainer = mock(DataNodeContainer.class);
- doReturn("DataSchemaNode").when(nodeContainer).toString();
- return new RuntimeBeanEntry("pa.cka.ge", nodeContainer,
- prefix + "child-name", capitalize(prefix) + "ChildName", false,
- Optional.absent(), Collections.emptyList(), children, Collections.emptySet());
- }
-
- @Test
- public void testHierarchy() {
- final LeafSchemaNode leaf = mock(LeafSchemaNode.class);
- doReturn(QName.create(URI.create("urn:x"), "leaf-local-name")).when(leaf).getQName();
- doReturn(Collections.emptyList()).when(leaf).getUnknownSchemaNodes();
- doReturn(java.util.Optional.empty()).when(leaf).getDescription();
-
- final StringTypeDefinition leafType = mock(StringTypeDefinition.class);
- doReturn(java.util.Optional.empty()).when(leafType).getDefaultValue();
- doReturn(leafType).when(leaf).getType();
-
- final TypeProviderWrapper typeProviderWrapper = mock(TypeProviderWrapper.class);
- final Type mockedType = mock(Type.class);
- doReturn(mockedType).when(typeProviderWrapper).getType(leaf);
- doReturn("java.lang.String").when(mockedType).getFullyQualifiedName();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants.MODULE_TYPE_Q_NAME;
-import static org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants.SERVICE_TYPE_Q_NAME;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableMap;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
-
-public class SchemaContextTest extends AbstractYangTest {
-
- IdentitySchemaNode findIdentityByQName(final Module module, final QName qName) {
- Map<QName, IdentitySchemaNode> mapIdentitiesByQNames = mapIdentitiesByQNames(module);
- IdentitySchemaNode found = mapIdentitiesByQNames.get(qName);
- assertNotNull(found);
- return found;
- }
-
- @Test
- public void testReadingIdentities_threadsModule() {
-
- IdentitySchemaNode serviceType = findIdentityByQName(configModule,
- SERVICE_TYPE_Q_NAME);
-
- Map<String /* identity name */, Optional<QName>> expectedIdentitiesToBases = ImmutableMap
- .of("eventbus", Optional.<QName>absent(), "threadfactory", Optional.<QName>absent(), "threadpool",
- Optional.<QName>absent(), "scheduled-threadpool", Optional.<QName>absent());
-
- assertThat(threadsModule.getIdentities().size(),
- is(expectedIdentitiesToBases.size()));
- assertAllIdentitiesAreExpected(threadsModule, expectedIdentitiesToBases);
-
- IdentitySchemaNode eventBusSchemaNode = null;
- for (IdentitySchemaNode id : threadsModule.getIdentities()) {
- String localName = id.getQName().getLocalName();
-
- if (localName.equals("eventbus")) {
- eventBusSchemaNode = id;
- }
- // all except scheduled-threadpool should have base set to
- // serviceType
- if (localName.equals("scheduled-threadpool") == false) {
- assertEquals(serviceType, id.getBaseIdentities().iterator().next());
- }
- }
- assertNotNull(eventBusSchemaNode);
- // check unknown schma nodes
- List<UnknownSchemaNode> unknownSchemaNodes = eventBusSchemaNode
- .getUnknownSchemaNodes();
- assertEquals(1, unknownSchemaNodes.size());
- UnknownSchemaNode usn = unknownSchemaNodes.get(0);
- assertEquals("com.google.common.eventbus.EventBus", usn.getQName()
- .getLocalName());
- assertEquals(ConfigConstants.JAVA_CLASS_EXTENSION_QNAME,
- usn.getNodeType());
- }
-
- private static void assertAllIdentitiesAreExpected(final Module module,
- final Map<String /* identity name */, Optional<QName>> expectedIdentitiesToBases) {
- Map<String /* identity name */, Optional<QName>> copyOfExpectedNames = new HashMap<>(
- expectedIdentitiesToBases);
- for (IdentitySchemaNode id : module.getIdentities()) {
- String localName = id.getQName().getLocalName();
- assertTrue("Unexpected identity " + localName,
- copyOfExpectedNames.containsKey(localName));
- Optional<QName> maybeExpectedBaseQName = copyOfExpectedNames
- .remove(localName);
- if (maybeExpectedBaseQName.isPresent()) {
- assertEquals("Unexpected base identity of " + localName,
- maybeExpectedBaseQName.get(), id.getBaseIdentities().iterator().next().getQName());
- }
- }
- assertEquals("Expected identities not found " + copyOfExpectedNames,
- Collections.emptyMap(), copyOfExpectedNames);
- }
-
- @Test
- public void testReadingIdentities_threadsJavaModule() {
- Map<String /* identity name */, Optional<QName>> expected = new HashMap<>();
- expected.put(ModuleMXBeanEntryTest.EVENTBUS_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
- expected.put(ModuleMXBeanEntryTest.ASYNC_EVENTBUS_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
- expected.put(ModuleMXBeanEntryTest.THREADFACTORY_NAMING_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
- expected.put(ModuleMXBeanEntryTest.THREADPOOL_DYNAMIC_MXB_NAME, Optional.of(MODULE_TYPE_Q_NAME));
- expected.put("thread-rpc-context", Optional.<QName>absent());
- expected.put(ModuleMXBeanEntryTest.THREADPOOL_REGISTRY_IMPL_NAME, Optional.of(MODULE_TYPE_Q_NAME));
-
- assertAllIdentitiesAreExpected(threadsJavaModule, expected);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-import com.google.common.collect.Sets;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import org.hamcrest.CoreMatchers;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-
-public class ServiceInterfaceEntryTest extends AbstractYangTest {
- public static final String PACKAGE_NAME = "packages.sis";
- public static final List<String> expectedSIEFileNames = toFileNames("[EventBusServiceInterface"
- + ".java, "
- + "ScheduledThreadPoolServiceInterface"
- + ".java, ThreadFactoryServiceInterface.java, ThreadPoolServiceInterface.java]");
-
- private static final URI THREADS_NAMESPACE;
- private static final Revision THREADS_REVISION_DATE = Revision.of("2013-04-09");
-
- static {
- try {
- THREADS_NAMESPACE = new URI(ConfigConstants.CONFIG_NAMESPACE + ":threads");
- } catch (URISyntaxException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
-
- public static final QName EVENTBUS_QNAME = QName.create(THREADS_NAMESPACE,
- THREADS_REVISION_DATE, "eventbus");
- public static final QName THREADFACTORY_QNAME = QName.create(
- THREADS_NAMESPACE, THREADS_REVISION_DATE, "threadfactory");
- public static final QName THREADPOOL_QNAME = QName.create(THREADS_NAMESPACE,
- THREADS_REVISION_DATE, "threadpool");
- public static final QName SCHEDULED_THREADPOOL_QNAME = QName.create(
- THREADS_NAMESPACE, THREADS_REVISION_DATE, "scheduled-threadpool");
- public static final QName SCHEDULED_EXECUTOR_SERVICE_QNAME = QName.create(
- THREADS_NAMESPACE, THREADS_REVISION_DATE,
- "scheduled-executor-service");
- public static final String SCHEDULED_THREADPOOL_INTERFACE_NAME = "ScheduledThreadPoolServiceInterface";
-
- public static List<String> toFileNames(String fileNameString) {
- assertThat(fileNameString.startsWith("["), CoreMatchers.is(true));
- assertThat(fileNameString.endsWith("]"), CoreMatchers.is(true));
- fileNameString = fileNameString.substring(1,
- fileNameString.length() - 1);
- return Arrays.asList(fileNameString.split(", "));
- }
-
- @Test
- public void testCreateFromIdentities() {
- // each identity has to have a base that leads to service-type
- Map<IdentitySchemaNode, ServiceInterfaceEntry> definedIdentities = new HashMap<>();
- Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry
- .create(threadsModule, PACKAGE_NAME,definedIdentities);
- // expected eventbus, threadfactory, threadpool,
- // scheduled-threadpool,thread-rpc-context
- assertThat(namesToSIEntries.size(), is(expectedSIEFileNames.size()));
-
- Set<QName> withNoBaseType = Sets.newHashSet(EVENTBUS_QNAME,
- THREADFACTORY_QNAME, THREADPOOL_QNAME,
- SCHEDULED_EXECUTOR_SERVICE_QNAME);
- HashSet<QName> withBaseType = new HashSet<>();
- for (Entry<QName, ServiceInterfaceEntry> entry : namesToSIEntries
- .entrySet()) {
- QName qName = entry.getKey();
- if (withNoBaseType.contains(qName)) {
- ServiceInterfaceEntry sie = namesToSIEntries.get(qName);
- assertNotNull(qName + " not found", sie);
- assertThat(qName + " should have empty base type", sie
- .getBase().isPresent(), is(false));
- assertThat(sie.getQName(), is(qName));
- } else {
- withBaseType.add(qName);
- }
- }
- // scheduled-threadpool has super type threadpool
- assertThat(withBaseType,
- is(Sets.newHashSet(SCHEDULED_THREADPOOL_QNAME)));
- assertThat(withBaseType.contains(SCHEDULED_THREADPOOL_QNAME), is(true));
- ServiceInterfaceEntry scheduled = namesToSIEntries
- .get(SCHEDULED_THREADPOOL_QNAME);
- assertNotNull(scheduled);
- assertThat(scheduled.getQName(), is(SCHEDULED_THREADPOOL_QNAME));
- ServiceInterfaceEntry threadPool = namesToSIEntries
- .get(THREADPOOL_QNAME);
- assertNotNull(threadPool);
- assertThat("scheduled-threadpool should extend threadpool", scheduled
- .getBase().get(), is(threadPool));
-
- assertThat(scheduled.getExportedOsgiClassName(),
- is(PackageTranslatorTest.EXPECTED_PACKAGE_PREFIX
- + ".threadpool.ScheduledThreadPool"));
- assertThat(threadPool.getExportedOsgiClassName(),
- is(PackageTranslatorTest.EXPECTED_PACKAGE_PREFIX
- + ".threadpool.ThreadPool"));
-
- String expectedDescription = "An extension of the simple pool of threads able to schedule\n"
- + "work to be executed at some point in time.";
- assertThat(trimInnerSpacesOrNull(scheduled.getNullableDescription()),
- is(expectedDescription));
- assertThat(scheduled.getPackageName(), is(PACKAGE_NAME));
- assertThat(scheduled.getTypeName(),
- is(SCHEDULED_THREADPOOL_INTERFACE_NAME));
- assertThat(scheduled.getFullyQualifiedName(), is(PACKAGE_NAME + "."
- + SCHEDULED_THREADPOOL_INTERFACE_NAME));
- }
-
- static String trimInnerSpacesOrNull(final String input) {
- if (input == null) {
- return null;
- }
- return input.replaceAll("\\s{2,}", " ");
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.plugin.util;
-
-import com.google.common.base.Preconditions;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-public class YangModelSearchUtils {
-
- public static Map<String, Module> mapModulesByNames(
- Collection<Module> modules) {
- Map<String, Module> result = new HashMap<>();
- for (Module m : modules) {
- String moduleName = m.getName();
- Preconditions.checkArgument(
- result.containsKey(moduleName) == false,
- "Two modules have same name " + moduleName);
- result.put(moduleName, m);
- }
- return result;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yangjmxgenerator.unknownextension;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.junit.Test;
-import org.opendaylight.controller.config.yangjmxgenerator.ConfigConstants;
-import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntryTest;
-import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.YangModelSearchUtils;
-import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-
-public class UnknownExtensionTest extends ServiceInterfaceEntryTest {
-
- @Test
- public void testStopOnUnknownLanguageExtension() throws Exception {
- List<String> yangs = new ArrayList<>();
- yangs.addAll(getConfigApiYangs());
- yangs.add("test-ifcWithUnknownExtension.yang");
-
- context = YangParserTestUtils.parseYangResources(UnknownExtensionTest.class, yangs);
- namesToModules = YangModelSearchUtils.mapModulesByNames(context.getModules());
- configModule = namesToModules.get(ConfigConstants.CONFIG_MODULE);
- threadsModule = namesToModules.get(ConfigConstants.CONFIG_THREADS_MODULE);
- try {
- super.testCreateFromIdentities();
- fail();
- } catch (IllegalStateException e) {
- assertTrue(e.getMessage(),
- e.getMessage().startsWith("Unexpected unknown schema node."));
- }
- }
-
-}
+++ /dev/null
-module config-bgp-listener-impl {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:config:bgp:listener:impl";
- prefix "bgpl-impl";
-
- import ietf-inet-types { prefix inet; }
- import config { prefix config; revision-date 2013-04-05; }
-
- description
- "This module contains the base YANG definitions for NS-OS
- BGP listener implementation.";
-
- revision "2013-04-09" {
- description
- "Initial revision";
- reference "NS-OS System Design, version 1.2.";
- }
-
- identity bgp-listener-impl {
- base config:module-type;
- }
-
- augment "/config:modules/config:module/config:state" {
- case bgp-listener-impl {
- when "/config:modules/config:module/config:type = 'bgp-listener-impl'";
- container bgp-listener-impl {
- list peers {
- config:inner-state-bean;
- leaf port {
- type inet:port-number;
- default 179;
- }
- leaf core-size {
- type uint32;
- }
- }
-
- leaf as-number {
- mandatory true;
- type inet:as-number;
- }
- }
- }
- }
-}
+++ /dev/null
-module config-jmx-it-impl {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:config:jmx:generator:it:impl";
- prefix "it-impl";
-
- import config-jmx-it { prefix jmxIt; revision-date 2013-06-13;}
- import config { prefix config; revision-date 2013-04-05; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
- import config-threads { prefix th; revision-date 2013-04-09; }
-
- description
- "Testing IMPL";
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity impl {
- base config:module-type;
- config:provided-service jmxIt:testing;
- config:java-name-prefix TestImpl;
- }
-
- identity impl-netconf {
- base config:module-type;
- config:provided-service jmxIt:testing;
- config:java-name-prefix NetconfTestImpl;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case impl {
- when "/config:modules/config:module/config:type = 'impl'";
-
- container dto-a1 {
- leaf simple-arg {
- type uint32;
- }
-
- leaf port {
- type inet:port-number;
- }
-
- }
-
- leaf as-number {
- mandatory true;
- type inet:as-number;
- }
-
-
- leaf simpleInt1 {
- type uint32;
- default 99L;
- }
-
- container dto_b {
- leaf simple-int1 {
- type uint32;
- }
-
- leaf simple-int2 {
- type uint32;
- }
- }
-
- }
-
- case impl-netconf {
- when "/config:modules/config:module/config:type = 'impl-netconf'";
-
- container dto-a {
- leaf simple-arg {
- type uint32;
- }
-
- container dto-a-inner {
- leaf simple-arg {
- type uint32;
- }
-
- container dto-a-inner-inner {
- leaf simple-arg {
- type uint32;
- }
- }
- }
- }
-
- leaf simpleInt2 {
- type uint32;
- }
-
- leaf simpleBoolean {
- type boolean;
- default false;
- }
-
- leaf simple-long {
- type int64 ;
- }
-
- leaf simple-long-2 {
- type uint32;
- }
-
- leaf simple-BigInteger {
- type uint64;
- }
-
- leaf simple-byte {
- type int8;
- }
-
- leaf simple-short {
- type uint8;
- }
-
- leaf simple-test {
- type uint16;
- default 99;
- }
-
- leaf-list simple-list {
- type uint16;
- }
-
- container dto_c {
- leaf simple-int1 {
- type uint32;
- }
-
- leaf simple-int2 {
- type uint32;
- }
-
- leaf simple-int3 {
- type uint16;
- }
-
- leaf-list simple-list {
- type uint16;
- }
-
- list complex-dto-bInner {
- leaf-list simple-list {
- type uint16;
- }
- leaf simple-int3 {
- type uint16;
- }
-
- container deep {
- leaf simple-int3 {
- type uint16;
- }
- }
- }
- }
-
- list complex-list {
- list simple-list {
- leaf simple-int3 {
- type uint16;
- }
- }
- }
-
- list peers {
- config:java-name-prefix Peer;
- leaf port {
- type string;
- }
- leaf core-size {
- type uint32;
- }
- leaf simple-int3 {
- type uint16;
- }
- }
-
- container thread-factory {
- uses config:service-ref {
- refine type {
- mandatory false;
- config:required-identity th:threadfactory;
- }
- refine name {
- mandatory false;
- }
- }
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case impl {
- when "/config:modules/config:module/config:type = 'impl'";
- // root runtime bean
- leaf created-sessions {
- type uint32;
- }
- }
-
- case impl-netconf {
- when "/config:modules/config:module/config:type = 'impl-netconf'";
- // root runtime bean
- leaf created-sessions-1 {
- type uint32;
- }
-
- leaf created-sessions-2 {
- type uint32;
- }
-
- }
- }
-
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-jmx-it {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:config:jmx:generator:it";
- prefix "jmxIt";
-
- import config { prefix config; revision-date 2013-04-05; }
-
-
-
- description
- "Testing API";
-
- revision "2013-06-13" {
- description
- "Initial revision";
- }
-
- identity testing {
- description
- "Test api";
-
- base "config:service-type";
- config:java-class "java.lang.AutoCloseable";
- }
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-test-duplicate-attribute-in-list {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:jmx:generator:it:duplicate";
- prefix "it-duplicate";
-
- import config { prefix config; revision-date 2013-04-05; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
- description
- "Testing IMPL";
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity implementation {
- base config:module-type;
- config:java-name-prefix TestImpl;
- }
-
- identity netconf {
- base config:module-type;
- config:java-name-prefix NetconfTestImpl;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case implementation {
- when "/config:modules/config:module/config:type = 'implementation'";
-
- container dto-a {
- leaf simple-arg {
- type uint32;
- }
-
- leaf port {
- type inet:port-number;
- }
-
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case implementation {
- when "/config:modules/config:module/config:type = 'implementation'";
- // root runtime bean
- leaf created-sessions {
- type uint32;
- }
- }
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case netconf {
- when "/config:modules/config:module/config:type = 'netconf'";
-
- list dtos {
- config:java-name-prefix dto-a;
- leaf port {
- type string;
- }
- leaf core-size {
- type uint32;
- }
- leaf simple-int3 {
- type uint16;
- }
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case netconf {
- when "/config:modules/config:module/config:type = 'netconf'";
- // root runtime bean
- leaf created-sessions2 {
- type uint32;
- }
-
- }
- }
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-test-duplicate-attribute-in-runtime-and-mxbean {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:jmx:duplicate:runtime";
- prefix "th-java";
-
- import config { prefix config; revision-date 2013-04-05; }
- import rpc-context { prefix rpcx; revision-date 2013-06-17; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
-
- description
- "This module contains the base YANG definitions for NS-OS
- thread services pure Java implementation.";
-
- revision "2013-04-05" {
- description
- "Updated to work with new anchors.";
- }
-
- revision "2013-04-03" {
- description
- "Initial revision.";
- }
-
- identity async-eventbus {
- base config:module-type;
- config:java-name-prefix AsyncEventBus;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- leaf port {
- type string;
- }
- leaf core-size {
- type uint32;
- }
- leaf simple-int3 {
- type uint16;
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- leaf simple-arg {
- type uint32;
- }
- leaf port {
- type inet:port-number;
- }
- }
- }
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-test-duplicate-attribute-runtime-bean {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:jmx:duplicate:runtime";
- prefix "th-java";
-
- import config { prefix config; revision-date 2013-04-05; }
- import rpc-context { prefix rpcx; revision-date 2013-06-17; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
-
- description
- "This module contains the base YANG definitions for NS-OS
- thread services pure Java implementation.";
-
- revision "2013-04-05" {
- description
- "Updated to work with new anchors.";
- }
-
- revision "2013-04-03" {
- description
- "Initial revision.";
- }
-
- identity async-eventbus {
- base config:module-type;
- config:java-name-prefix AsyncEventBus;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- list dtos {
- config:java-name-prefix dto-a;
- leaf port {
- type string;
- }
- leaf core-size {
- type uint32;
- }
- leaf simple-int3 {
- type uint16;
- }
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- container dto-a {
- leaf simple-arg {
- type uint32;
- }
-
- leaf port {
- type inet:port-number;
- }
- }
- }
- }
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-test-duplicate-attribute {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:jmx:generator:it:duplicate";
- prefix "it-duplicate";
-
- import config { prefix config; revision-date 2013-04-05; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
- description
- "Testing IMPL";
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity implementation {
- base config:module-type;
- config:java-name-prefix TestImpl;
- }
-
- identity netconf {
- base config:module-type;
- config:java-name-prefix NetconfTestImpl;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case implementation {
- when "/config:modules/config:module/config:type = 'implementation'";
-
- container dto-a {
- leaf simple-arg {
- type uint32;
- }
-
- leaf port {
- type inet:port-number;
- }
-
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case implementation {
- when "/config:modules/config:module/config:type = 'implementation'";
- // root runtime bean
- leaf created-sessions {
- type uint32;
- }
- }
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case netconf {
- when "/config:modules/config:module/config:type = 'netconf'";
-
- container dto-a2 {
- leaf simple-arg {
- type uint32;
- }
-
- leaf port {
- type inet:port-number;
- }
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case netconf {
- when "/config:modules/config:module/config:type = 'netconf'";
- // root runtime bean
- leaf created-sessions2 {
- type uint32;
- }
-
- }
- }
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-test-generated-attributes-name-conflict {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:jmx:duplicate:runtime:bean";
- prefix "th-java";
-
- import config { prefix config; revision-date 2013-04-05; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
- description
- "This module contains the base YANG definitions for NS-OS
- thread services pure Java implementation.";
-
- revision "2013-04-05" {
- description
- "Updated to work with new anchors.";
- }
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity async-eventbus {
- base config:module-type;
- config:java-name-prefix AsyncEventBus;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- leaf port {
- type string;
- }
-
- list state-b {
- leaf port {
- type string;
- }
- }
-
- container stateB {
- leaf port {
- type string;
- }
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
-
- list state-a {
- config:inner-state-bean;
-
- leaf port {
- type string;
- }
-
- list state-b {
- leaf port {
- type string;
- }
- }
- }
- }
- }
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-test-runtime-bean-list-name-conflict {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:jmx:duplicate:runtime:bean";
- prefix "th-java";
-
- import config { prefix config; revision-date 2013-04-05; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
- description
- "This module contains the base YANG definitions for NS-OS
- thread services pure Java implementation.";
-
- revision "2013-04-05" {
- description
- "Updated to work with new anchors.";
- }
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity async-eventbus {
- base config:module-type;
- config:java-name-prefix AsyncEventBus;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- leaf port {
- type string;
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
-
- list state-a-runtime-mX-bean {
- leaf port {
- type string;
- }
- }
-
- list state-a {
- config:inner-state-bean;
-
- leaf port {
- type string;
- }
- }
- }
- }
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-test-runtime-bean-list-name-conflict2 {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:jmx:duplicate:runtime:bean";
- prefix "th-java";
-
- import config { prefix config; revision-date 2013-04-05; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
- description
- "This module contains the base YANG definitions of
- thread services pure Java implementation.";
-
- revision "2013-04-05" {
- description
- "Updated to work with new anchors.";
- }
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity async-eventbus {
- base config:module-type;
- config:java-name-prefix AsyncEventBus;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- leaf port {
- type string;
- }
-
- list state-a-runtime-mX-bean {
- leaf port {
- type string;
- }
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
-
- list state-a {
- config:inner-state-bean;
-
- leaf port {
- type string;
- }
- }
- }
- }
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-test-runtime-bean-name-conflict {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:jmx:duplicate:runtime:bean";
- prefix "th-java";
-
- import config { prefix config; revision-date 2013-04-05; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
- description
- "This module contains the base YANG definitions for
- thread services pure Java implementation.";
-
- revision "2013-04-05" {
- description
- "Updated to work with new anchors.";
- }
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity async-eventbus {
- base config:module-type;
- config:java-name-prefix AsyncEventBus;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- leaf port {
- type string;
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
-
- list state-a {
- config:inner-state-bean;
-
- leaf port {
- type string;
- }
-
- list state-a {
- config:inner-state-bean;
-
- leaf port {
- type string;
- }
- }
- }
- }
- }
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-test-runtime-bean-name-conflict2 {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:jmx:duplicate:runtime:bean";
- prefix "th-java";
-
- import config { prefix config; revision-date 2013-04-05; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
-
- description
- "This module contains the base YANG definitions for
- thread services pure Java implementation.";
-
- revision "2013-04-05" {
- description
- "Initial";
- }
-
- identity async-eventbus {
- base config:module-type;
- config:java-name-prefix AsyncEventBus;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- leaf port {
- type string;
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
-
- list state-a {
- config:inner-state-bean;
-
- leaf port {
- type string;
- }
- }
- }
- }
-
-
- identity async-eventbus-b {
- base config:module-type;
- config:java-name-prefix AsyncEventBusB;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case async-eventbus-b {
- when "/config:modules/config:module/config:type = 'async-eventbus-b'";
- leaf port {
- type string;
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case async-eventbus-b {
- when "/config:modules/config:module/config:type = 'async-eventbus-b'";
-
- list state-a {
- config:inner-state-bean;
-
- leaf port {
- type string;
- }
-
- }
- }
- }
-}
+++ /dev/null
-module ietf-inet-types {
-
- namespace "urn:ietf:params:xml:ns:yang:ietf-inet-types";
- prefix "inet";
-
- organization
- "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
-
- contact
- "WG Web: <http://tools.ietf.org/wg/netmod/>
- WG List: <mailto:netmod@ietf.org>
-
- WG Chair: David Kessens
- <mailto:david.kessens@nsn.com>
-
- WG Chair: Juergen Schoenwaelder
- <mailto:j.schoenwaelder@jacobs-university.de>
-
- Editor: Juergen Schoenwaelder
- <mailto:j.schoenwaelder@jacobs-university.de>";
-
- description
- "This module contains a collection of generally useful derived
- YANG data types for Internet addresses and related things.
-
- Copyright (c) 2013 IETF Trust and the persons identified as
- authors of the code. All rights reserved.
-
- Redistribution and use in source and binary forms, with or
- without modification, is permitted pursuant to, and subject
- to the license terms contained in, the Simplified BSD License
- set forth in Section 4.c of the IETF Trust's Legal Provisions
- Relating to IETF Documents
- (http://trustee.ietf.org/license-info).
-
- This version of this YANG module is part of RFC 6991; see
- the RFC itself for full legal notices.";
-
- revision 2013-07-15 {
- description
- "This revision adds the following new data types:
- - ip-address-no-zone
- - ipv4-address-no-zone
- - ipv6-address-no-zone";
- reference
- "RFC 6991: Common YANG Data Types";
- }
-
- revision 2010-09-24 {
- description
- "Initial revision.";
- reference
- "RFC 6021: Common YANG Data Types";
- }
-
- /*** collection of types related to protocol fields ***/
-
- typedef ip-version {
- type enumeration {
- enum unknown {
- value "0";
- description
- "An unknown or unspecified version of the Internet
- protocol.";
- }
- enum ipv4 {
- value "1";
- description
- "The IPv4 protocol as defined in RFC 791.";
- }
- enum ipv6 {
- value "2";
- description
- "The IPv6 protocol as defined in RFC 2460.";
- }
- }
- description
- "This value represents the version of the IP protocol.
-
- In the value set and its semantics, this type is equivalent
- to the InetVersion textual convention of the SMIv2.";
- reference
- "RFC 791: Internet Protocol
- RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
- RFC 4001: Textual Conventions for Internet Network Addresses";
- }
-
- typedef dscp {
- type uint8 {
- range "0..63";
- }
- description
- "The dscp type represents a Differentiated Services Code Point
- that may be used for marking packets in a traffic stream.
- In the value set and its semantics, this type is equivalent
- to the Dscp textual convention of the SMIv2.";
- reference
- "RFC 3289: Management Information Base for the Differentiated
- Services Architecture
- RFC 2474: Definition of the Differentiated Services Field
- (DS Field) in the IPv4 and IPv6 Headers
- RFC 2780: IANA Allocation Guidelines For Values In
- the Internet Protocol and Related Headers";
- }
-
- typedef ipv6-flow-label {
- type uint32 {
- range "0..1048575";
- }
- description
- "The ipv6-flow-label type represents the flow identifier or Flow
- Label in an IPv6 packet header that may be used to
- discriminate traffic flows.
-
- In the value set and its semantics, this type is equivalent
- to the IPv6FlowLabel textual convention of the SMIv2.";
- reference
- "RFC 3595: Textual Conventions for IPv6 Flow Label
- RFC 2460: Internet Protocol, Version 6 (IPv6) Specification";
- }
-
- typedef port-number {
- type uint16 {
- range "0..65535";
- }
- description
- "The port-number type represents a 16-bit port number of an
- Internet transport-layer protocol such as UDP, TCP, DCCP, or
- SCTP. Port numbers are assigned by IANA. A current list of
- all assignments is available from <http://www.iana.org/>.
-
- Note that the port number value zero is reserved by IANA. In
- situations where the value zero does not make sense, it can
- be excluded by subtyping the port-number type.
- In the value set and its semantics, this type is equivalent
- to the InetPortNumber textual convention of the SMIv2.";
- reference
- "RFC 768: User Datagram Protocol
- RFC 793: Transmission Control Protocol
- RFC 4960: Stream Control Transmission Protocol
- RFC 4340: Datagram Congestion Control Protocol (DCCP)
- RFC 4001: Textual Conventions for Internet Network Addresses";
- }
-
- /*** collection of types related to autonomous systems ***/
-
- typedef as-number {
- type uint32;
- description
- "The as-number type represents autonomous system numbers
- which identify an Autonomous System (AS). An AS is a set
- of routers under a single technical administration, using
- an interior gateway protocol and common metrics to route
- packets within the AS, and using an exterior gateway
- protocol to route packets to other ASes. IANA maintains
- the AS number space and has delegated large parts to the
- regional registries.
-
- Autonomous system numbers were originally limited to 16
- bits. BGP extensions have enlarged the autonomous system
- number space to 32 bits. This type therefore uses an uint32
- base type without a range restriction in order to support
- a larger autonomous system number space.
-
- In the value set and its semantics, this type is equivalent
- to the InetAutonomousSystemNumber textual convention of
- the SMIv2.";
- reference
- "RFC 1930: Guidelines for creation, selection, and registration
- of an Autonomous System (AS)
- RFC 4271: A Border Gateway Protocol 4 (BGP-4)
- RFC 4001: Textual Conventions for Internet Network Addresses
- RFC 6793: BGP Support for Four-Octet Autonomous System (AS)
- Number Space";
- }
-
- /*** collection of types related to IP addresses and hostnames ***/
-
- typedef ip-address {
- type union {
- type inet:ipv4-address;
- type inet:ipv6-address;
- }
- description
- "The ip-address type represents an IP address and is IP
- version neutral. The format of the textual representation
- implies the IP version. This type supports scoped addresses
- by allowing zone identifiers in the address format.";
- reference
- "RFC 4007: IPv6 Scoped Address Architecture";
- }
-
- typedef ipv4-address {
- type string {
- pattern
- '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
- + '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
- + '(%[\p{N}\p{L}]+)?';
- }
- description
- "The ipv4-address type represents an IPv4 address in
- dotted-quad notation. The IPv4 address may include a zone
- index, separated by a % sign.
-
- The zone index is used to disambiguate identical address
- values. For link-local addresses, the zone index will
- typically be the interface index number or the name of an
- interface. If the zone index is not present, the default
- zone of the device will be used.
-
- The canonical format for the zone index is the numerical
- format";
- }
-
- typedef ipv6-address {
- type string {
- pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
- + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
- + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
- + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
- + '(%[\p{N}\p{L}]+)?';
- pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
- + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
- + '(%.+)?';
- }
- description
- "The ipv6-address type represents an IPv6 address in full,
- mixed, shortened, and shortened-mixed notation. The IPv6
- address may include a zone index, separated by a % sign.
-
- The zone index is used to disambiguate identical address
- values. For link-local addresses, the zone index will
- typically be the interface index number or the name of an
- interface. If the zone index is not present, the default
- zone of the device will be used.
-
- The canonical format of IPv6 addresses uses the textual
- representation defined in Section 4 of RFC 5952. The
- canonical format for the zone index is the numerical
- format as described in Section 11.2 of RFC 4007.";
- reference
- "RFC 4291: IP Version 6 Addressing Architecture
- RFC 4007: IPv6 Scoped Address Architecture
- RFC 5952: A Recommendation for IPv6 Address Text
- Representation";
- }
-
- typedef ip-address-no-zone {
- type union {
- type inet:ipv4-address-no-zone;
- type inet:ipv6-address-no-zone;
- }
- description
- "The ip-address-no-zone type represents an IP address and is
- IP version neutral. The format of the textual representation
- implies the IP version. This type does not support scoped
- addresses since it does not allow zone identifiers in the
- address format.";
- reference
- "RFC 4007: IPv6 Scoped Address Architecture";
- }
-
- typedef ipv4-address-no-zone {
- type inet:ipv4-address {
- pattern '[0-9\.]*';
- }
- description
- "An IPv4 address without a zone index. This type, derived from
- ipv4-address, may be used in situations where the zone is
- known from the context and hence no zone index is needed.";
- }
-
- typedef ipv6-address-no-zone {
- type inet:ipv6-address {
- pattern '[0-9a-fA-F:\.]*';
- }
- description
- "An IPv6 address without a zone index. This type, derived from
- ipv6-address, may be used in situations where the zone is
- known from the context and hence no zone index is needed.";
- reference
- "RFC 4291: IP Version 6 Addressing Architecture
- RFC 4007: IPv6 Scoped Address Architecture
- RFC 5952: A Recommendation for IPv6 Address Text
- Representation";
- }
-
- typedef ip-prefix {
- type union {
- type inet:ipv4-prefix;
- type inet:ipv6-prefix;
- }
- description
- "The ip-prefix type represents an IP prefix and is IP
- version neutral. The format of the textual representations
- implies the IP version.";
- }
-
- typedef ipv4-prefix {
- type string {
- pattern
- '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
- + '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
- + '/(([0-9])|([1-2][0-9])|(3[0-2]))';
- }
- description
- "The ipv4-prefix type represents an IPv4 address prefix.
- The prefix length is given by the number following the
- slash character and must be less than or equal to 32.
-
- A prefix length value of n corresponds to an IP address
- mask that has n contiguous 1-bits from the most
- significant bit (MSB) and all other bits set to 0.
-
- The canonical format of an IPv4 prefix has all bits of
- the IPv4 address set to zero that are not part of the
- IPv4 prefix.";
- }
-
- typedef ipv6-prefix {
- type string {
- pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
- + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
- + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
- + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
- + '(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))';
- pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
- + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
- + '(/.+)';
- }
- description
- "The ipv6-prefix type represents an IPv6 address prefix.
- The prefix length is given by the number following the
- slash character and must be less than or equal to 128.
-
- A prefix length value of n corresponds to an IP address
- mask that has n contiguous 1-bits from the most
- significant bit (MSB) and all other bits set to 0.
-
- The IPv6 address should have all bits that do not belong
- to the prefix set to zero.
-
- The canonical format of an IPv6 prefix has all bits of
- the IPv6 address set to zero that are not part of the
- IPv6 prefix. Furthermore, the IPv6 address is represented
- as defined in Section 4 of RFC 5952.";
- reference
- "RFC 5952: A Recommendation for IPv6 Address Text
- Representation";
- }
-
- /*** collection of domain name and URI types ***/
-
- typedef domain-name {
- type string {
- pattern
- '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*'
- + '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)'
- + '|\.';
- length "1..253";
- }
- description
- "The domain-name type represents a DNS domain name. The
- name SHOULD be fully qualified whenever possible.
-
- Internet domain names are only loosely specified. Section
- 3.5 of RFC 1034 recommends a syntax (modified in Section
- 2.1 of RFC 1123). The pattern above is intended to allow
- for current practice in domain name use, and some possible
- future expansion. It is designed to hold various types of
- domain names, including names used for A or AAAA records
- (host names) and other records, such as SRV records. Note
- that Internet host names have a stricter syntax (described
- in RFC 952) than the DNS recommendations in RFCs 1034 and
- 1123, and that systems that want to store host names in
- schema nodes using the domain-name type are recommended to
- adhere to this stricter standard to ensure interoperability.
-
- The encoding of DNS names in the DNS protocol is limited
- to 255 characters. Since the encoding consists of labels
- prefixed by a length bytes and there is a trailing NULL
- byte, only 253 characters can appear in the textual dotted
- notation.
-
- The description clause of schema nodes using the domain-name
- type MUST describe when and how these names are resolved to
- IP addresses. Note that the resolution of a domain-name value
- may require to query multiple DNS records (e.g., A for IPv4
- and AAAA for IPv6). The order of the resolution process and
- which DNS record takes precedence can either be defined
- explicitly or may depend on the configuration of the
- resolver.
-
- Domain-name values use the US-ASCII encoding. Their canonical
- format uses lowercase US-ASCII characters. Internationalized
- domain names MUST be A-labels as per RFC 5890.";
- reference
- "RFC 952: DoD Internet Host Table Specification
- RFC 1034: Domain Names - Concepts and Facilities
- RFC 1123: Requirements for Internet Hosts -- Application
- and Support
- RFC 2782: A DNS RR for specifying the location of services
- (DNS SRV)
- RFC 5890: Internationalized Domain Names in Applications
- (IDNA): Definitions and Document Framework";
- }
-
- typedef host {
- type union {
- type inet:ip-address;
- type inet:domain-name;
- }
- description
- "The host type represents either an IP address or a DNS
- domain name.";
- }
-
- typedef uri {
- type string;
- description
- "The uri type represents a Uniform Resource Identifier
- (URI) as defined by STD 66.
-
- Objects using the uri type MUST be in US-ASCII encoding,
- and MUST be normalized as described by RFC 3986 Sections
- 6.2.1, 6.2.2.1, and 6.2.2.2. All unnecessary
- percent-encoding is removed, and all case-insensitive
- characters are set to lowercase except for hexadecimal
- digits, which are normalized to uppercase as described in
- Section 6.2.2.1.
-
- The purpose of this normalization is to help provide
- unique URIs. Note that this normalization is not
- sufficient to provide uniqueness. Two URIs that are
- textually distinct after this normalization may still be
- equivalent.
-
- Objects using the uri type may restrict the schemes that
- they permit. For example, 'data:' and 'urn:' schemes
- might not be appropriate.
-
- A zero-length URI is not a valid URI. This can be used to
- express 'URI absent' where required.
-
- In the value set and its semantics, this type is equivalent
- to the Uri SMIv2 textual convention defined in RFC 5017.";
- reference
- "RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
- RFC 3305: Report from the Joint W3C/IETF URI Planning Interest
- Group: Uniform Resource Identifiers (URIs), URLs,
- and Uniform Resource Names (URNs): Clarifications
- and Recommendations
- RFC 5017: MIB Textual Conventions for Uniform Resource
- Identifiers (URIs)";
- }
-
-}
+++ /dev/null
-// vi: set smarttab et sw=4 tabstop=4:
-module config-threads {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:threads";
- prefix "th";
-
- import config { prefix config; revision-date 2013-04-05; }
-
- revision "2013-05-02" {
- description
- "Add test";
- }
-
- extension java-class2 {
- description
- "YANG language extension carrying the fully-qualified name of
- a Java class. Code generation tools use the provided reference
- to tie a specific construct to its Java representation.";
-
- argument "name";
- }
-
- identity eventbus {
- description
- "Service representing an event bus. The service acts as message
- router between event producers and event consumers";
-
- base "config:service-type";
- th:java-class2 "com.google.common.eventbus.EventBus";
- }
-
-}
+++ /dev/null
-module test-config-files {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:config:test:files";
- prefix "it-duplicate";
-
- import config { prefix config; revision-date 2013-04-05; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
-
- description
- "Testing IMPL";
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity implementation {
- base config:module-type;
- config:java-name-prefix TestFileImpl;
- }
-
- identity netconf {
- base config:module-type;
- config:java-name-prefix NetconfTestFileImpl;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case implementation {
- when "/config:modules/config:module/config:type = 'implementation'";
-
- container dto-a {
- leaf simple-arg {
- type uint32;
- }
-
- leaf port {
- type inet:port-number;
- }
-
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case implementation {
- when "/config:modules/config:module/config:type = 'implementation'";
- // root runtime bean
- leaf created-sessions {
- type uint32;
- }
- }
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case netconf {
- when "/config:modules/config:module/config:type = 'netconf'";
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case netconf {
- when "/config:modules/config:module/config:type = 'netconf'";
- // root runtime bean
- leaf created-sessions2 {
- type uint32;
- }
-
- }
- }
-}
+++ /dev/null
-module test-config-files1 {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:config:test:files1";
- prefix "it-duplicate";
-
- import config { prefix config; revision-date 2013-04-05; }
- import ietf-inet-types { prefix inet; revision-date 2013-07-15;}
-
-
- description
- "Testing IMPL";
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity implementation1 {
- base config:module-type;
- config:java-name-prefix TestFiles1Impl;
- }
-
- identity netconf1 {
- base config:module-type;
- config:java-name-prefix NetconfTestFiles1Impl;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case implementation1 {
- when "/config:modules/config:module/config:type = 'implementation1'";
-
- container dto-a {
- leaf simple-arg {
- type uint32;
- }
-
- leaf port {
- type inet:port-number;
- }
-
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case implementation1 {
- when "/config:modules/config:module/config:type = 'implementation1'";
- // root runtime bean
- leaf created-sessions {
- type uint32;
- }
- }
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case netconf1 {
- when "/config:modules/config:module/config:type = 'netconf1'";
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case netconf1 {
- when "/config:modules/config:module/config:type = 'netconf1'";
- // root runtime bean
- leaf created-sessions2 {
- type uint32;
- }
-
- }
- }
-}
+++ /dev/null
-module config-threads-java {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:config:threads:java";
- prefix "th-java";
-
- import config-threads { prefix th2; revision-date 2013-04-09; }
- import config { prefix config; revision-date 2013-04-05; }
- import rpc-context { prefix rpcx; revision-date 2013-06-17; }
-
- description
- "This module contains the base YANG definitions for NS-OS
- thread services pure Java implementation.";
-
- revision "2013-04-05" {
- description
- "Updated to work with new anchors.";
- }
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity thread-rpc-context;
-
- identity eventbus {
- base config:module-type;
- config:provided-service "th2:eventbus";
- config:java-name-prefix EventBus;
- }
-
- identity async-eventbus {
- base config:module-type;
- config:provided-service "th2:eventbus";
- config:java-name-prefix AsyncEventBus;
- }
-
- identity threadfactory-naming {
- base config:module-type;
- config:provided-service "th2:threadfactory";
- config:java-name-prefix NamingThreadFactory;
- }
-
- identity threadpool-dynamic {
- base config:module-type;
- description "threadpool-dynamic description";
- config:provided-service "th2:threadpool";
- config:provided-service "th2:scheduled-threadpool";
- config:java-name-prefix DynamicThreadPool;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case eventbus {
- when "/config:modules/config:module/config:type = 'eventbus'";
- // No real configuration
- }
- }
-
- grouping async-eventbus-config-attrs {
- leaf cfg-attr {
- type string;
- }
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- container threadpool {
- uses config:service-ref {
- refine type {
- config:required-identity th2:threadpool;
- }
- }
- }
-
- container from-grouping {
- uses async-eventbus-config-attrs;
- }
- }
- }
- augment "/config:modules/config:module/config:state" {
- case async-eventbus {
- when "/config:modules/config:module/config:type = 'async-eventbus'";
- // simulate not having root runtime bean
- list event {
- config:inner-state-bean;
- key "name";
- leaf name {
- type string;
- }
- }
- }
- }
-
- typedef thread-state {
- type enumeration {
- enum "STARTED";
- enum "STOPPED";
- }
- description "Enum type holding state in which a thread can be.";
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case threadfactory-naming {
- when "/config:modules/config:module/config:type = 'threadfactory-naming'";
- leaf name-prefix {
- description "String that will be prefixed to each created thread. Suffix will be constructed from
- underscore (_) and auto-incremented index number.";
- type string;
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case threadfactory-naming {
- when "/config:modules/config:module/config:type = 'threadfactory-naming'";
- list thread {
- config:inner-state-bean;
- key "name";
- leaf name {
- type string;
- }
- // add rpc context
- rpcx:rpc-context-instance "thread-rpc-context";
-
- list stream {
- config:inner-state-bean;
- config:java-name-prefix ThreadStream;
- // no key – key will be generated by incrementing a counter
- leaf timestamp {
- type string;
- }
- leaf state {
- type thread-state;
- }
-
- container peer {
- leaf port {
- type uint32;
- default 179;
- }
- leaf core-size {
- type uint32;
- }
- }
-
- list inner-stream-list {
- leaf timestamp {
- type string;
- }
- }
-
- }
- }
-
- list stream {
- config:inner-state-bean;
-
- leaf timestamp {
- type string;
- }
- }
-
- // root runtime bean
- leaf created-sessions {
- type uint32;
- }
- }
- }
-
-
- rpc dump-stack {
- config:java-name-prefix dumpStack;
- input {
- uses rpcx:rpc-context-ref {
- refine context-instance {
- rpcx:rpc-context-instance thread-rpc-context;
- }
- }
- }
- }
-
- rpc sleep {
- input {
- uses rpcx:rpc-context-ref {
- refine context-instance {
- rpcx:rpc-context-instance thread-rpc-context;
- }
- }
- leaf millis {
- type uint32;
- }
- }
- output {
- leaf result {
- type thread-state;
- }
- }
- }
-
-
- augment "/config:modules/config:module/config:configuration" {
- case threadpool-dynamic {
- when "/config:modules/config:module/config:type = 'threadpool-dynamic'";
- container threadpool-dynamic {
- leaf core-size {
- type uint32;
- }
-
- leaf keep-alive {
- type uint32;
- units seconds;
- default 10;
- }
-
- leaf maximum-size {
- type uint32;
- description "maximum-size description";
- }
-
- leaf binary {
- type binary;
- }
-
- container threadfactory {
- description "threadfactory description";
- uses config:service-ref {
- refine type {
- mandatory true;
- config:required-identity th2:threadfactory;
- }
- }
- }
-
- leaf-list users {
- type string;
- }
-
- leaf-list users-numbers {
- type uint32;
- description "numbers of users description";
- }
- }
- }
- }
-
- augment "/config:modules/config:module/config:state" {
- case threadpool-dynamic {
- when "/config:modules/config:module/config:type = 'threadpool-dynamic'";
- container threadpool-dynamic {
- // root runtime bean
- leaf created-sessions {
- type uint32;
- }
- }
- }
- }
-
- identity threadpool-registry-impl {
- base config:module-type;
- config:java-name-prefix ThreadPoolRegistryImpl;
- }
-
- augment "/config:modules/config:module/config:configuration" {
- case threadpool-registry-impl {
- when "/config:modules/config:module/config:type = 'threadpool-registry-impl'";
-
- // list of dependencies:
- list threadpools {
- uses config:service-ref {
- refine type {
- mandatory true;
- config:required-identity th2:threadpool;
- }
- }
- }
- }
- }
-}
+++ /dev/null
-module config-threads {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:controller:config:threads";
- prefix "th";
-
- import config { prefix config; revision-date 2013-04-05; }
-
- description
- "This module contains the base YANG definitions for NS-OS
- thread-related services.";
-
- revision "2013-04-09" {
- description
- "Added eventbus service.";
- }
-
- revision "2013-04-05" {
- description
- "Updated with YANG extension for Java class specification.";
- }
-
- revision "2013-04-03" {
- description
- "Initial revision";
- }
-
- identity eventbus {
- description
- "Service representing an event bus. The service acts as message
- router between event producers and event consumers";
-
- base "config:service-type";
- config:java-class "com.google.common.eventbus.EventBus";
- }
-
- identity threadfactory {
- description
- "Service representing a ThreadFactory instance. It is directly
- useful in Java world, where various library pieces need to create
- threads and you may want to inject a customized thread
- implementation.";
-
- base "config:service-type";
- config:java-class "java.util.concurrent.ThreadFactory";
- }
-
- identity threadpool {
- description
- "A simple pool of threads able to execute work.";
-
- base "config:service-type";
- config:java-class "org.opendaylight.controller.config.threadpool.ThreadPool";
- }
-
- identity scheduled-threadpool {
- description
- "An extension of the simple pool of threads able to schedule
- work to be executed at some point in time.";
-
- base "threadpool";
- config:java-class "org.opendaylight.controller.config.threadpool.ScheduledThreadPool";
- }
-}
+++ /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>config-plugin-parent</artifactId>
- <version>0.9.0-SNAPSHOT</version>
- <relativePath>../config-plugin-parent</relativePath>
- </parent>
- <artifactId>yang-test-plugin</artifactId>
- <packaging>maven-plugin</packaging>
- <name>${project.artifactId}</name>
-
- <description>Remove generated source files, after new files generation, implementation is inserted.</description>
-
- <dependencies>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.maven</groupId>
- <artifactId>maven-plugin-api</artifactId>
- <version>3.3.3</version>
- </dependency>
- </dependencies>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.test.plugin;
-
-import java.io.File;
-import org.apache.maven.plugin.AbstractMojo;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
-
-/**
- * Delete all Module/ModuleFactory sources
- *
- * @goal delete-sources
- *
- * @phase initialize
- */
-public class DeleteSources extends AbstractMojo{
- /**
- * @parameter expression="${project.build.sourceDirectory}"
- * @readOnly
- * @required
- */
- private File directory;
-
- @Override
- public void execute() throws MojoExecutionException, MojoFailureException {
- if (directory == null || !directory.exists()) {
- super.getLog().error("Directory does not exists.");
- }
- File sourceDirectory = new File(directory.getPath() + Util.replaceDots(".org.opendaylight.controller.config.yang.test.impl"));
- if (sourceDirectory == null || !sourceDirectory.exists()) {
- super.getLog().error(String.format("Source directory does not exists %s", sourceDirectory.getPath()));
- }
- File[] sourceFiles = sourceDirectory.listFiles();
- for (File sourceFile: sourceFiles) {
- if(sourceFile.getName().endsWith("Module.java") || sourceFile.getName().endsWith("ModuleFactory.java")) {
- super.getLog().debug(String.format("Source file deleted: %s", sourceFile.getName()));
- sourceFile.delete();
- }
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.test.plugin;
-
-import com.google.common.io.Files;
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.util.regex.Pattern;
-import org.apache.maven.plugin.AbstractMojo;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
-
-/**
- * Add implementation code from stub.txt
- *
- * @goal process-sources
- *
- * @phase process-sources
- *
- */
-public class ProcessSources extends AbstractMojo{
- /**
- * @parameter expression="${project.build.sourceDirectory}"
- * @readOnly
- * @required
- */
- private File directory;
-
- @Override
- public void execute() throws MojoExecutionException, MojoFailureException {
- if (directory == null || !directory.exists()) {
- super.getLog().error("Directory does not exists.");
- }
- File sourceDirectory = new File(directory.getPath() + Util.replaceDots(".org.opendaylight.controller.config.yang.test.impl"));
- if (!sourceDirectory.exists()) {
- super.getLog().error(String.format("Source directory does not exists %s", sourceDirectory.getPath()));
- }
-
- File[] sourceFiles = sourceDirectory.listFiles();
- for (File sourceFile: sourceFiles) {
- if (sourceFile.getName().endsWith(".java")) {
- String sourceContent;
- try {
- sourceContent = Files.toString(sourceFile, StandardCharsets.UTF_8);
- } catch (IOException e) {
- getLog().error(String.format("Cannot read %s", sourceFile.getAbsolutePath()), e);
- continue;
- }
- if (sourceFile.getName().endsWith("Module.java") || sourceFile.getName().endsWith("ModuleFactory.java")) {
- File stubFile = new File(sourceFile.getPath().replace(".java", "Stub.txt"));
- if (stubFile.exists()) {
- String stubContent = null;
- try {
- stubContent = Files.toString(stubFile, StandardCharsets.UTF_8);
- } catch (IOException e) {
- getLog().error(String.format("Cannot read %s", stubFile.getAbsolutePath()), e);
- }
- if (stubContent != null) {
- sourceContent = rewriteStub(sourceContent, stubContent);
- }
- }
- }
- // remove copyright headers as they can contain timestamp
- sourceContent = removeCopyrights(sourceContent);
-
- // replace the file content
- try {
- Files.write(sourceContent, sourceFile, StandardCharsets.UTF_8);
- } catch (IOException e) {
- getLog().error(String.format("Cannot write %s", sourceFile.getAbsolutePath()), e);
- }
- }
-
- }
- }
-
- private static Pattern MULTILINE_COMMENT_PATTERN = Pattern.compile("/\\*.*\\*/", Pattern.MULTILINE | Pattern.DOTALL);
- private static String removeCopyrights(String source) {
- String target = MULTILINE_COMMENT_PATTERN.matcher(source).replaceAll("\n");
- //FileUtils.write(sourceFile, target);
- return target;
- }
-
- private static Pattern UNSUPPORTED_OP_PATTERN = Pattern.compile("^.*TODO.*\n.*throw new java.lang.UnsupportedOperationException.*$", Pattern.MULTILINE);
-
- private static String rewriteStub(String source, String replaceTODOWith) {
- String target = UNSUPPORTED_OP_PATTERN.matcher(source).replaceFirst(replaceTODOWith);
- return target;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.yang.test.plugin;
-
-import java.io.File;
-import java.util.regex.Matcher;
-
-public class Util {
-
- public static String replaceDots(String path) {
- path = path.replace(".", Matcher.quoteReplacement(File.separator));
- return path;
- }
-}