From: Tom Pantelis Date: Wed, 20 Jun 2018 22:42:09 +0000 (-0400) Subject: Remove CSS code X-Git-Tag: release/fluorine~71 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=ac6f2699cd0c1e340cc32e8f0d0ca94c8e9c0cc0 Remove CSS code JIRA: TSC-111 Change-Id: Ib74c1d3dfc029c2472b8834ae55ce05c8231d225 Signed-off-by: Tom Pantelis --- diff --git a/features/config-persister/features-config-persister/pom.xml b/features/config-persister/features-config-persister/pom.xml deleted file mode 100644 index 747b59c566..0000000000 --- a/features/config-persister/features-config-persister/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - feature-repo-parent - 3.1.0 - - - - org.opendaylight.controller - features-config-persister - 0.9.0-SNAPSHOT - feature - - - - ${project.groupId} - odl-config-manager-facade-xml - ${project.version} - xml - features - - - ${project.groupId} - odl-config-persister - ${project.version} - xml - features - - - ${project.groupId} - odl-config-persister-all - ${project.version} - xml - features - - - ${project.groupId} - odl-config-startup - ${project.version} - xml - features - - - - diff --git a/features/config-persister/odl-config-manager-facade-xml/pom.xml b/features/config-persister/odl-config-manager-facade-xml/pom.xml deleted file mode 100644 index ad736a3fc0..0000000000 --- a/features/config-persister/odl-config-manager-facade-xml/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - single-feature-parent - 3.1.0 - - - - org.opendaylight.controller - odl-config-manager-facade-xml - 0.9.0-SNAPSHOT - feature - - Opendaylight :: Config Persister:: Mapping for Config Subsystem - - - - ${project.groupId} - odl-config-core - ${project.version} - xml - features - - - ${project.groupId} - config-manager-facade-xml - ${project.version} - - - - diff --git a/features/config-persister/odl-config-persister-all/pom.xml b/features/config-persister/odl-config-persister-all/pom.xml deleted file mode 100644 index c657fbc472..0000000000 --- a/features/config-persister/odl-config-persister-all/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - single-feature-parent - 3.1.0 - - - - org.opendaylight.controller - odl-config-persister-all - 0.9.0-SNAPSHOT - feature - - OpenDaylight :: Config Persister:: All - - - - ${project.groupId} - odl-config-persister - ${project.version} - xml - features - - - ${project.groupId} - odl-config-startup - ${project.version} - xml - features - - - - diff --git a/features/config-persister/odl-config-persister/pom.xml b/features/config-persister/odl-config-persister/pom.xml deleted file mode 100644 index 884a3cfbe4..0000000000 --- a/features/config-persister/odl-config-persister/pom.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - single-feature-parent - 3.1.0 - - - - org.opendaylight.controller - odl-config-persister - 0.9.0-SNAPSHOT - feature - - OpenDaylight :: Config Persister - - - - - org.opendaylight.mdsal - mdsal-artifacts - 2.5.0-SNAPSHOT - pom - import - - - ${project.groupId} - config-artifacts - ${project.version} - pom - import - - - - - - - ${project.groupId} - odl-config-api - xml - features - - - ${project.groupId} - odl-config-core - xml - features - - - ${project.groupId} - odl-config-manager - xml - features - - - ${project.groupId} - odl-config-manager-facade-xml - xml - features - - - org.opendaylight.mdsal - odl-mdsal-binding-runtime - xml - features - - - ${project.groupId} - config-persister-feature-adapter - - - - org.apache.karaf - org.apache.karaf.util - ${karaf.version} - - - - diff --git a/features/config-persister/odl-config-startup/pom.xml b/features/config-persister/odl-config-startup/pom.xml deleted file mode 100644 index 96ba9b2caf..0000000000 --- a/features/config-persister/odl-config-startup/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - single-feature-parent - 3.1.0 - - - - org.opendaylight.controller - odl-config-startup - 0.9.0-SNAPSHOT - feature - - OpenDaylight :: Config Persister:: Config Startup - - - - ${project.groupId} - odl-config-persister - ${project.version} - xml - features - - - - diff --git a/features/config-persister/pom.xml b/features/config-persister/pom.xml deleted file mode 100644 index 7176170988..0000000000 --- a/features/config-persister/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.odlparent - odlparent-lite - 3.1.0 - - - - org.opendaylight.controller - features-config-persister-aggregator - 0.9.0-SNAPSHOT - pom - - - features-config-persister - odl-config-manager-facade-xml - odl-config-persister - odl-config-persister-all - odl-config-startup - - - - scm:git:http://git.opendaylight.org/gerrit/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL - - diff --git a/features/config/features-config/pom.xml b/features/config/features-config/pom.xml deleted file mode 100644 index f6640b8bc4..0000000000 --- a/features/config/features-config/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - feature-repo-parent - 3.1.0 - - - - org.opendaylight.controller - features-config - 0.9.0-SNAPSHOT - feature - - - - ${project.groupId} - odl-config-all - ${project.version} - xml - features - - - ${project.groupId} - odl-config-api - ${project.version} - xml - features - - - ${project.groupId} - odl-config-core - ${project.version} - xml - features - - - ${project.groupId} - odl-config-manager - ${project.version} - xml - features - - - ${project.groupId} - odl-config-netty-config-api - ${project.version} - xml - features - - - ${project.groupId} - odl-config-util - ${project.version} - xml - features - - - - diff --git a/features/config/odl-config-all/pom.xml b/features/config/odl-config-all/pom.xml deleted file mode 100644 index a720ad0d1d..0000000000 --- a/features/config/odl-config-all/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - single-feature-parent - 3.1.0 - - - - org.opendaylight.controller - odl-config-all - 0.9.0-SNAPSHOT - feature - - - - ${project.groupId} - odl-config-api - ${project.version} - xml - features - - - ${project.groupId} - odl-config-netty-config-api - ${project.version} - xml - features - - - ${project.groupId} - odl-config-core - ${project.version} - xml - features - - - ${project.groupId} - odl-config-manager - ${project.version} - xml - features - - - - diff --git a/features/config/odl-config-api/pom.xml b/features/config/odl-config-api/pom.xml deleted file mode 100644 index 0b9b8bafb4..0000000000 --- a/features/config/odl-config-api/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - single-feature-parent - 3.1.0 - - - - org.opendaylight.controller - odl-config-api - 0.9.0-SNAPSHOT - feature - - - - org.opendaylight.mdsal - odl-mdsal-binding-base - 2.5.0-SNAPSHOT - xml - features - - - ${project.groupId} - config-api - ${project.version} - - - - diff --git a/features/config/odl-config-core/pom.xml b/features/config/odl-config-core/pom.xml deleted file mode 100644 index bf45aabe84..0000000000 --- a/features/config/odl-config-core/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - single-feature-parent - 3.1.0 - - - - org.opendaylight.controller - odl-config-core - 0.9.0-SNAPSHOT - feature - - - - - org.opendaylight.mdsal - mdsal-artifacts - 2.5.0-SNAPSHOT - pom - import - - - org.opendaylight.controller - config-artifacts - ${project.version} - pom - import - - - - - - - org.opendaylight.mdsal - odl-mdsal-binding-runtime - xml - features - - - ${project.groupId} - odl-config-util - xml - features - - - ${project.groupId} - yang-jmx-generator - - - ${project.groupId} - shutdown-api - - - ${project.groupId} - shutdown-impl - - - - diff --git a/features/config/odl-config-manager/pom.xml b/features/config/odl-config-manager/pom.xml deleted file mode 100644 index 53d6527a7f..0000000000 --- a/features/config/odl-config-manager/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - single-feature-parent - 3.1.0 - - - - org.opendaylight.controller - odl-config-manager - 0.9.0-SNAPSHOT - feature - - - - ${project.groupId} - odl-config-core - ${project.version} - xml - features - - - ${project.groupId} - config-manager - ${project.version} - - - - diff --git a/features/config/odl-config-manager/src/main/feature/feature.xml b/features/config/odl-config-manager/src/main/feature/feature.xml deleted file mode 100644 index c5c322ef1b..0000000000 --- a/features/config/odl-config-manager/src/main/feature/feature.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - mvn:org.opendaylight.controller/odl-config-core/${project.version}/xml/features - - mvn:org.opendaylight.controller/config-manager/${project.version} - - diff --git a/features/config/odl-config-netty-config-api/pom.xml b/features/config/odl-config-netty-config-api/pom.xml deleted file mode 100644 index 297d215f93..0000000000 --- a/features/config/odl-config-netty-config-api/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - single-feature-parent - 3.1.0 - - - - org.opendaylight.controller - odl-config-netty-config-api - 0.9.0-SNAPSHOT - feature - - - - ${project.groupId} - odl-config-api - ${project.version} - xml - features - - - org.opendaylight.odlparent - odl-netty-4 - 3.1.0 - xml - features - - - ${project.groupId} - netty-config-api - ${project.version} - - - - diff --git a/features/config/odl-config-netty-config-api/src/main/feature/feature.xml b/features/config/odl-config-netty-config-api/src/main/feature/feature.xml deleted file mode 100644 index f0137072a4..0000000000 --- a/features/config/odl-config-netty-config-api/src/main/feature/feature.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - odl-netty-4 - - diff --git a/features/config/odl-config-util/pom.xml b/features/config/odl-config-util/pom.xml deleted file mode 100644 index 1ada18620c..0000000000 --- a/features/config/odl-config-util/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.odlparent - single-feature-parent - 3.1.0 - - - - org.opendaylight.controller - odl-config-util - 0.9.0-SNAPSHOT - feature - - - - - org.opendaylight.yangtools - yangtools-artifacts - 2.0.5 - pom - import - - - org.opendaylight.controller - config-artifacts - ${project.version} - pom - import - - - - - - - org.opendaylight.yangtools - odl-yangtools-data-api - xml - features - - - ${project.groupId} - odl-config-api - xml - features - - - ${project.groupId} - config-util - - - - diff --git a/features/config/odl-config-util/src/main/feature/feature.xml b/features/config/odl-config-util/src/main/feature/feature.xml deleted file mode 100644 index a48cd9f8f6..0000000000 --- a/features/config/odl-config-util/src/main/feature/feature.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - odl-yangtools-data-api - - diff --git a/features/config/pom.xml b/features/config/pom.xml deleted file mode 100644 index e42fc8086f..0000000000 --- a/features/config/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.odlparent - odlparent-lite - 3.1.0 - - - - org.opendaylight.controller - features-config-aggregator - 0.9.0-SNAPSHOT - pom - - - features-config - odl-config-all - odl-config-api - odl-config-core - odl-config-manager - odl-config-netty-config-api - odl-config-util - - - - scm:git:http://git.opendaylight.org/gerrit/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL - - diff --git a/features/pom.xml b/features/pom.xml index 29f12e85e5..2971d590db 100644 --- a/features/pom.xml +++ b/features/pom.xml @@ -14,8 +14,6 @@ pom - config - config-persister config-netty mdsal extras diff --git a/opendaylight/config/config-api/pom.xml b/opendaylight/config/config-api/pom.xml deleted file mode 100644 index 4d87288194..0000000000 --- a/opendaylight/config/config-api/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - binding-parent - 0.13.0-SNAPSHOT - - - - org.opendaylight.controller - 0.9.0-SNAPSHOT - config-api - bundle - ${project.artifactId} - - - - org.opendaylight.mdsal - yang-binding - - - org.opendaylight.yangtools - yang-common - - - org.osgi - org.osgi.core - - - compile - - - org.opendaylight.yangtools - mockito-configuration - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - org.apache.felix - maven-bundle-plugin - - - org.opendaylight.yangtools - yang-maven-plugin - - - - diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConfigRegistry.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConfigRegistry.java deleted file mode 100644 index a3c747bafb..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConfigRegistry.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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 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 getAvailableModuleNames(); -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConfigSystemService.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConfigSystemService.java deleted file mode 100644 index 9a1470ac3e..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConfigSystemService.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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(); -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConfigTransactionController.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConfigTransactionController.java deleted file mode 100644 index c234da7df5..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConfigTransactionController.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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 getAvailableModuleNames(); -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConflictingVersionException.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConflictingVersionException.java deleted file mode 100644 index 9e3c5016ce..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ConflictingVersionException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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); - } - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/DependencyResolver.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/DependencyResolver.java deleted file mode 100644 index e9b63e6f05..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/DependencyResolver.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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 { - - /** - * 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 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 resolveInstance(Class expectedType, ObjectName objectName, JmxAttribute jmxAttribute); - - /** - * To be used during commit phase to resolve identity-ref config attributes. - * - * @return actual class object generated from identity - */ - Class resolveIdentity(IdentityAttributeRef identityRef, - Class expectedBaseClass); - - /** - * Validate identity-ref config attribute. - */ - void validateIdentity(IdentityAttributeRef identityRef, Class 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 - * type of proxy for type safe return value - * @return instance of MXBean proxy - */ - T newMXBeanProxy(ObjectName objectName, Class 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); -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/DependencyResolverFactory.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/DependencyResolverFactory.java deleted file mode 100644 index 77f40c84fd..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/DependencyResolverFactory.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * 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); - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/DynamicMBeanWithInstance.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/DynamicMBeanWithInstance.java deleted file mode 100644 index 61a1148d86..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/DynamicMBeanWithInstance.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/IdentityAttributeRef.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/IdentityAttributeRef.java deleted file mode 100644 index 735a6e1d27..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/IdentityAttributeRef.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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 Class resolveIdentity(final DependencyResolver resolver, - final Class baseIdentity) { - return resolver.resolveIdentity(this, baseIdentity); - } - - public void validateIdentity(final DependencyResolver resolver, - final Class 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(); - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/JmxAttribute.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/JmxAttribute.java deleted file mode 100644 index 7b67b95d37..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/JmxAttribute.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 + "'}"; - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/JmxAttributeValidationException.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/JmxAttributeValidationException.java deleted file mode 100644 index c7b1ed3348..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/JmxAttributeValidationException.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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 attributeNames; - - public JmxAttributeValidationException(final JmxAttribute jmxAttribute) { - this(Arrays.asList(jmxAttribute)); - } - - public JmxAttributeValidationException(final List jmxAttribute) { - this.attributeNames = jmxAttribute; - } - - public JmxAttributeValidationException(final String message, - final JmxAttribute jmxAttribute) { - this(message, Arrays.asList(jmxAttribute)); - } - - public JmxAttributeValidationException(final String message, - final List 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 jmxAttributes) { - super(message, cause); - this.attributeNames = jmxAttributes; - } - - public List getAttributeNames() { - return attributeNames; - } - - public static T checkNotNull(final T param, final JmxAttribute jmxAttribute) { - String message = "is null"; - return checkNotNull(param, message, jmxAttribute); - } - - public static 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); - } - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/LookupRegistry.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/LookupRegistry.java deleted file mode 100644 index 0492268338..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/LookupRegistry.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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 lookupConfigBeans(); - - /** - * Find modules with given module name. - * - * @param moduleName - * name of module - * @return objectNames - */ - Set 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 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 getAvailableModuleFactoryQNames(); - - /** - * Find all runtime beans. - * - * @return objectNames - */ - Set lookupRuntimeBeans(); - - /** - * Find all runtime of specified module. - * - * @param moduleName - * of bean - * @param instanceName - * of bean - * @return objectNames - */ - Set lookupRuntimeBeans(String moduleName, String instanceName); -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ModuleFactoryNotFoundException.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ModuleFactoryNotFoundException.java deleted file mode 100644 index 029367ff1b..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ModuleFactoryNotFoundException.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ModuleIdentifier.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ModuleIdentifier.java deleted file mode 100644 index 600c9eeaec..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ModuleIdentifier.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 + '\'' + '}'; - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/RuntimeBeanRegistratorAwareModule.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/RuntimeBeanRegistratorAwareModule.java deleted file mode 100644 index 2b46ac79d7..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/RuntimeBeanRegistratorAwareModule.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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); - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ServiceReferenceReadableRegistry.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ServiceReferenceReadableRegistry.java deleted file mode 100644 index f4ee78784f..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ServiceReferenceReadableRegistry.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * 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> 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 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 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; -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ServiceReferenceWritableRegistry.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ServiceReferenceWritableRegistry.java deleted file mode 100644 index 77fc8dc3c7..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ServiceReferenceWritableRegistry.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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; -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ValidationException.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ValidationException.java deleted file mode 100644 index 9daacd16dc..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/ValidationException.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * 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> failedValidations; - - public ValidationException( - final Map> failedValidations) { - super(failedValidations.toString()); - this.failedValidations = Collections.unmodifiableMap(failedValidations); - } - - public static ValidationException createFromCollectedValidationExceptions( - final List collectedExceptions) { - Map> failedValidations = new HashMap<>(); - for (ValidationException ve : collectedExceptions) { - for (Entry> outerEntry : ve.getFailedValidations() - .entrySet()) { - for (Entry innerEntry : outerEntry.getValue().entrySet()) { - String moduleName = outerEntry.getKey(); - String instanceName = innerEntry.getKey(); - ExceptionMessageWithStackTrace ex = innerEntry.getValue(); - Map 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> failedValidations = new HashMap<>(); - Map innerMap = new HashMap<>(); - - failedValidations.put(moduleIdentifier.getFactoryName(), innerMap); - innerMap.put(moduleIdentifier.getInstanceName(), new ExceptionMessageWithStackTrace(exception)); - return new ValidationException(failedValidations); - } - - public Map> 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; - } - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/AbstractServiceInterface.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/AbstractServiceInterface.java deleted file mode 100644 index 0b1d7872fc..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/AbstractServiceInterface.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * 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 { -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/Description.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/Description.java deleted file mode 100644 index 77362a890e..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/Description.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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(); -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/RequireInterface.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/RequireInterface.java deleted file mode 100644 index 0e8f6fd736..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/RequireInterface.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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. - * - *

- * Example:
- * - * - * {@literal @}RequireInterface(value = ThreadPoolServiceInterface.class, optional = false)
- * void setThreadPool(ObjectName on); - *
- */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -public @interface RequireInterface { - - /** - * Declares dependency on service interface. - */ - Class value(); - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/ServiceInterfaceAnnotation.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/ServiceInterfaceAnnotation.java deleted file mode 100644 index 1adf6c5478..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/annotations/ServiceInterfaceAnnotation.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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(); -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/CommitStatus.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/CommitStatus.java deleted file mode 100644 index ed9164d151..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/CommitStatus.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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 newInstances; - private final List reusedInstances; - private final List recreatedInstances; - - /** - * Constructor. - * - * @param newInstances - * newly created instances - * @param reusedInstances - * reused instances - * @param recreatedInstances - * recreated instances - */ - @ConstructorProperties({ "newInstances", "reusedInstances", "recreatedInstances" }) - public CommitStatus(final List newInstances, final List reusedInstances, - final List recreatedInstances) { - this.newInstances = Collections.unmodifiableList(newInstances); - this.reusedInstances = Collections.unmodifiableList(reusedInstances); - this.recreatedInstances = Collections.unmodifiableList(recreatedInstances); - } - - public List getNewInstances() { - return newInstances; - } - - public List getReusedInstances() { - return reusedInstances; - } - - public List 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 + "]"; - } - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ConfigRegistryMXBean.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ConfigRegistryMXBean.java deleted file mode 100644 index af02f14a4b..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ConfigRegistryMXBean.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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.
- * 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 { - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ConfigTransactionControllerMXBean.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ConfigTransactionControllerMXBean.java deleted file mode 100644 index b59bf2d736..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ConfigTransactionControllerMXBean.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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 ConfigMBeanServer 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.
- * 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 { - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ObjectNameUtil.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ObjectNameUtil.java deleted file mode 100644 index 3b7858c477..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ObjectNameUtil.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * 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 attribs) { - Hashtable 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 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 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 onParams = createModuleMap(moduleName, instanceName); - return createON(ON_DOMAIN, onParams); - } - - public static ObjectName createReadOnlyServiceON(final String serviceQName, final String refName) { - Map onParams = createServiceMap(serviceQName, refName); - return createON(ON_DOMAIN, onParams); - } - - public static ObjectName createTransactionServiceON(final String transactionName, final String serviceQName, - final String refName) { - Map 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 createServiceON(final String transactionName, final String serviceQName, - final String refName) { - Map result = new HashMap<>(createServiceMap(serviceQName, refName)); - result.put(TRANSACTION_NAME_KEY, transactionName); - return result; - } - - private static Map createServiceMap(final String serviceQName, final String refName) { - Map 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 createModuleMap(final String moduleName, final String instanceName) { - Map 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 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 allProperties = getAdditionalProperties(inputON); - for (Entry 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 additionalProperties = getAdditionalProperties(inputON); - additionalProperties.put(TRANSACTION_NAME_KEY, transactionName); - return createON(inputON.getDomain(), additionalProperties); - - } - - private static void assertDoesNotContain(final Map 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 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 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 blacklist = new HashSet<>( - Arrays.asList(MODULE_FACTORY_NAME_KEY, INSTANCE_NAME_KEY, TYPE_KEY)); - - public static Map getAdditionalPropertiesOfRuntimeBeanName(final ObjectName on) { - checkType(on, TYPE_RUNTIME_BEAN); - Map allProperties = getAdditionalProperties(on); - Map result = new HashMap<>(); - for (Entry entry : allProperties.entrySet()) { - if (!blacklist.contains(entry.getKey())) { - result.put(entry.getKey(), entry.getValue()); - } - } - return result; - } - - public static Map getAdditionalProperties(final ObjectName on) { - Map keyPropertyList = on.getKeyPropertyList(); - Map result = new HashMap<>(); - for (Entry 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)); - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ServiceReferenceMXBean.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ServiceReferenceMXBean.java deleted file mode 100644 index 7ecf758bda..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ServiceReferenceMXBean.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/constants/ConfigRegistryConstants.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/constants/ConfigRegistryConstants.java deleted file mode 100644 index de4b582abf..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/constants/ConfigRegistryConstants.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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); - } - - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/notifications/CommitJMXNotification.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/notifications/CommitJMXNotification.java deleted file mode 100644 index 2c79470563..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/notifications/CommitJMXNotification.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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; -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/notifications/ConfigJMXNotification.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/notifications/ConfigJMXNotification.java deleted file mode 100644 index 0d804c5973..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/notifications/ConfigJMXNotification.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/osgi/ServiceNotFoundException.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/osgi/ServiceNotFoundException.java deleted file mode 100644 index 2c6d76a9d6..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/osgi/ServiceNotFoundException.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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); - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/osgi/WaitingServiceTracker.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/osgi/WaitingServiceTracker.java deleted file mode 100644 index 5cb99d34d4..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/osgi/WaitingServiceTracker.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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 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 tracker; - private final Class serviceInterface; - - private WaitingServiceTracker(final Class serviceInterface, final ServiceTracker 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 WaitingServiceTracker create(@Nonnull final Class serviceInterface, - @Nonnull final BundleContext context) { - ServiceTracker 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 WaitingServiceTracker create(@Nonnull final Class serviceInterface, - @Nonnull final BundleContext context, @Nonnull final String filter) { - String newFilter = String.format("(&(%s=%s)%s)", Constants.OBJECTCLASS, serviceInterface.getName(), filter); - try { - ServiceTracker 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(); - } -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/runtime/HierarchicalRuntimeBeanRegistration.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/runtime/HierarchicalRuntimeBeanRegistration.java deleted file mode 100644 index 185c13c9f9..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/runtime/HierarchicalRuntimeBeanRegistration.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/runtime/RootRuntimeBeanRegistrator.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/runtime/RootRuntimeBeanRegistrator.java deleted file mode 100644 index 76949bfc6d..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/runtime/RootRuntimeBeanRegistrator.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/runtime/RuntimeBean.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/runtime/RuntimeBean.java deleted file mode 100644 index b4a7ed16b3..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/runtime/RuntimeBean.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * 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 { -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/spi/AbstractModule.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/spi/AbstractModule.java deleted file mode 100644 index 29a8ce3ebe..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/spi/AbstractModule.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * 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 - * Type of module implementation. Enables easier implementation for - * the isSame() method - */ -public abstract class AbstractModule> - 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(); -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/spi/Module.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/spi/Module.java deleted file mode 100644 index ad4f2d36c4..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/spi/Module.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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. - *

- * In order to guide dependency resolution, the setter method should be - * annotated with - * {@link org.opendaylight.controller.config.api.annotations.RequireInterface}. - *

- *

- * Thread safety note: implementations of this interface are not required to be - * thread safe as thread safety is enforced by configuration manager. - *

- */ -@NotThreadSafe -public interface Module extends Identifiable { - /** - * 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); -} diff --git a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/spi/ModuleFactory.java b/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/spi/ModuleFactory.java deleted file mode 100644 index 37dcd65d0a..0000000000 --- a/opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/spi/ModuleFactory.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * 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. - * - *

- * 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. - * - *

- * 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 serviceInterface); - - Set> 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 getDefaultModules(DependencyResolverFactory dependencyResolverFactory, - BundleContext bundleContext); -} diff --git a/opendaylight/config/config-api/src/main/yang/config@2013-04-05.yang b/opendaylight/config/config-api/src/main/yang/config@2013-04-05.yang deleted file mode 100644 index 3d06dd6abb..0000000000 --- a/opendaylight/config/config-api/src/main/yang/config@2013-04-05.yang +++ /dev/null @@ -1,198 +0,0 @@ -// 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"; - } - } - } - } - } - - -} diff --git a/opendaylight/config/config-api/src/main/yang/rpc-context@2013-06-17.yang b/opendaylight/config/config-api/src/main/yang/rpc-context@2013-06-17.yang deleted file mode 100644 index 5c8b113412..0000000000 --- a/opendaylight/config/config-api/src/main/yang/rpc-context@2013-06-17.yang +++ /dev/null @@ -1,32 +0,0 @@ -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"; - } -} diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/IdentityAttributeRefTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/IdentityAttributeRefTest.java deleted file mode 100644 index 5daac19b76..0000000000 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/IdentityAttributeRefTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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 {} -} diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/JmxAttributeTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/JmxAttributeTest.java deleted file mode 100644 index cb0bbafb3a..0000000000 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/JmxAttributeTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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()); - } -} diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/JmxAttributeValidationExceptionTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/JmxAttributeValidationExceptionTest.java deleted file mode 100644 index c39710acd7..0000000000 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/JmxAttributeValidationExceptionTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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 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 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()); - } -} diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ModuleIdentifierTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ModuleIdentifierTest.java deleted file mode 100644 index 2e78e69ed4..0000000000 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ModuleIdentifierTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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()); - } -} diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ValidationExceptionTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ValidationExceptionTest.java deleted file mode 100644 index 11b3f0be7e..0000000000 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/ValidationExceptionTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * 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> failedMap = collected - .getFailedValidations(); - assertEquals(1, failedMap.size()); - assertTrue(failedMap.containsKey("module")); - - Map 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); - } -} diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/CommitStatusTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/CommitStatusTest.java deleted file mode 100644 index abea9c5afd..0000000000 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/CommitStatusTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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 newInst = new ArrayList<>(); - List reusedInst = new ArrayList<>(); - List 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 newInst2 = new ArrayList<>(); - List reusedInst2 = new ArrayList<>(); - List 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); - } -} diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/ConfigRegistryConstantsTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/ConfigRegistryConstantsTest.java deleted file mode 100644 index 5fb50f700b..0000000000 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/ConfigRegistryConstantsTest.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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"); - } -} diff --git a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/ObjectNameUtilTest.java b/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/ObjectNameUtilTest.java deleted file mode 100644 index 7498561eb2..0000000000 --- a/opendaylight/config/config-api/src/test/java/org/opendaylight/controller/config/api/jmx/ObjectNameUtilTest.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * 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 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 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 map = new HashMap<>(); - ObjectNameUtil.createON(">}+!#", map); - } -} diff --git a/opendaylight/config/config-artifacts/pom.xml b/opendaylight/config/config-artifacts/pom.xml index 4cf2226669..6c21ae0735 100644 --- a/opendaylight/config/config-artifacts/pom.xml +++ b/opendaylight/config/config-artifacts/pom.xml @@ -18,100 +18,9 @@ - ${project.groupId} - config-api - ${project.version} - - - ${project.groupId} - config-manager - ${project.version} - - - ${project.groupId} - config-manager - ${project.version} - test-jar - test - - - ${project.groupId} - config-netty-config - ${project.version} - - - ${project.groupId} - config-persister-api - ${project.version} - - - ${project.groupId} - config-persister-api - ${project.version} - test-jar - test - - - ${project.groupId} - config-persister-directory-adapter - ${project.version} - - - ${project.groupId} - config-persister-directory-autodetect-adapter - ${project.version} - - - ${project.groupId} - config-persister-directory-xml-adapter - ${project.version} - - - ${project.groupId} - config-persister-feature-adapter - ${project.version} - - - ${project.groupId} - config-persister-file-adapter - ${project.version} - - - ${project.groupId} - config-persister-file-xml-adapter - ${project.version} - - - ${project.groupId} - config-plugin-parent - ${project.version} - - - ${project.groupId} - config-persister-impl - ${project.version} - - - org.opendaylight.controller - config-manager-facade-xml - ${project.version} - - - ${project.groupId} - config-util - ${project.version} - - - ${project.groupId} - config-util - ${project.version} - test-jar - test - - - ${project.groupId} - netty-config-api - ${project.version} + ${project.groupId} + netty-config-api + ${project.version} ${project.groupId} @@ -128,16 +37,6 @@ netty-timer-config ${project.version} - - ${project.groupId} - shutdown-api - ${project.version} - - - ${project.groupId} - shutdown-impl - ${project.version} - ${project.groupId} threadpool-config-api @@ -148,142 +47,6 @@ threadpool-config-impl ${project.version} - - ${project.groupId} - yang-jmx-generator - ${project.version} - - - ${project.groupId} - yang-jmx-generator - ${project.version} - test-jar - test - - - ${project.groupId} - yang-jmx-generator-plugin - ${project.version} - - - ${project.groupId} - yang-store-api - ${project.version} - - - ${project.groupId} - yang-store-impl - ${project.version} - - - ${project.groupId} - yang-test - ${project.version} - - - - ${project.groupId} - features-config - ${project.version} - features - xml - runtime - - - ${project.groupId} - features-config-netty - ${project.version} - features - xml - runtime - - - ${project.groupId} - features-config-persister - ${project.version} - features - xml - runtime - - - ${project.groupId} - config-netty-features - ${project.version} - features - xml - runtime - - - - ${project.groupId} - odl-config-api - ${project.version} - features - xml - - - ${project.groupId} - odl-config-core - ${project.version} - features - xml - - - ${project.groupId} - odl-config-manager - ${project.version} - features - xml - - - ${project.groupId} - odl-config-manager-facade-xml - ${project.version} - features - xml - - - ${project.groupId} - odl-config-netty - ${project.version} - features - xml - - - ${project.groupId} - odl-config-netty-config-api - ${project.version} - features - xml - - - ${project.groupId} - odl-config-persister - ${project.version} - features - xml - - - ${project.groupId} - odl-config-persister-all - ${project.version} - features - xml - - - ${project.groupId} - odl-config-startup - ${project.version} - features - xml - - - ${project.groupId} - odl-config-util - ${project.version} - features - xml - diff --git a/opendaylight/config/config-filtering-parent/pom.xml b/opendaylight/config/config-filtering-parent/pom.xml deleted file mode 100644 index b2007d4d24..0000000000 --- a/opendaylight/config/config-filtering-parent/pom.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - - - org.opendaylight.controller - config-parent - 0.9.0-SNAPSHOT - ../config-parent - - - 4.0.0 - org.opendaylight.controller - config-filtering-parent - pom - - - src/main/config - default-config.xml - ${config.dir}/${config.filename} - ${project.build.directory}/generated-config - ${generated.config.dir}/${config.filename} - - - - - apply-filtering-before-attaching-config - - - ${config.file} - - - - - - - maven-resources-plugin - - - copy-resources - validate - - copy-resources - - - ${generated.config.dir} - - - ${config.dir} - true - - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${generated.config.file} - xml - config - - - - - - - - - - - org.apache.maven.plugins - maven-resources-plugin - - - - - - diff --git a/opendaylight/config/config-it-base/pom.xml b/opendaylight/config/config-it-base/pom.xml deleted file mode 100644 index 4424c51d76..0000000000 --- a/opendaylight/config/config-it-base/pom.xml +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - org.opendaylight.controller - config-parent - 0.9.0-SNAPSHOT - ../config-parent - - 4.0.0 - config-it-base - bundle - - - 3.1.0 - - - - - - org.opendaylight.controller - config-artifacts - ${project.version} - pom - import - - - - - - org.opendaylight.controller - config-util - - - org.opendaylight.odlparent - opendaylight-karaf-empty - 3.1.0 - zip - - - - - org.ops4j.pax.exam - pax-exam-container-karaf - compile - - - org.ops4j.pax.exam - pax-exam-junit4 - compile - - - org.ops4j.pax.exam - pax-exam - compile - - - org.ops4j.pax.url - pax-url-aether - compile - - - javax.inject - javax.inject - compile - - - org.apache.karaf.features - org.apache.karaf.features.core - ${karaf.version} - compile - - - org.osgi - org.osgi.core - compile - - - junit - junit - compile - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - - - src/main/resources - true - - - - diff --git a/opendaylight/config/config-it-base/src/main/java/org/opendaylight/controller/config/it/base/AbstractConfigTestBase.java b/opendaylight/config/config-it-base/src/main/java/org/opendaylight/controller/config/it/base/AbstractConfigTestBase.java deleted file mode 100644 index ee2cf1db7f..0000000000 --- a/opendaylight/config/config-it-base/src/main/java/org/opendaylight/controller/config/it/base/AbstractConfigTestBase.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * 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); - } - }; -} diff --git a/opendaylight/config/config-it-base/src/main/resources/abstractconfigtestbase.properties b/opendaylight/config/config-it-base/src/main/resources/abstractconfigtestbase.properties deleted file mode 100644 index e5cee97046..0000000000 --- a/opendaylight/config/config-it-base/src/main/resources/abstractconfigtestbase.properties +++ /dev/null @@ -1 +0,0 @@ -karaf.distro.version=${opendaylight.karaf.version} diff --git a/opendaylight/config/config-manager-facade-xml/pom.xml b/opendaylight/config/config-manager-facade-xml/pom.xml deleted file mode 100644 index f41b63424c..0000000000 --- a/opendaylight/config/config-manager-facade-xml/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - 4.0.0 - - config-subsystem - org.opendaylight.controller - 0.9.0-SNAPSHOT - - config-manager-facade-xml - ${project.artifactId} - bundle - - - - org.opendaylight.controller - config-util - - - org.opendaylight.controller - yang-jmx-generator - - - org.opendaylight.yangtools - yang-data-api - - - org.opendaylight.mdsal - mdsal-binding-generator-impl - - - org.slf4j - slf4j-api - - - junit - junit - test - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.config.facade.xml.osgi.YangStoreActivator - - - - - - - diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/CandidateDatastoreQueryStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/CandidateDatastoreQueryStrategy.java deleted file mode 100644 index 3f2fcfaf6f..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/CandidateDatastoreQueryStrategy.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 queryInstances(final ConfigRegistryClient configRegistryClient) { - ObjectName on = transactionProvider.getOrCreateTransaction(); - ConfigTransactionClient proxy = configRegistryClient.getConfigTransactionClient(on); - return proxy.lookupConfigBeans(); - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/ConfigExecution.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/ConfigExecution.java deleted file mode 100644 index d6179c793b..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/ConfigExecution.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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> 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> 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/ConfigSubsystemFacade.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/ConfigSubsystemFacade.java deleted file mode 100644 index 4ee3c7ae6e..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/ConfigSubsystemFacade.java +++ /dev/null @@ -1,461 +0,0 @@ -/* - * 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. - * - *

- * 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 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.absent()); - final Set 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>> namespaceToServiceNameToRefNameToInstance = - services.getNamespaceToServiceNameToRefNameToInstance(); - - for (Map.Entry>> - namespaceToServiceToRefEntry : namespaceToServiceNameToRefNameToInstance - .entrySet()) { - for (Map.Entry> serviceToRefEntry - : namespaceToServiceToRefEntry.getValue().entrySet()) { - String qnameOfService = getQname(ta, namespaceToServiceToRefEntry.getKey(), serviceToRefEntry.getKey()); - Map refNameToInstance = serviceToRefEntry.getValue(); - - for (Map.Entry 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 modulesToResolved : execution.getResolvedXmlElements(ta) - .values()) { - - for (Map.Entry 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 modulesToResolved : execution.getModulesDefinition(ta) - .values()) { - for (Map.Entry 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> factories = transformMbeToModuleConfigs( - snapshot.getModuleMXBeanEntryMap()); - Map, IdentityMapping>> identitiesMap = - transformIdentities(snapshot.getModules()); - return new Config(factories, identitiesMap, snapshot.getEnumResolver()); - } - - private static Map, IdentityMapping>> transformIdentities( - final Set modules) { - Map, IdentityMapping>> mappedIds = new HashMap<>(); - for (Module module : modules) { - String namespace = module.getNamespace().toString(); - Map, IdentityMapping> revisionsByNamespace = mappedIds.computeIfAbsent(namespace, - k -> new HashMap<>()); - - Optional 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> transformMbeToModuleConfigs( - final Map> mbeanentries) { - return transformMbeToModuleConfigs(configRegistryClient, mbeanentries); - } - - public Map> transformMbeToModuleConfigs( - final BeanReader reader, - final Map> mbeanentries) { - Map> namespaceToModuleNameToModuleConfig = new HashMap<>(); - - for (Map.Entry> namespaceToModuleToMbe : mbeanentries.entrySet()) { - for (Map.Entry 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 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> createModuleRuntimes( - final ConfigRegistryClient client, - final Map> mbeanentries) { - Map> retVal = new HashMap<>(); - - for (Map.Entry> namespaceToModuleEntry : mbeanentries.entrySet()) { - - Map innerMap = new HashMap<>(); - Map entriesFromNamespace = namespaceToModuleEntry.getValue(); - for (Map.Entry moduleToMXEntry : entriesFromNamespace.entrySet()) { - - ModuleMXBeanEntry mbe = moduleToMXEntry.getValue(); - - Map 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 cache) { - Map 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 createJmxToYangMap(final List children) { - Map 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 runtimeBeans = configRegistryClient.lookupRuntimeBeans(); - - final Set configBeans = Datastore - .getInstanceQueryStrategy(Datastore.running, transactionProvider) - .queryInstances(configRegistryClient); - - final Map> moduleRuntimes = createModuleRuntimes(configRegistryClient, - yangStoreService.getModuleMXBeanEntryMap()); - - final YangStoreContext yangStoreSnapshot = yangStoreService.getCurrentSnapshot(); - final Map> 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; - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/ConfigSubsystemFacadeFactory.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/ConfigSubsystemFacadeFactory.java deleted file mode 100644 index 1d680a95ad..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/ConfigSubsystemFacadeFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 getCurrentCapabilities() { - Set modules = yangStoreService.getModules(); - final Set capabilities = Sets.newHashSet(); - for (Module module : modules) { - capabilities.add(new YangModuleCapability(module, yangStoreService.getModuleSource( - RevisionSourceIdentifier.create(module.getName(), module.getRevision())))); - } - return capabilities; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/Datastore.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/Datastore.java deleted file mode 100644 index 93df25ffc6..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/Datastore.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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); - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/DatastoreQueryStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/DatastoreQueryStrategy.java deleted file mode 100644 index 5be09c6598..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/DatastoreQueryStrategy.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * 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 queryInstances(ConfigRegistryClient configRegistryClient); -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/RpcFacade.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/RpcFacade.java deleted file mode 100644 index aaa773ee51..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/RpcFacade.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * 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> map = new HashMap<>(); - - for (final Map.Entry> namespaceToModuleEntry : yangStoreService - .getModuleMXBeanEntryMap().entrySet()) { - - Map namespaceToModules = map.computeIfAbsent(namespaceToModuleEntry.getKey(), - k -> new HashMap<>()); - - for (final Map.Entry 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 attributes = instanceRuntimeRpc.fromXml(xml); - attributes = sortAttributes(attributes, xml); - - return new OperationExecution(on, instanceRuntimeRpc.getName(), attributes, instanceRuntimeRpc.getReturnType(), - namespace); - } - - private Map sortAttributes(final Map attributes, - final XmlElement xml) { - final Map 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> 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 attributes; - private final AttributeIfc returnType; - private final String namespace; - - public OperationExecution(final ObjectName on, final String name, - final Map 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 getAttributes() { - return attributes; - } - - public AttributeIfc getReturnType() { - return returnType; - } - - public String getNamespace() { - return namespace; - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/RunningDatastoreQueryStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/RunningDatastoreQueryStrategy.java deleted file mode 100644 index 28f203b4d9..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/RunningDatastoreQueryStrategy.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 queryInstances(final ConfigRegistryClient configRegistryClient) { - ObjectName on = transactionProvider.getOrCreateReadTransaction(); - ConfigTransactionClient proxy = configRegistryClient.getConfigTransactionClient(on); - return proxy.lookupConfigBeans(); - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/TestOption.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/TestOption.java deleted file mode 100644 index b5b2960666..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/TestOption.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/exception/ConfigHandlingException.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/exception/ConfigHandlingException.java deleted file mode 100644 index 50db588f6f..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/exception/ConfigHandlingException.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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 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 errorInfo) { - super(message, cause, errorType, errorTag, errorSeverity, errorInfo); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/exception/OperationNotPermittedException.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/exception/OperationNotPermittedException.java deleted file mode 100644 index cedb833b12..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/exception/OperationNotPermittedException.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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.emptyMap()); - } - - public OperationNotPermittedException(final String message, final ErrorType errorType, final ErrorTag errorTag, - final ErrorSeverity errorSeverity, final Map errorInfo) { - super(message, errorType, errorTag, errorSeverity, errorInfo); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/IdentityMapping.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/IdentityMapping.java deleted file mode 100644 index 759e33e0a6..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/IdentityMapping.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 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); - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/AttributeIfcSwitchStatement.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/AttributeIfcSwitchStatement.java deleted file mode 100644 index 36a41d0441..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/AttributeIfcSwitchStatement.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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 { - - 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); - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/AbstractAttributeReadingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/AbstractAttributeReadingStrategy.java deleted file mode 100644 index 6d193118b5..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/AbstractAttributeReadingStrategy.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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 configNodes) throws DocumentedException { - if (configNodes.isEmpty()) { - return AttributeConfigElement.createNullValue(postprocessNullableDefault(nullableDefault)); - } - return readElementHook(configNodes); - } - - abstract AttributeConfigElement readElementHook(List configNodes) throws DocumentedException; - - @SuppressWarnings("checkstyle:hiddenField") - protected Object postprocessNullableDefault(final String nullableDefault) { - return nullableDefault; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/ArrayAttributeReadingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/ArrayAttributeReadingStrategy.java deleted file mode 100644 index 8887fbd088..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/ArrayAttributeReadingStrategy.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 configNodes) throws DocumentedException { - List 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); - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/AttributeConfigElement.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/AttributeConfigElement.java deleted file mode 100644 index ac8380f90b..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/AttributeConfigElement.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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 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> 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 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 + "]"; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/AttributeReadingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/AttributeReadingStrategy.java deleted file mode 100644 index eeb538bd5f..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/AttributeReadingStrategy.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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 element) throws DocumentedException; - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/CompositeAttributeReadingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/CompositeAttributeReadingStrategy.java deleted file mode 100644 index f35281411a..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/CompositeAttributeReadingStrategy.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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 innerStrategies; - - public CompositeAttributeReadingStrategy(final String nullableDefault, - final Map innerStrategies) { - super(nullableDefault); - this.innerStrategies = innerStrategies; - } - - @Override - AttributeConfigElement readElementHook(final List configNodes) throws DocumentedException { - - Preconditions.checkState(configNodes.size() == 1, "This element should be present only once %s", configNodes); - - XmlElement complexElement = configNodes.get(0); - - Map innerMap = Maps.newHashMap(); - - List recognisedChildren = Lists.newArrayList(); - for (Entry innerAttrEntry : innerStrategies.entrySet()) { - List 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)); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/ObjectNameAttributeReadingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/ObjectNameAttributeReadingStrategy.java deleted file mode 100644 index cce74ad6c6..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/ObjectNameAttributeReadingStrategy.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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 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 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 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; - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/ObjectXmlReader.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/ObjectXmlReader.java deleted file mode 100644 index c99d21d6ac..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/ObjectXmlReader.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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 { - - private String key; - private Map, IdentityMapping>> identityMap; - - @SuppressWarnings("checkstyle:hiddenField") - public Map prepareReading(final Map yangToAttrConfig, - final Map, IdentityMapping>> identityMap) { - Map strategies = Maps.newHashMap(); - this.identityMap = identityMap; - - for (Entry 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 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 inner = ((TOAttribute) lastAttribute).getYangPropertiesToTypesMap(); - - Map innerStrategies = Maps.newHashMap(); - - for (Entry 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); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleAttributeReadingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleAttributeReadingStrategy.java deleted file mode 100644 index db2d9c1d1e..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleAttributeReadingStrategy.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 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; - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleBinaryAttributeReadingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleBinaryAttributeReadingStrategy.java deleted file mode 100644 index 5353049b4d..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleBinaryAttributeReadingStrategy.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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 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); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleCompositeAttributeReadingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleCompositeAttributeReadingStrategy.java deleted file mode 100644 index 764629bf7c..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleCompositeAttributeReadingStrategy.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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 map = Maps.newHashMap(); - map.put(key, textContent); - return map; - } - - @Override - protected Object postprocessNullableDefault(final String nullableDefault) { - return nullableDefault == null ? null : postprocessParsedValue(nullableDefault); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleIdentityRefAttributeReadingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleIdentityRefAttributeReadingStrategy.java deleted file mode 100644 index 679631b24c..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleIdentityRefAttributeReadingStrategy.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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, IdentityMapping>> identityMap; - - public SimpleIdentityRefAttributeReadingStrategy(final String nullableDefault, final String key, - final Map, IdentityMapping>> identityMap) { - super(nullableDefault); - this.key = key; - this.identityMap = identityMap; - } - - @Override - protected String readElementContent(final XmlElement xmlElement) throws DocumentedException { - Map.Entry 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 = null; - Map, IdentityMapping> revisions = identityMap.get(namespace); - if (revisions.keySet().size() > 1) { - for (Map.Entry, 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 map = Maps.newHashMap(); - map.put(key, textContent); - return map; - } - - @Override - protected Object postprocessNullableDefault(final String nullableDefault) { - return nullableDefault == null ? null : postprocessParsedValue(nullableDefault); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleUnionAttributeReadingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleUnionAttributeReadingStrategy.java deleted file mode 100644 index d2466bbad9..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleUnionAttributeReadingStrategy.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 chars = Lists.newArrayListWithCapacity(charArray.length); - - for (char c : charArray) { - chars.add(Character.toString(c)); - } - - Map map = Maps.newHashMap(); - map.put(key, chars); - return map; - } - - @Override - protected Object postprocessNullableDefault(final String nullableDefault) { - return nullableDefault == null ? null : postprocessParsedValue(nullableDefault); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/AbstractAttributeMappingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/AbstractAttributeMappingStrategy.java deleted file mode 100644 index 7ff7cfade9..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/AbstractAttributeMappingStrategy.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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> implements - AttributeMappingStrategy { - - private final O attrOpenType; - - public AbstractAttributeMappingStrategy(final O attributeIfc) { - this.attrOpenType = attributeIfc; - } - - @Override - public O getOpenType() { - return attrOpenType; - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/ArrayAttributeMappingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/ArrayAttributeMappingStrategy.java deleted file mode 100644 index 9aa5a6a914..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/ArrayAttributeMappingStrategy.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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, ArrayType> { - - private final AttributeMappingStrategy> innerElementStrategy; - - public ArrayAttributeMappingStrategy(final ArrayType arrayType, - final AttributeMappingStrategy> innerElementStrategy) { - super(arrayType); - this.innerElementStrategy = innerElementStrategy; - } - - @Override - public Optional> mapAttribute(final Object value) { - if (value == null) { - return Optional.absent(); - } - - Preconditions.checkArgument(value.getClass().isArray(), "Value has to be instanceof Array "); - - List 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); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/AttributeMappingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/AttributeMappingStrategy.java deleted file mode 100644 index 33eb64d395..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/AttributeMappingStrategy.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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> { - - O getOpenType(); - - Optional mapAttribute(Object object); -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/CompositeAttributeMappingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/CompositeAttributeMappingStrategy.java deleted file mode 100644 index d5c3848e8c..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/CompositeAttributeMappingStrategy.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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, CompositeType> { - - private final Map>> innerStrategies; - private final Map jmxToJavaNameMapping; - - public CompositeAttributeMappingStrategy(final CompositeType compositeType, - final Map>> innerStrategies, - final Map jmxToJavaNameMapping) { - super(compositeType); - this.innerStrategies = innerStrategies; - this.jmxToJavaNameMapping = jmxToJavaNameMapping; - } - - @Override - public Optional> 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 expectedCompositeTypeKeys = expectedType.keySet(); - Set currentCompositeTypeKeys = currentType.keySet(); - Preconditions.checkArgument(expectedCompositeTypeKeys.equals(currentCompositeTypeKeys), - "Composite type mismatch, expected composite type with attributes " + expectedCompositeTypeKeys - + " but was " + currentCompositeTypeKeys); - - Map 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> attributeMappingStrategy = innerStrategies.get(jmxName); - return attributeMappingStrategy.mapAttribute(innerValue); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/EnumAttributeMappingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/EnumAttributeMappingStrategy.java deleted file mode 100644 index c6b20c826f..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/EnumAttributeMappingStrategy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 { - - private final EnumResolver enumResolver; - - public EnumAttributeMappingStrategy(final CompositeType openType, final EnumResolver enumResolver) { - super(openType); - this.enumResolver = enumResolver; - } - - @Override - public Optional mapAttribute(final Object value) { - if (value == null) { - return Optional.absent(); - } - - String expectedClass = getOpenType().getTypeName(); - return Optional.of(enumResolver.toYang(expectedClass, value.toString())); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/ObjectMapper.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/ObjectMapper.java deleted file mode 100644 index 36fd085da6..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/ObjectMapper.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * 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>> { - - private EnumResolver enumResolver; - - @SuppressWarnings("checkstyle:hiddenField") - public Map>> prepareMapping( - final Map configDefinition, final EnumResolver enumResolver) { - this.enumResolver = Preconditions.checkNotNull(enumResolver); - Map>> strategies = Maps.newHashMap(); - - for (Entry attrEntry : configDefinition.entrySet()) { - strategies.put(attrEntry.getKey(), prepareStrategy(attrEntry.getValue())); - } - return strategies; - } - - public AttributeMappingStrategy> 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 createJmxToYangMapping(final TOAttribute attributeIfc) { - Map retVal = Maps.newHashMap(); - for (Entry entry : attributeIfc.getJmxPropertiesToTypesMap().entrySet()) { - retVal.put(entry.getKey(), entry.getValue().getAttributeYangName()); - } - return retVal; - } - - @Override - protected AttributeMappingStrategy> caseJavaSimpleAttribute(final SimpleType openType) { - return new SimpleAttributeMappingStrategy(openType); - } - - @Override - protected AttributeMappingStrategy> caseJavaEnumAttribute(final OpenType openType) { - return new EnumAttributeMappingStrategy((CompositeType) openType, enumResolver); - } - - @Override - protected AttributeMappingStrategy> caseJavaArrayAttribute(final ArrayType openType) { - - AttributeMappingStrategy> innerStrategy = new SimpleAttributeMappingStrategy( - (SimpleType) openType.getElementOpenType()); - return new ArrayAttributeMappingStrategy(openType, innerStrategy); - } - - @Override - protected AttributeMappingStrategy> caseJavaCompositeAttribute( - final CompositeType openType) { - Map>> innerStrategies = Maps.newHashMap(); - - Map 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> caseJavaUnionAttribute(final OpenType openType) { - Map>> innerStrategies = Maps.newHashMap(); - - Map 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> caseDependencyAttribute(final SimpleType openType) { - return new ObjectNameAttributeMappingStrategy(openType, namespaceOfDepAttr); - } - - @Override - protected AttributeMappingStrategy> caseTOAttribute(final CompositeType openType) { - Map>> innerStrategies = Maps.newHashMap(); - - Preconditions.checkState(getLastAttribute() instanceof TOAttribute); - TOAttribute lastTO = (TOAttribute) getLastAttribute(); - - for (Entry innerAttrEntry : ((TOAttribute) getLastAttribute()) - .getJmxPropertiesToTypesMap().entrySet()) { - innerStrategies.put(innerAttrEntry.getKey(), prepareStrategy(innerAttrEntry.getValue())); - } - - return new CompositeAttributeMappingStrategy(openType, innerStrategies, createJmxToYangMapping(lastTO)); - } - - @Override - protected AttributeMappingStrategy> caseListAttribute(final ArrayType openType) { - Preconditions.checkState(getLastAttribute() instanceof ListAttribute); - return new ArrayAttributeMappingStrategy(openType, - prepareStrategy(((ListAttribute) getLastAttribute()).getInnerAttribute())); - } - - @Override - protected AttributeMappingStrategy> caseListDependeciesAttribute( - final ArrayType openType) { - Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute); - return new ArrayAttributeMappingStrategy(openType, caseDependencyAttribute(SimpleType.OBJECTNAME)); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/ObjectNameAttributeMappingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/ObjectNameAttributeMappingStrategy.java deleted file mode 100644 index 9d6c59c73f..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/ObjectNameAttributeMappingStrategy.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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> { - - private final String namespace; - - public ObjectNameAttributeMappingStrategy(final SimpleType openType, final String namespace) { - super(openType); - this.namespace = namespace; - } - - @Override - public Optional 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 + '\'' - + '}'; - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/SimpleAttributeMappingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/SimpleAttributeMappingStrategy.java deleted file mode 100644 index 782d243550..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/SimpleAttributeMappingStrategy.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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> { - - public SimpleAttributeMappingStrategy(final SimpleType openType) { - super(openType); - } - - @Override - public Optional 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 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(); - } - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/UnionCompositeAttributeMappingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/UnionCompositeAttributeMappingStrategy.java deleted file mode 100644 index 3053964e02..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/mapping/UnionCompositeAttributeMappingStrategy.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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>> innerStrategies, - final Map 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); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/AbstractAttributeResolvingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/AbstractAttributeResolvingStrategy.java deleted file mode 100644 index 4f9cef4179..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/AbstractAttributeResolvingStrategy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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> - implements AttributeResolvingStrategy { - 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/ArrayAttributeResolvingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/ArrayAttributeResolvingStrategy.java deleted file mode 100644 index ec2b665b2f..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/ArrayAttributeResolvingStrategy.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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> { - - private final AttributeResolvingStrategy> innerTypeResolvingStrategy; - - private static final Logger LOG = LoggerFactory.getLogger(ArrayAttributeResolvingStrategy.class); - - public ArrayAttributeResolvingStrategy(final AttributeResolvingStrategy> innerTypeResolved, - final ArrayType openType) { - super(openType); - this.innerTypeResolvingStrategy = innerTypeResolved; - } - - @Override - public Optional 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 + "]"; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/AttributeResolvingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/AttributeResolvingStrategy.java deleted file mode 100644 index e9f311fd83..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/AttributeResolvingStrategy.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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> { - O getOpenType(); - - Optional parseAttribute(String attrName, Object value) throws DocumentedException; -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/CompositeAttributeResolvingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/CompositeAttributeResolvingStrategy.java deleted file mode 100644 index f08233c8ee..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/CompositeAttributeResolvingStrategy.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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 { - private final Map>> innerTypes; - private final Map yangToJavaAttrMapping; - - private static final Logger LOG = LoggerFactory.getLogger(CompositeAttributeResolvingStrategy.class); - - CompositeAttributeResolvingStrategy( - final Map>> innerTypes, - final CompositeType openType, final Map yangToJavaAttrMapping) { - super(openType); - this.innerTypes = innerTypes; - this.yangToJavaAttrMapping = yangToJavaAttrMapping; - } - - @Override - public String toString() { - return "ResolvedCompositeAttribute [" + innerTypes + "]"; - } - - @Override - public Optional 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 items = Maps.newHashMap(); - Map> 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> 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/EnumAttributeResolvingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/EnumAttributeResolvingStrategy.java deleted file mode 100644 index 4d426b59cc..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/EnumAttributeResolvingStrategy.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 { - - 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 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); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/ObjectNameAttributeResolvingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/ObjectNameAttributeResolvingStrategy.java deleted file mode 100644 index 1318bb9d87..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/ObjectNameAttributeResolvingStrategy.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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> { - - 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 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); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/ObjectResolver.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/ObjectResolver.java deleted file mode 100644 index 4fcdc1298c..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/ObjectResolver.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * 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>> { - - private final ServiceRegistryWrapper serviceTracker; - private EnumResolver enumResolver; - - public ObjectResolver(final ServiceRegistryWrapper serviceTracker) { - this.serviceTracker = serviceTracker; - } - - @SuppressWarnings("checkstyle:hiddenField") - public Map>> prepareResolving( - final Map configDefinition, final EnumResolver enumResolver) { - this.enumResolver = enumResolver; - - Map>> strategies = Maps.newHashMap(); - - for (Entry attrEntry : configDefinition.entrySet()) { - strategies.put(attrEntry.getKey(), prepareStrategy(attrEntry.getValue())); - } - - return strategies; - } - - private AttributeResolvingStrategy> prepareStrategy(final AttributeIfc attributeIfc) { - return switchAttribute(attributeIfc); - } - - private Map createYangToJmxMapping(final TOAttribute attributeIfc) { - Map retVal = Maps.newHashMap(); - for (Entry entry : attributeIfc.getYangPropertiesToTypesMap().entrySet()) { - retVal.put(entry.getKey(), entry.getValue().getLowerCaseCammelCase()); - } - return retVal; - } - - @Override - protected AttributeResolvingStrategy> caseJavaEnumAttribute(final OpenType openType) { - return new EnumAttributeResolvingStrategy((CompositeType) openType, enumResolver); - } - - @Override - protected AttributeResolvingStrategy> caseJavaSimpleAttribute( - final SimpleType openType) { - return new SimpleAttributeResolvingStrategy(openType); - } - - @Override - protected AttributeResolvingStrategy> caseJavaArrayAttribute(final ArrayType openType) { - - SimpleType innerType = (SimpleType) openType.getElementOpenType(); - AttributeResolvingStrategy> strat = new SimpleAttributeResolvingStrategy(innerType); - return new ArrayAttributeResolvingStrategy(strat, openType); - } - - @Override - protected AttributeResolvingStrategy> caseJavaCompositeAttribute( - final CompositeType openType) { - Map>> innerMap = Maps.newHashMap(); - Map yangToJmxMapping = Maps.newHashMap(); - - fillMappingForComposite(openType, innerMap, yangToJmxMapping); - return new CompositeAttributeResolvingStrategy(innerMap, openType, yangToJmxMapping); - } - - private void fillMappingForComposite(final CompositeType openType, - final Map>> innerMap, - final Map yangToJmxMapping) { - for (String innerAttributeKey : openType.keySet()) { - innerMap.put(innerAttributeKey, caseJavaAttribute(openType.getType(innerAttributeKey))); - yangToJmxMapping.put(innerAttributeKey, innerAttributeKey); - } - } - - @Override - protected AttributeResolvingStrategy> caseJavaUnionAttribute(final OpenType openType) { - - Preconditions.checkState(openType instanceof CompositeType, "Unexpected open type, expected %s but was %s"); - CompositeType compositeType = (CompositeType) openType; - - Map>> innerMap = Maps.newHashMap(); - Map yangToJmxMapping = Maps.newHashMap(); - fillMappingForComposite(compositeType, innerMap, yangToJmxMapping); - - return new UnionCompositeAttributeResolvingStrategy(innerMap, compositeType, yangToJmxMapping); - } - - @Override - protected AttributeResolvingStrategy> caseDependencyAttribute( - final SimpleType openType) { - return new ObjectNameAttributeResolvingStrategy(serviceTracker); - } - - @Override - protected AttributeResolvingStrategy> caseTOAttribute(final CompositeType openType) { - Preconditions.checkState(getLastAttribute() instanceof TOAttribute); - TOAttribute toAttribute = (TOAttribute) getLastAttribute(); - - Map>> 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> caseListAttribute(final ArrayType openType) { - Preconditions.checkState(getLastAttribute() instanceof ListAttribute); - AttributeIfc innerAttribute = ((ListAttribute) getLastAttribute()).getInnerAttribute(); - return new ArrayAttributeResolvingStrategy(prepareStrategy(innerAttribute), openType); - } - - @Override - protected AttributeResolvingStrategy> caseListDependeciesAttribute( - final ArrayType openType) { - Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute); - return new ArrayAttributeResolvingStrategy(caseDependencyAttribute(SimpleType.OBJECTNAME), openType); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/SimpleAttributeResolvingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/SimpleAttributeResolvingStrategy.java deleted file mode 100644 index f7952528d1..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/SimpleAttributeResolvingStrategy.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * 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> { - - 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 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 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); - } - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/UnionCompositeAttributeResolvingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/UnionCompositeAttributeResolvingStrategy.java deleted file mode 100644 index ed2e30aaea..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/resolving/UnionCompositeAttributeResolvingStrategy.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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>> innerTypes, - final CompositeType openType, final Map yangToJavaAttrMapping) { - super(innerTypes, openType, yangToJavaAttrMapping); - } - - @Override - protected Map 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 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/ArrayAttributeWritingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/ArrayAttributeWritingStrategy.java deleted file mode 100644 index 311ab1d512..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/ArrayAttributeWritingStrategy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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); - } - - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/AttributeWritingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/AttributeWritingStrategy.java deleted file mode 100644 index 105d7b39ae..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/AttributeWritingStrategy.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * 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); - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/CompositeAttributeWritingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/CompositeAttributeWritingStrategy.java deleted file mode 100644 index 58579f72c7..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/CompositeAttributeWritingStrategy.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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 innerStrats; - - public CompositeAttributeWritingStrategy(final Document document, final String key, - final Map 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 getInnerStrats() { - return innerStrats; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/ObjectNameAttributeWritingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/ObjectNameAttributeWritingStrategy.java deleted file mode 100644 index 31305af844..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/ObjectNameAttributeWritingStrategy.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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.absent()); - innerNode.appendChild(nameElement); - - parentElement.appendChild(innerNode); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/ObjectXmlWriter.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/ObjectXmlWriter.java deleted file mode 100644 index a3a8b7aafa..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/ObjectXmlWriter.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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 { - - private Document document; - private String key; - - @SuppressWarnings("checkstyle:hiddenField") - public Map prepareWriting(final Map yangToAttrConfig, - final Document document) { - - Map preparedWriting = Maps.newHashMap(); - - for (Entry 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 innerStrats = Maps.newHashMap(); - String currentKey = key; - for (Entry 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); - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/RuntimeBeanEntryWritingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/RuntimeBeanEntryWritingStrategy.java deleted file mode 100644 index f0a1121958..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/RuntimeBeanEntryWritingStrategy.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 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.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.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); - - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleAttributeWritingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleAttributeWritingStrategy.java deleted file mode 100644 index 00d863907e..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleAttributeWritingStrategy.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 namespace) { - Element typeElement = XmlUtil.createElement(document, key, namespace); - - typeElement.appendChild(document.createTextNode(value)); - return typeElement; - } - - protected Object preprocess(final Object value) { - return value; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleBinaryAttributeWritingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleBinaryAttributeWritingStrategy.java deleted file mode 100644 index 6c75c9f0df..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleBinaryAttributeWritingStrategy.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleCompositeAttributeWritingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleCompositeAttributeWritingStrategy.java deleted file mode 100644 index 8c6fd6c54b..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleCompositeAttributeWritingStrategy.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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(); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleIdentityRefAttributeWritingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleIdentityRefAttributeWritingStrategy.java deleted file mode 100644 index 7fe55b72f8..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleIdentityRefAttributeWritingStrategy.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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 namespace) { - QName qualifiedName = QName.create(value); - String identityValue = qualifiedName.getLocalName(); - String identityNamespace = qualifiedName.getNamespace().toString(); - return XmlUtil.createTextElementWithNamespacedContent(doc, key, PREFIX, identityNamespace, identityValue, - namespace); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleUnionAttributeWritingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleUnionAttributeWritingStrategy.java deleted file mode 100644 index 7aeb76b864..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/toxml/SimpleUnionAttributeWritingStrategy.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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(); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/Config.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/Config.java deleted file mode 100644 index 381934ae13..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/Config.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * 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> moduleConfigs; - - private final Map, IdentityMapping>> identityMap; - - private final EnumResolver enumResolver; - - public Config(final Map> moduleConfigs, final EnumResolver enumResolver) { - this(moduleConfigs, Collections., IdentityMapping>>emptyMap(), enumResolver); - } - - public Config(final Map> moduleConfigs, - final Map, IdentityMapping>> identityMap, final EnumResolver enumResolver) { - this.moduleConfigs = moduleConfigs; - this.identityMap = identityMap; - this.enumResolver = enumResolver; - } - - public static Map>> getMappedInstances( - final Set instancesToMap, final Map> configs) { - Multimap moduleToInstances = mapInstancesToModules(instancesToMap); - - Map>> retVal = Maps.newLinkedHashMap(); - - for (Entry> namespaceToModuleToConfigEntry : configs.entrySet()) { - - Map> innerRetVal = Maps.newHashMap(); - - for (Entry mbeEntry : namespaceToModuleToConfigEntry.getValue().entrySet()) { - - String moduleName = mbeEntry.getKey(); - Collection 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 mapInstancesToModules(final Set instancesToMap) { - Multimap retVal = HashMultimap.create(); - - for (ObjectName objectName : instancesToMap) { - String factoryName = ObjectNameUtil.getFactoryName(objectName); - retVal.put(factoryName, objectName); - } - return retVal; - } - - public Element toXml(final Set instancesToMap, final Optional maybeNamespace, - final Document document, final Element dataElement, final ServiceRegistryWrapper serviceTracker) { - - Map>> 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>> moduleToInstanceEntry : moduleToInstances.entrySet()) { - for (Entry> 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> fromXmlModulesResolved(final XmlElement xml, - final EditStrategyType defaultEditStrategyType, final ServiceRegistryWrapper serviceTracker) - throws DocumentedException { - Optional modulesElement = getModulesElement(xml); - List moduleElements = getModulesElementList(modulesElement); - - Map> retVal = Maps.newHashMap(); - - ResolvingStrategy 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> fromXmlModulesMap(final XmlElement xml, - final EditStrategyType defaultEditStrategyType, final ServiceRegistryWrapper serviceTracker) - throws DocumentedException { - Optional modulesElement = getModulesElement(xml); - List moduleElements = getModulesElementList(modulesElement); - - Map> retVal = Maps.newHashMap(); - - ResolvingStrategy 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 getModulesElement(final XmlElement xml) { - return xml.getOnlyChildElementOptionally(XmlMappingConstants.MODULES_KEY, - XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG); - } - - private List getModulesElementList(final Optional modulesElement) - throws DocumentedException { - List moduleElements; - - if (modulesElement.isPresent()) { - moduleElements = modulesElement.get().getChildElementsWithSameNamespace(XmlMappingConstants.MODULE_KEY); - modulesElement.get().checkUnrecognisedElements(moduleElements); - } else { - moduleElements = Lists.newArrayList(); - } - return moduleElements; - } - - private void resolveModule(final Map> retVal, - final ServiceRegistryWrapper serviceTracker, final XmlElement moduleElement, - final EditStrategyType defaultStrategy, final ResolvingStrategy resolvingStrategy) - throws DocumentedException { - XmlElement typeElement = null; - typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY); - Entry 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 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 servicesElement = getServicesElement(xml); - - Services services; - if (servicesElement.isPresent()) { - services = Services.fromXml(servicesElement.get()); - } else { - services = new Services(); - } - - return services; - } - - private static Optional 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 servicesOpt = getServicesElement(parent); - Optional modulesOpt = getModulesElement(parent); - - List 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 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 resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker, - String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) - throws DocumentedException; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/InstanceConfig.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/InstanceConfig.java deleted file mode 100644 index 1bea5c2638..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/InstanceConfig.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * 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 yangToAttrConfig; - private final String nullableDummyContainerName; - private final Map jmxToAttrConfig; - private final BeanReader configRegistryClient; - - public InstanceConfig(final BeanReader configRegistryClient, final Map yangNamesToAttributes, - final String nullableDummyContainerName) { - - this.yangToAttrConfig = yangNamesToAttributes; - this.nullableDummyContainerName = nullableDummyContainerName; - this.jmxToAttrConfig = reverseMap(yangNamesToAttributes); - this.configRegistryClient = configRegistryClient; - } - - @SuppressWarnings("IllegalCatch") - private Map getMappedConfiguration(final ObjectName on, final EnumResolver enumResolver) { - - // TODO make field, mappingStrategies can be instantiated only once - Map>> mappingStrategies = new ObjectMapper() - .prepareMapping(jmxToAttrConfig, enumResolver); - - Map toXml = Maps.newHashMap(); - - for (Entry 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> 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 strats = new ObjectXmlWriter().prepareWriting(yangToAttrConfig, document); - Map 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 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>> resolvingStrategies = new ObjectResolver( - depTracker).prepareResolving(yangToAttrConfig, enumResolver); - - for (Entry configDefEntry : mappedConfig.getConfiguration().entrySet()) { - AttributeConfigElement value = configDefEntry.getValue(); - String attributeName = configDefEntry.getKey(); - try { - AttributeResolvingStrategy> 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, IdentityMapping>> identityMap, - final EnumResolver enumResolver) - throws DocumentedException { - Map retVal = Maps.newHashMap(); - - Map strats = new ObjectXmlReader().prepareReading(yangToAttrConfig, - identityMap); - List recognisedChildren = Lists.newArrayList(); - - XmlElement typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY); - XmlElement nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.NAME_KEY); - List 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 readStratEntry : strats.entrySet()) { - List 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 getConfigNodes(final XmlElement moduleElement, final String moduleNamespace, - final String name, final List recognisedChildren, - final List typeAndName) - throws DocumentedException { - List 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 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 reverseMap(final Map yangNameToAttr) { - Map reversednameToAtr = Maps.newHashMap(); - - for (Entry entry : yangNameToAttr.entrySet()) { - reversednameToAtr.put(entry.getValue().getUpperCaseCammelCase(), entry.getValue()); - } - return reversednameToAtr; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/InstanceConfigElementResolved.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/InstanceConfigElementResolved.java deleted file mode 100644 index 4c4fb78f45..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/InstanceConfigElementResolved.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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 configuration; - - public InstanceConfigElementResolved(final String currentStrategy, - final Map configuration, final EditStrategyType defaultStrategy) - throws DocumentedException { - this.editStrategy = parseStrategy(currentStrategy, defaultStrategy); - this.configuration = configuration; - } - - public InstanceConfigElementResolved(final Map 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 getConfiguration() { - return configuration; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ModuleConfig.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ModuleConfig.java deleted file mode 100644 index 3746c35e7e..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ModuleConfig.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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 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 prefix:moduleName - - 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, IdentityMapping>> identityMap, final EnumResolver enumResolver) - throws DocumentedException { - - InstanceConfigElementResolved ice = instanceConfig.fromXml(moduleElement, depTracker, moduleNamespace, - defaultStrategy, identityMap, enumResolver); - return new ModuleElementResolved(instanceName, ice); - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ModuleElementDefinition.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ModuleElementDefinition.java deleted file mode 100644 index fc0cd4a52f..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ModuleElementDefinition.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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; - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ModuleElementResolved.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ModuleElementResolved.java deleted file mode 100644 index 34e5ebae3e..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ModuleElementResolved.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ServiceRegistryWrapper.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ServiceRegistryWrapper.java deleted file mode 100644 index 0d04194af6..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/ServiceRegistryWrapper.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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>> mappedServices = getMappedServices(); - Map> 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 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>> getMappedServices() { - Map>> retVal = new HashMap<>(); - - Map> serviceMapping = configServiceRefRegistry.getServiceMapping(); - for (Map.Entry> 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> serviceToRefs = retVal.computeIfAbsent(namespace, - k -> new HashMap<>()); - - String localName = qname.getLocalName(); - Map 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/Services.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/Services.java deleted file mode 100644 index b96ba72a07..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/mapping/config/Services.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * 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>> namespaceToServiceNameToRefNameToInstance = new HashMap<>(); - - public Map>> getNamespaceToServiceNameToRefNameToInstance() { - return namespaceToServiceNameToRefNameToInstance; - } - - private static Services resolveServices(final Map>> mappedServices) { - Services tracker = new Services(); - - for (Entry>> namespaceEntry : mappedServices.entrySet()) { - String namespace = namespaceEntry.getKey(); - - for (Entry> serviceEntry : namespaceEntry.getValue().entrySet()) { - - String serviceName = serviceEntry.getKey(); - for (Entry refEntry : serviceEntry.getValue().entrySet()) { - - Map> namespaceToServices = - tracker.namespaceToServiceNameToRefNameToInstance - .computeIfAbsent(namespace, k -> new HashMap<>()); - - Map 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>> retVal = new HashMap<>(); - - List services = xml.getChildElements(SERVICE_KEY); - xml.checkUnrecognisedElements(services); - - for (XmlElement service : services) { - - XmlElement typeElement = service.getOnlyChildElement(TYPE_KEY); - Entry prefixNamespace = typeElement.findNamespaceOfTextContent(); - - Preconditions.checkState(prefixNamespace.getKey() != null && !prefixNamespace.getKey().equals(""), - "Type attribute was not prefixed"); - - Map> namespaceToServices = retVal.computeIfAbsent(prefixNamespace.getValue(), - k -> new HashMap<>()); - - String serviceName = ObjectNameAttributeReadingStrategy.checkPrefixAndExtractServiceName(typeElement, - prefixNamespace); - - Map innerMap = namespaceToServices.computeIfAbsent(serviceName, k -> new HashMap<>()); - - List 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 configNs = Optional - .of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG); - Element root = XmlUtil.createElement(document, XmlMappingConstants.SERVICES_KEY, configNs); - - Map>> mappedServices = serviceRegistryWrapper.getMappedServices(); - for (Entry>> namespaceToRefEntry : mappedServices.entrySet()) { - - for (Entry> 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 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)); - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/EnumResolver.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/EnumResolver.java deleted file mode 100644 index 556ec364c0..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/EnumResolver.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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); -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreActivator.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreActivator.java deleted file mode 100644 index 016c944d80..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreActivator.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * 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 yangStoreServiceServiceRegistration; - private ConfigRegistryLookupThread configRegistryLookup = null; - private BundleContext context; - private ServiceRegistration osgiRegistrayion; - - @Override - @SuppressWarnings("checkstyle:hiddenField") - public void start(final BundleContext context) throws Exception { - LOG.debug("ConfigPersister starting"); - this.context = context; - - final ServiceTrackerCustomizer schemaServiceTrackerCustomizer = - new ServiceTrackerCustomizer() { - - private final AtomicBoolean alreadyStarted = new AtomicBoolean(false); - - @Override - public YangStoreService addingService(final ServiceReference 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) 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 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 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 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<>()); - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreContext.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreContext.java deleted file mode 100644 index 8e97d76993..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreContext.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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> getModuleMXBeanEntryMap(); - - Map> 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 getModules(); - - String getModuleSource(SourceIdentifier moduleIdentifier); - - EnumResolver getEnumResolver(); -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreService.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreService.java deleted file mode 100644 index 02865c2163..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreService.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * 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 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 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 sourceProvider) { - this.sourceProvider = sourceProvider; - } - - public YangStoreContext getCurrentSnapshot() { - return this.snap; - } - - @Deprecated - @Override - public Map> getModuleMXBeanEntryMap() { - Map> ret; - YangStoreSnapshot snapshot; - - do { - snapshot = this.snap; - ret = snapshot.getModuleMXBeanEntryMap(); - } while (!snapshot.equals(this.snap)); - - return ret; - } - - @Override - public Map> getQNamesToIdentitiesToModuleMXBeanEntries() { - Map> ret; - YangStoreSnapshot snapshot; - - do { - snapshot = this.snap; - ret = snapshot.getQNamesToIdentitiesToModuleMXBeanEntries(); - } while (!snapshot.equals(this.snap)); - - return ret; - } - - @Override - public Set 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.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 prevModules = previous.getModules(); - final Set currModules = current.getModules(); - final Set removed = Sets.difference(prevModules, currModules); - final Set added = Sets.difference(currModules, prevModules); - - final Set addedCaps = toCapabilities(added, current); - final Set removedCaps = toCapabilities(removed, current); - - synchronized (this.listeners) { - for (final ModuleListener listener : this.listeners) { - listener.onCapabilitiesChanged(addedCaps, removedCaps); - } - } - } - - private static Set toCapabilities(final Set modules, final YangStoreContext current) { - return ImmutableSet.copyOf(Collections2.transform(modules, - input -> new YangModuleCapability(input, current.getModuleSource( - RevisionSourceIdentifier.create(input.getName(), input.getRevision()))))); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreSnapshot.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreSnapshot.java deleted file mode 100644 index 452054518e..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/osgi/YangStoreSnapshot.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * 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> moduleMXBeanEntryMap; - private final Map> namesToIdentitiesToModuleMXBeanEntries; - - MXBeans(final SchemaContext schemaContext) { - LOG.trace("Resolved modules:{}", schemaContext.getModules()); - - // JMX generator - final Map namespaceToPackageMapping = Maps.newHashMap(); - final PackageTranslator packageTranslator = new PackageTranslator(namespaceToPackageMapping); - final Map qNamesToSIEs = new HashMap<>(); - final Map knownSEITracker = new HashMap<>(); - // create SIE structure qNamesToSIEs - for (final Module module : schemaContext.getModules()) { - final String packageName = packageTranslator.getPackageName(module); - final Map namesToSIEntries = ServiceInterfaceEntry - .create(module, packageName, knownSEITracker); - for (final Entry 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> moduleMXBeanEntries = Maps.newHashMap(); - - final Map> 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 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 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 ref = new SoftReference<>(null); - - public YangStoreSnapshot(final BindingRuntimeContext bindingContextProvider, - final SchemaSourceProvider 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> getModuleMXBeanEntryMap() { - return getMXBeans().moduleMXBeanEntryMap; - } - - @Override - public Map> getQNamesToIdentitiesToModuleMXBeanEntries() { - return getMXBeans().namesToIdentitiesToModuleMXBeanEntries; - } - - @Override - public Set getModules() { - final Set 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 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 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 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()); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/InstanceRuntimeRpc.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/InstanceRuntimeRpc.java deleted file mode 100644 index 8c101be4f5..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/InstanceRuntimeRpc.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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 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 map(final List parameters) { - Map mapped = Maps.newHashMap(); - for (JavaAttribute javaAttribute : parameters) { - mapped.put(javaAttribute.getAttributeYangName(), javaAttribute); - } - return mapped; - } - - private void resolveConfiguration(final Map mappedConfig) { - - // TODO make field, resolvingStrategies can be instantiated only once - Map>> resolvingStrategies = new ObjectResolver(null) - .prepareResolving(yangToAttrConfig, enumResolver); - // TODO make constructor for object resolver without service tracker - for (Entry configDefEntry : mappedConfig.entrySet()) { - try { - - AttributeResolvingStrategy> 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 fromXml(final XmlElement configRootNode) throws DocumentedException { - Map retVal = Maps.newHashMap(); - - // FIXME add identity map to runtime data - Map strats = new ObjectXmlReader().prepareReading(yangToAttrConfig, - Collections., IdentityMapping>>emptyMap()); - - for (Entry readStratEntry : strats.entrySet()) { - List 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(); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/ModuleRpcs.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/ModuleRpcs.java deleted file mode 100644 index 8ce71a1dc5..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/ModuleRpcs.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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 yangToJavaNames = new HashMap<>(); - private final Map> 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 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 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; - } - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/Rpcs.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/Rpcs.java deleted file mode 100644 index f409ee25ea..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/Rpcs.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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> mappedRpcs; - - public Rpcs(Map> mappedRpcs) { - this.mappedRpcs = mappedRpcs; - } - - public ModuleRpcs getRpcMapping(RuntimeRpcElementResolved id) { - Map 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/RuntimeRpcElementResolved.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/RuntimeRpcElementResolved.java deleted file mode 100644 index a63114c9ad..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/rpc/RuntimeRpcElementResolved.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * 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 additionalAttributes; - - private RuntimeRpcElementResolved(String namespace, String moduleName, String instanceName, String runtimeBeanName, - Map 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 getAdditionalAttributes() { - return additionalAttributes; - } - - public String getInstanceName() { - return instanceName; - } - - public String getNamespace() { - return namespace; - } - - public String getRuntimeBeanName() { - return runtimeBeanName; - } - - public ObjectName getObjectName(ModuleRpcs rpcMapping) { - Map 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: - * - *
-     * /modules/module[name=instanceName][type=moduleType]
-     * 
- * - *

- * or - * - *

-     * /a:modules/a:module[a:name=instanceName][a:type=moduleType]
-     * 
- */ - private static final String XPATH_PATTERN_BLUEPRINT = "/" + getRegExForPrefixedName(Modules.QNAME.getLocalName()) - + "/" + getRegExForPrefixedName(Module.QNAME.getLocalName()) - - + "\\[" + "(?" + getRegExForPrefixedName(XmlMappingConstants.TYPE_KEY) + "|" - + getRegExForPrefixedName(XmlMappingConstants.NAME_KEY) + ")" + "=('|\")?(?[^'\"\\]]+)('|\")?" - + "( and |\\]\\[)" + "(?" + getRegExForPrefixedName(XmlMappingConstants.TYPE_KEY) + "|" - + getRegExForPrefixedName(XmlMappingConstants.NAME_KEY) + ")" + "=('|\")?(?[^'\"\\]]+)('|\")?" - + "\\]" - - + "(?.*)"; - - /** - * 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: - * - *
-     * /modules/module[name=instanceName and type=moduleType]/inner[key=b]
-     * 
- */ - private static final String ADDITIONAL_PATTERN_BLUEPRINT = getRegExForPrefixedName("(?.+)") - + "\\[(?" + getRegExForPrefixedName("(.+)") - + ")=('|\")?(?[^'\"\\]]+)('|\")?\\]"; - 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 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 getAdditionalKeys(String elementName, String moduleName) { - HashMap 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; - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/runtime/InstanceRuntime.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/runtime/InstanceRuntime.java deleted file mode 100644 index c0532317d8..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/runtime/InstanceRuntime.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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 childrenMappings; - private final Map jmxToYangChildRbeMapping; - - public InstanceRuntime(InstanceConfig instanceMapping, Map childrenMappings, - Map 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 findChildren(ObjectName innerRootBean, Set childRbeOns) { - final Map wantedProperties = innerRootBean.getKeyPropertyList(); - - return Sets.newHashSet(Collections2.filter(childRbeOns, on -> { - Map localProperties = on.getKeyPropertyList(); - for (Entry 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 getRootBeans(Set 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 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 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 childMappingEntry : childrenMappings.entrySet()) { - Set innerRootBeans = getRootBeans(childRbeOns, childMappingEntry.getKey(), - rootOn.getKeyPropertyList().size()); - - for (ObjectName objectName : innerRootBeans) { - Set 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/runtime/ModuleRuntime.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/runtime/ModuleRuntime.java deleted file mode 100644 index 67fd458db7..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/runtime/ModuleRuntime.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 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 runtimeBeanOns, Document document, - ModuleConfig moduleConfig, ObjectName configBeanON, final EnumResolver enumResolver) { - - Element moduleElement = moduleConfig.toXml(configBeanON, document, namespace, enumResolver); - - ObjectName rootName = findRoot(runtimeBeanOns); - - Set 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/runtime/Runtime.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/runtime/Runtime.java deleted file mode 100644 index 1a5d105314..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/runtime/Runtime.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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> moduleRuntimes; - private final Map> moduleConfigs; - - public Runtime(Map> moduleRuntimes, - Map> moduleConfigs) { - this.moduleRuntimes = moduleRuntimes; - this.moduleConfigs = moduleConfigs; - } - - private Map> mapInstancesToModules(Set instancesToMap) { - Map> 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 multimap = retVal.computeIfAbsent(moduleName, k -> HashMultimap.create()); - - String instanceName = ObjectNameUtil.getInstanceName(objectName); - - multimap.put(instanceName, objectName); - } - return retVal; - } - - public Element toXml(Set instancesToMap, Set configBeans, Document document, - final EnumResolver enumResolver) { - Element root = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.absent()); - - Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY, - Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG)); - root.appendChild(modulesElement); - - Map> moduleToRuntimeInstance = mapInstancesToModules(instancesToMap); - Map>> moduleToConfigInstance = Config.getMappedInstances(configBeans, - moduleConfigs); - - for (String localNamespace : moduleConfigs.keySet()) { - - Map> instanceToMbe = moduleToConfigInstance.get(localNamespace); - - for (String moduleName : moduleConfigs.get(localNamespace).keySet()) { - Multimap 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; - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/AbstractEditConfigStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/AbstractEditConfigStrategy.java deleted file mode 100644 index dcebd4984b..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/AbstractEditConfigStrategy.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 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 configuration, ConfigTransactionClient ta, - String module, String instance, ServiceRegistryWrapper services) throws - ConfigHandlingException; - - abstract void executeStrategy(Map configuration, ConfigTransactionClient ta, - ObjectName objectName, ServiceRegistryWrapper services) throws - ConfigHandlingException; - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/DeleteEditConfigStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/DeleteEditConfigStrategy.java deleted file mode 100644 index c1a1fd47a6..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/DeleteEditConfigStrategy.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 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 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); - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/EditConfigStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/EditConfigStrategy.java deleted file mode 100644 index ac54edf586..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/EditConfigStrategy.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * 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 configuration, - ConfigTransactionClient ta, ServiceRegistryWrapper services) throws - ConfigHandlingException; - -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/EditStrategyType.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/EditStrategyType.java deleted file mode 100644 index 5061592791..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/EditStrategyType.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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 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); - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/MergeEditConfigStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/MergeEditConfigStrategy.java deleted file mode 100644 index 02aa783cb1..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/MergeEditConfigStrategy.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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 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 configuration, ConfigTransactionClient ta, ObjectName on, - ServiceRegistryWrapper services) throws ConfigHandlingException { - - for (Entry 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 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()]); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/MissingInstanceHandlingStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/MissingInstanceHandlingStrategy.java deleted file mode 100644 index 637e837284..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/MissingInstanceHandlingStrategy.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 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 configuration, ConfigTransactionClient ta, - ObjectName objectName, ServiceRegistryWrapper services) { - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/NoneEditConfigStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/NoneEditConfigStrategy.java deleted file mode 100644 index b2d765d748..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/NoneEditConfigStrategy.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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 configuration, - ConfigTransactionClient ta, ServiceRegistryWrapper services) throws ConfigHandlingException { - if (configuration != null && !configuration.isEmpty()) { - for (Map.Entry attrEntry : configuration.entrySet()) { - if (attrEntry.getValue().getEditStrategy().isPresent()) { - final Map 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); - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/ReCreateEditConfigStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/ReCreateEditConfigStrategy.java deleted file mode 100644 index 776abdce40..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/ReCreateEditConfigStrategy.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 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 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); - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/RemoveEditConfigStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/RemoveEditConfigStrategy.java deleted file mode 100644 index 0c071be851..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/RemoveEditConfigStrategy.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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 configuration, ConfigTransactionClient ta, - String module, String instance, ServiceRegistryWrapper services) { - LOG.warn("Unable to delete {}:{}, ServiceInstance not found", module, instance); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/ReplaceEditConfigStrategy.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/ReplaceEditConfigStrategy.java deleted file mode 100644 index 8cc2b9e68d..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/strategy/ReplaceEditConfigStrategy.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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 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 configuration, ConfigTransactionClient ta, ObjectName on, - ServiceRegistryWrapper services) throws ConfigHandlingException { - for (Entry 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); - } - } - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/transactions/TransactionProvider.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/transactions/TransactionProvider.java deleted file mode 100644 index e255757dc1..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/transactions/TransactionProvider.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * 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 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 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 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 ta = getTransaction(); - - if (ta.isPresent()) { - return ta.get(); - } - candidateTx = configRegistryClient.beginConfig(); - allOpenedTransactions.add(candidateTx); - return candidateTx; - } - - public synchronized ObjectName getOrCreateReadTransaction() { - Optional 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 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 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 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 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 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 taON = getTransaction(); - Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + sessionIdForReporting); - wipeInternal(taON.get(), false); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/util/Util.java b/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/util/Util.java deleted file mode 100644 index d704d63037..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/main/java/org/opendaylight/controller/config/facade/xml/util/Util.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/test/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleIdentityRefAttributeReadingStrategyTest.java b/opendaylight/config/config-manager-facade-xml/src/test/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleIdentityRefAttributeReadingStrategyTest.java deleted file mode 100644 index 60d2118bdf..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/test/java/org/opendaylight/controller/config/facade/xml/mapping/attributes/fromxml/SimpleIdentityRefAttributeReadingStrategyTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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, IdentityMapping>> identityMapping = Maps.newHashMap(); - final IdentityMapping value = new IdentityMapping(); - final Optional 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("local")); - assertEquals(QName.create(URI.create("namespace"), rev.toJavaUtil(), "local").toString(), read); - - read = key.readElementContent(XmlElement.fromString("a:local")); - assertEquals(QName.create(URI.create("inner"), rev.toJavaUtil(), "local").toString(), read); - - read = key.readElementContent( - XmlElement.fromString("local").getOnlyChildElement()); - assertEquals(QName.create(URI.create("namespace"), rev.toJavaUtil(), "local").toString(), read); - } -} diff --git a/opendaylight/config/config-manager-facade-xml/src/test/java/org/opendaylight/controller/config/facade/xml/rpc/RuntimeRpcElementResolvedTest.java b/opendaylight/config/config-manager-facade-xml/src/test/java/org/opendaylight/controller/config/facade/xml/rpc/RuntimeRpcElementResolvedTest.java deleted file mode 100644 index babd325c1b..0000000000 --- a/opendaylight/config/config-manager-facade-xml/src/test/java/org/opendaylight/controller/config/facade/xml/rpc/RuntimeRpcElementResolvedTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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 additional; - - @Parameterized.Parameters(name = "{index}: parsed({0}) contains moduleName:{1} and instanceName:{2}") - @SuppressWarnings("linelength") - public static Collection 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()); - } - } -} diff --git a/opendaylight/config/config-manager/pom.xml b/opendaylight/config/config-manager/pom.xml deleted file mode 100644 index 6ee2d1090b..0000000000 --- a/opendaylight/config/config-manager/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-subsystem - 0.9.0-SNAPSHOT - .. - - config-manager - bundle - ${project.artifactId} - - - - - ${project.groupId} - config-api - - - com.google.guava - guava - - - - - org.opendaylight.mdsal - mdsal-binding-generator-impl - - - org.opendaylight.yangtools - concepts - - - - - org.opendaylight.yangtools - mockito-configuration - - - org.opendaylight.yangtools - yang-data-impl - - - org.osgi - org.osgi.core - - - org.slf4j - slf4j-api - - - - - ${project.groupId} - config-util - test - - - ${project.groupId} - config-util - test-jar - test - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - org.apache.felix - maven-bundle-plugin - - - org.opendaylight.controller.config.manager.impl.osgi.ConfigManagerActivator - org.opendaylight.controller.config.manager.* - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - package - - - - - - - diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CloseableServiceReferenceReadableRegistry.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CloseableServiceReferenceReadableRegistry.java deleted file mode 100644 index 87067e8324..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CloseableServiceReferenceReadableRegistry.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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(); -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CommitInfo.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CommitInfo.java deleted file mode 100644 index eb7fd380cf..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/CommitInfo.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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 destroyedFromPreviousTransactions; - private final Map commitMap; - - public CommitInfo(final List destroyedFromPreviousTransactions, - final Map 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 getDestroyedFromPreviousTransactions() { - return destroyedFromPreviousTransactions; - } - - public Map getCommitted() { - return commitMap; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImpl.java deleted file mode 100644 index 41e2b5bf60..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImpl.java +++ /dev/null @@ -1,759 +0,0 @@ -/* - * 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 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> 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> transactions = - transactionsHolder.getCurrentTransactions(); - Entry 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 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 orderedModuleIdentifiers = configTransactionController.secondPhaseCommit(); - txLookupRegistry.close(); - configTransactionController.close(); - - // copy configuration to read only mode - List newInstances = new LinkedList<>(); - List reusedInstances = new LinkedList<>(); - List recreatedInstances = new LinkedList<>(); - - Map 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 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 getOpenConfigs() { - Map> transactions = - transactionsHolder.getCurrentTransactions(); - List result = new ArrayList<>(transactions.size()); - for (Entry - 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> transactions = - transactionsHolder.getCurrentTransactions(); - for (Entry - 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 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 getAvailableModuleNames() { - return new HierarchicalConfigMBeanFactoriesHolder(resolver.getAllFactories()).getModuleNames(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isHealthy() { - return isHealthy; - } - - // filtering methods - - /** - * {@inheritDoc} - */ - @Override - public Set lookupConfigBeans() { - return lookupConfigBeans("*", "*"); - } - - /** - * {@inheritDoc} - */ - @Override - public Set lookupConfigBeans(final String moduleName) { - return lookupConfigBeans(moduleName, "*"); - } - - /** - * {@inheritDoc} - */ - @Override - public Set 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 lookupRuntimeBeans() { - return lookupRuntimeBeans("*", "*"); - } - - /** - * {@inheritDoc} - */ - @Override - public Set 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> getServiceMapping() { - synchronized (readableSRRegistryLock) { - return readableSRRegistry.getServiceMapping(); - } - } - - @Override - public Map lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) { - synchronized (readableSRRegistryLock) { - return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName); - } - } - - @Override - public Set 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 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> 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> getCurrentTransactions() { - // first, remove closed transaction - for (Iterator>> - it = transactions.entrySet().iterator(); it.hasNext();) { - Entry> 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 currentConfig = new ConcurrentHashMap<>(); - - /** - * Add all modules to the internal map. Also add service instance to OSGi - * Service Registry. - */ - public void addAll(final Collection 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 getEntries() { - return currentConfig.values(); - } - - public List getModulesToBeDestroyed() { - List result = new ArrayList<>(); - for (ModuleInternalInfo moduleInternalInfo : getEntries()) { - result.add(moduleInternalInfo.toDestroyedModule()); - } - Collections.sort(result); - return result; - } - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplMXBean.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplMXBean.java deleted file mode 100644 index 827646f334..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplMXBean.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImpl.java deleted file mode 100644 index d5d82dd1cb..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImpl.java +++ /dev/null @@ -1,654 +0,0 @@ -/* - * 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 { - 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> 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> 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 existingModules, - final List 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 lastListOfFactories) { - transactionStatus.checkNotCommitStarted(); - transactionStatus.checkNotAborted(); - - Set oldSet = new HashSet<>(lastListOfFactories); - Set newSet = new HashSet<>(factoriesHolder.getModuleFactories()); - - List toBeAdded = new ArrayList<>(); - List 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 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 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 modulesOfRemovedFactory = dependencyResolverManager.findAllByFactory(removedFactory); - for (ModuleIdentifier name : modulesOfRemovedFactory) { - // remove service refs - final ModuleFactory moduleFactory = dependencyResolverManager.findModuleInternalTransactionalInfo(name) - .getModuleFactory(); - final Set 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 collectedExceptions = new ArrayList<>(); - for (Entry 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 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 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 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 lookupConfigBeans() { - return txLookupRegistry.lookupConfigBeans(); - } - - /** - * {@inheritDoc} - */ - @Override - public Set lookupConfigBeans(final String moduleName) { - return txLookupRegistry.lookupConfigBeans(moduleName); - } - - /** - * {@inheritDoc} - */ - @Override - public Set 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 lookupRuntimeBeans() { - return txLookupRegistry.lookupRuntimeBeans(); - } - - /** - * {@inheritDoc} - */ - @Override - public Set lookupRuntimeBeans(final String moduleName, final String instanceName) { - return txLookupRegistry.lookupRuntimeBeans(moduleName, instanceName); - } - - // -- - - /** - * {@inheritDoc} - */ - @Override - public Set 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 getCurrentlyRegisteredFactories() { - return new ArrayList<>(factoriesHolder.getModuleFactories()); - } - - @Override - public TransactionIdentifier getIdentifier() { - return getTransactionIdentifier(); - } - - @Override - public BundleContext getModuleFactoryBundleContext(final String factoryName) { - Map.Entry 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> getServiceMapping() { - return writableSRRegistry.getServiceMapping(); - } - - @Override - public synchronized Map lookupServiceReferencesByServiceInterfaceName( - final String serviceInterfaceQName) { - return writableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName); - } - - @Override - public synchronized Set 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 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); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplMXBean.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplMXBean.java deleted file mode 100644 index dd506af74f..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplMXBean.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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(); -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerInternal.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerInternal.java deleted file mode 100644 index 5b7ecb938c..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerInternal.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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 entries, - List 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 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 getCurrentlyRegisteredFactories(); - - BundleContext getModuleFactoryBundleContext(String factoryName); - - SearchableServiceReferenceWritableRegistry getWritableRegistry(); - - TransactionIdentifier getTransactionIdentifier(); - - @Override - void close(); -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionLookupRegistry.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionLookupRegistry.java deleted file mode 100644 index f9a5acffad..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionLookupRegistry.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * 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> allCurrentFactories; - - interface TransactionJMXRegistratorFactory { - TransactionJMXRegistrator create(); - } - - ConfigTransactionLookupRegistry(final TransactionIdentifier transactionIdentifier, - final TransactionJMXRegistratorFactory factory, - final Map> 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 lookupConfigBeans() { - return lookupConfigBeans("*", "*"); - } - - /** - * {@inheritDoc} - */ - @Override - public Set lookupConfigBeans(final String moduleName) { - return lookupConfigBeans(moduleName, "*"); - } - - /** - * {@inheritDoc} - */ - @Override - public Set 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 getAvailableModuleFactoryQNames() { - return ModuleQNameUtil.getQNames(allCurrentFactories); - } - - /** - * {@inheritDoc} - */ - @Override - public Set lookupRuntimeBeans() { - return lookupRuntimeBeans("*", "*"); - } - - /** - * {@inheritDoc} - */ - @Override - public Set 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 + '}'; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/DeadlockMonitor.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/DeadlockMonitor.java deleted file mode 100644 index 6115326632..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/DeadlockMonitor.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * 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 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 + '}'; - } - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ModuleInternalInfo.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ModuleInternalInfo.java deleted file mode 100644 index fa263bc933..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ModuleInternalInfo.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * 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, Identifiable { - - 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; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/SearchableServiceReferenceWritableRegistry.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/SearchableServiceReferenceWritableRegistry.java deleted file mode 100644 index 288f2ac669..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/SearchableServiceReferenceWritableRegistry.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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 findServiceInterfaces( - ModuleIdentifier moduleIdentifier); -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java deleted file mode 100644 index b682766f75..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImpl.java +++ /dev/null @@ -1,571 +0,0 @@ -/* - * 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 factories; - private final Map> 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> - namespacesToAnnotations; - private final Map serviceQNamesToAnnotations; - // all Service Interface qNames for sanity checking - private final Set allQNames; - Map> modulesToServiceRef = - new HashMap<>(); - - // actual reference database - private final Map refNames = new HashMap<>(); - private final boolean writable; - private final Map> - managementBeans = new HashMap<>(); - - private ServiceReferenceRegistryImpl(final Map factories, - final LookupRegistry lookupRegistry, - final ServiceReferenceTransactionRegistratorFactory serviceReferenceRegistratorFactory, - final boolean writable) { - this.factories = factories; - this.writable = writable; - this.lookupRegistry = lookupRegistry; - - this.serviceReferenceRegistrator = serviceReferenceRegistratorFactory.create(); - - Map> modifiableFactoryNamesToQNames = new HashMap<>(); - Set allAnnotations = new HashSet<>(); - Set allQNameSet = new HashSet<>(); - - for (Entry 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 siAnnotations = InterfacesHelper - .getServiceInterfaceAnnotations(entry.getValue()); - Set 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> - modifiableNamespacesToAnnotations = new HashMap<>(); - Map - modifiableServiceQNamesToAnnotations = new HashMap<>(); - for (ServiceInterfaceAnnotation sia : allAnnotations) { - Map 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 lookupConfigBeans() { - throw new UnsupportedOperationException(); - } - - @Override - public Set lookupConfigBeans(final String moduleName) { - throw new UnsupportedOperationException(); - } - - @Override - public Set 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 getAvailableModuleFactoryQNames() { - throw new UnsupportedOperationException(); - } - - @Override - public Set lookupRuntimeBeans() { - throw new UnsupportedOperationException(); - } - - @Override - public Set 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.emptyMap(), lookupRegistry, - serviceReferenceRegistratorFactory, false); - } - - public static SearchableServiceReferenceWritableRegistry createSRWritableRegistry( - final ServiceReferenceReadableRegistry oldReadableRegistry, - final ConfigTransactionLookupRegistry txLookupRegistry, - final Map> currentlyRegisteredFactories) { - - if (txLookupRegistry == null) { - throw new IllegalArgumentException("txLookupRegistry is null"); - } - ServiceReferenceRegistryImpl old = (ServiceReferenceRegistryImpl) oldReadableRegistry; - Map 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> - 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 extractFactoriesMap( - final Map> currentlyRegisteredFactories) { - Map result = new HashMap<>(); - for (Entry> entry : currentlyRegisteredFactories.entrySet()) { - result.put(entry.getKey(), entry.getValue().getKey()); - } - return result; - } - - @Override - public Map findServiceInterfaces( - final ModuleIdentifier moduleIdentifier) { - Map result = modulesToServiceRef - .get(moduleIdentifier); - if (result == null) { - return Collections.emptyMap(); - } - return Collections.unmodifiableMap(result); - } - - @Override - public synchronized Set lookupServiceInterfaceNames(final ObjectName objectName) - throws InstanceNotFoundException { - lookupRegistry.checkConfigBeanExists(objectName); - - String factoryName = ObjectNameUtil.getFactoryName(objectName); - Set 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 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> getServiceMapping() { - Map> result = new HashMap<>(); - for (Entry entry : refNames.entrySet()) { - String name = entry.getKey().getServiceInterfaceQName(); - Map 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 lookupServiceReferencesByServiceInterfaceName( - final String serviceInterfaceQName) { - Map> serviceMapping = getServiceMapping(); - Map 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 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 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 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 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 serviceInterfaceQNames = factoryNamesToQNames.get(factoryName); - return removeServiceReferences(moduleObjectName, serviceInterfaceQNames); - } - - private boolean removeServiceReferences(final ObjectName moduleObjectName, final Set names) - throws InstanceNotFoundException { - ObjectNameUtil.checkType(moduleObjectName, ObjectNameUtil.TYPE_MODULE); - assertWritable(); - Set serviceReferencesLinkingTo = findServiceReferencesLinkingTo(moduleObjectName, names); - for (ServiceReference sr : serviceReferencesLinkingTo) { - removeServiceReference(sr); - } - return !serviceReferencesLinkingTo.isEmpty(); - } - - private Set findServiceReferencesLinkingTo(final ObjectName moduleObjectName, - final Set 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 result = new HashSet<>(); - for (Entry 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(); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionIdentifier.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionIdentifier.java deleted file mode 100644 index ac056a85ae..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionIdentifier.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionStatus.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionStatus.java deleted file mode 100644 index af333c3893..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/TransactionStatus.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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"); - } - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverImpl.java deleted file mode 100644 index f46113fb9a..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverImpl.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * 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 { - 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 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 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 resolveInstance(final Class 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 Class resolveIdentity(final IdentityAttributeRef identityRef, - final Class 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) 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 void validateIdentity(final IdentityAttributeRef identityRef, - final Class 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 chainForDetectingCycles) { - int maxDepth = 0; - final LinkedHashSet 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 newMXBeanProxy(final ObjectName name, final Class interfaceClass) { - ObjectName newName = translateServiceRefIfPossible(name); - // add transaction name - newName = ObjectNameUtil.withTransactionName(newName, this.transactionName); - return JMX.newMXBeanProxy(this.beanServer, newName, interfaceClass); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManager.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManager.java deleted file mode 100644 index 1a2c6b7b22..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManager.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * 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 - 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 getAllSorted() { - transactionStatus.checkCommitStarted(); - List sorted = new ArrayList<>(moduleIdentifiersToDependencyResolverMap.values()); - for (DependencyResolverImpl dri : sorted) { - dri.countMaxDependencyDepth(this); - } - Collections.sort(sorted); - return sorted; - } - - public List getSortedModuleIdentifiers() { - List 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 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 getAllModules() { - return modulesHolder.getAllModules(); - } - - public void assertNotExists(final ModuleIdentifier moduleIdentifier) throws InstanceAlreadyExistsException { - modulesHolder.assertNotExists(moduleIdentifier); - } - - public List findAllByFactory(final ModuleFactory factory) { - List 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(); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DestroyedModule.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DestroyedModule.java deleted file mode 100644 index 6f4ed6366a..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DestroyedModule.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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, Identifiable { - 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; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModuleInternalTransactionalInfo.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModuleInternalTransactionalInfo.java deleted file mode 100644 index e8a6d512a4..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModuleInternalTransactionalInfo.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * 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 { - 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; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModulesHolder.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModulesHolder.java deleted file mode 100644 index 1132f991d1..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/ModulesHolder.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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 commitMap = new HashMap<>(); - - @GuardedBy("this") - private final Set unorderedDestroyedFromPreviousTransactions = new HashSet<>(); - - ModulesHolder(final TransactionIdentifier transactionIdentifier) { - this.transactionIdentifier = transactionIdentifier; - } - - public CommitInfo toCommitInfo() { - List 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 getAllModules() { - Map 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 getAllInfos() { - return commitMap.values(); - } - - @Override - public void close() { - unorderedDestroyedFromPreviousTransactions.clear(); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapper.java deleted file mode 100644 index 54f7946db5..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapper.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * 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 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> 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 attributeHolderMap, final MBeanOperationInfo[] operations, - final Set> jmxInterfaces) { - - String description = findDescription(module.getClass(), jmxInterfaces); - MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0]; - List 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> jmxInterfaces) { - List 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 buildMBeanInfo(final boolean writable, final ModuleIdentifier modId, - final Set> jmxInterfaces, final ObjectName internalObjectName) { - - // internal variables for describing MBean elements - Set 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 attributeMap = new HashMap<>(); - for (MBeanAttributeInfo a : internalInfo.getAttributes()) { - attributeMap.put(a.getName(), a); - } - Map 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); - } - -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsHelper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsHelper.java deleted file mode 100644 index f9548ae08e..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsHelper.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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 - * generic type of annotation - * @return list of found annotations - */ - static List findMethodAnnotationInSuperClassesAndIfcs(final Method setter, - final Class annotationType, final Set> inspectedInterfaces) { - Builder 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 List findClassAnnotationInSuperClassesAndIfcs(final Class clazz, - final Class annotationType, final Set> interfaces) { - List 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 descriptions) { - StringBuilder builder = new StringBuilder(); - for (Description d : descriptions) { - if (builder.length() != 0) { - builder.append("\n"); - } - builder.append(d.value()); - - } - return builder.toString(); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AttributeHolder.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AttributeHolder.java deleted file mode 100644 index ff607d32e5..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AttributeHolder.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * 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> 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> jmxInterfaces) { - List 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> inspectedInterfaces) { - - // only allow setX(ObjectName y) or setX(ObjectName[] y) or - // setX(List y) to continue - - if (setter.getParameterTypes().length > 1 - || !PERMITTED_PARAMETER_TYPES_FOR_DEPENDENCY_SETTER.contains(setter.getParameterTypes()[0])) { - return null; - } - - List foundRequireInterfaces = AnnotationsHelper - .findMethodAnnotationInSuperClassesAndIfcs(setter, RequireInterface.class, inspectedInterfaces); - // make sure the list if not empty contains always annotation with same - // value - Set> 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); - } - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicMBeanModuleWrapper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicMBeanModuleWrapper.java deleted file mode 100644 index d095839d1e..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicMBeanModuleWrapper.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * 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 { - -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapper.java deleted file mode 100644 index f768731e51..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapper.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapper.java deleted file mode 100644 index 1ac299bcbb..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapper.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * 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. - *

- * 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. - *

- */ -@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(); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/ReadOnlyAtomicBoolean.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/ReadOnlyAtomicBoolean.java deleted file mode 100644 index 8b66ad7563..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/ReadOnlyAtomicBoolean.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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(); - } - - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolder.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolder.java deleted file mode 100644 index e07d0d76e1..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolder.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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> moduleNamesToConfigBeanFactories; - private final Set moduleNames; - private final List moduleFactories; - - /** - * Create instance. - * - * @param factoriesMap map of factories - * @throws IllegalArgumentException - * if unique constraint on module names is violated - */ - public HierarchicalConfigMBeanFactoriesHolder( - final Map> factoriesMap) { - this.moduleNamesToConfigBeanFactories = Collections.unmodifiableMap(factoriesMap); - moduleNames = Collections.unmodifiableSet(new TreeSet<>(moduleNamesToConfigBeanFactories.keySet())); - List factories = new ArrayList<>(this.moduleNamesToConfigBeanFactories.size()); - Collection> entryCollection = this.moduleNamesToConfigBeanFactories - .values(); - for (Map.Entry 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 result = moduleNamesToConfigBeanFactories.get(moduleName); - if (result == null) { - throw new ModuleFactoryNotFoundException(moduleName); - } - return result.getKey(); - } - - public Set getModuleNames() { - return moduleNames; - } - - public List getModuleFactories() { - return moduleFactories; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/ModuleFactoriesResolver.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/ModuleFactoriesResolver.java deleted file mode 100644 index 15122b4696..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/ModuleFactoriesResolver.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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> getAllFactories(); - -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/BaseJMXRegistrator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/BaseJMXRegistrator.java deleted file mode 100644 index a4c69a0904..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/BaseJMXRegistrator.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 queryNames(final ObjectName name, final QueryExp query) { - return internalJMXRegistrator.queryNames(name, query); - } - - public Set getRegisteredObjectNames() { - return internalJMXRegistrator.getRegisteredObjectNames(); - } - - @Override - public InternalJMXRegistrator createChild() { - return internalJMXRegistrator.createChild(); - } - - @Override - public void close() { - internalJMXRegistrator.close(); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ConfigRegistryJMXRegistrator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ConfigRegistryJMXRegistrator.java deleted file mode 100644 index d782764679..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ConfigRegistryJMXRegistrator.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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(); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/HierarchicalRuntimeBeanRegistrationImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/HierarchicalRuntimeBeanRegistrationImpl.java deleted file mode 100644 index f621392e79..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/HierarchicalRuntimeBeanRegistrationImpl.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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 properties; - - public HierarchicalRuntimeBeanRegistrationImpl( - final ModuleIdentifier moduleIdentifier, - final InternalJMXRegistrator internalJMXRegistrator, - final Map 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 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(); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistration.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistration.java deleted file mode 100644 index 5698e54fd1..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistration.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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 { - 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()); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistrator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistrator.java deleted file mode 100644 index f4b326ea19..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/InternalJMXRegistrator.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * 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 registeredObjectNames = new HashSet<>(1); - @GuardedBy("this") - private final List 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 newMBeanProxy(final ObjectName objectName, final Class interfaceClass) { - return JMX.newMBeanProxy(getMBeanServer(), objectName, interfaceClass); - } - - public final T newMBeanProxy(final ObjectName objectName, final Class interfaceClass, - final boolean notificationBroadcaster) { - return JMX.newMBeanProxy(getMBeanServer(), objectName, interfaceClass, notificationBroadcaster); - } - - public final T newMXBeanProxy(final ObjectName objectName, final Class interfaceClass) { - return JMX.newMXBeanProxy(getMBeanServer(), objectName, interfaceClass); - } - - public final T newMXBeanProxy(final ObjectName objectName, final Class interfaceClass, - final boolean notificationBroadcaster) { - return JMX.newMXBeanProxy(getMBeanServer(), objectName, interfaceClass, notificationBroadcaster); - } - - public final Set getRegisteredObjectNames() { - return Collections.unmodifiableSet(registeredObjectNames); - } - - public final Set 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 getSameNames(final Set superSet) { - final Set result = new HashSet<>(superSet); - result.retainAll(registeredObjectNames); - - for (InternalJMXRegistrator child : children) { - result.addAll(child.getSameNames(superSet)); - } - return result; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/JMXNotifierConfigRegistry.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/JMXNotifierConfigRegistry.java deleted file mode 100644 index 50cccc796f..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/JMXNotifierConfigRegistry.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * 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 getOpenConfigs() { - return delegate.getOpenConfigs(); - } - - @Override - public boolean isHealthy() { - return delegate.isHealthy(); - } - - @Override - public Set getAvailableModuleNames() { - return delegate.getAvailableModuleNames(); - } - - @Override - public Set lookupConfigBeans() { - return delegate.lookupConfigBeans(); - } - - @Override - public Set lookupConfigBeans(final String moduleName) { - return delegate.lookupConfigBeans(moduleName); - } - - @Override - public Set 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 getAvailableModuleFactoryQNames() { - return delegate.getAvailableModuleFactoryQNames(); - } - - @Override - public Set lookupRuntimeBeans() { - return delegate.lookupRuntimeBeans(); - } - - @Override - public Set 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> getServiceMapping() { - return delegate.getServiceMapping(); - } - - @Override - public Map lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) { - return delegate.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName); - } - - @Override - public Set 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)); - } - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ModuleJMXRegistrator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ModuleJMXRegistrator.java deleted file mode 100644 index 206a623990..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ModuleJMXRegistrator.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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(); - } - -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/NestableJMXRegistrator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/NestableJMXRegistrator.java deleted file mode 100644 index ff78e0257b..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/NestableJMXRegistrator.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * 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(); -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/RootRuntimeBeanRegistratorImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/RootRuntimeBeanRegistratorImpl.java deleted file mode 100644 index e84d2ee953..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/RootRuntimeBeanRegistratorImpl.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.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.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); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReference.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReference.java deleted file mode 100644 index 88646b4cc1..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReference.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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 - + '\'' + '}'; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBeanImpl.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBeanImpl.java deleted file mode 100644 index b4938f32fb..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBeanImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceRegistrator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceRegistrator.java deleted file mode 100644 index 5dc3fe2eca..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceRegistrator.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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); - } - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/TransactionJMXRegistrator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/TransactionJMXRegistrator.java deleted file mode 100644 index ceba1c8905..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/TransactionJMXRegistrator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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 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(); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/TransactionModuleJMXRegistrator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/TransactionModuleJMXRegistrator.java deleted file mode 100644 index dbffe4cc90..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/TransactionModuleJMXRegistrator.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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 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(); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BeanToOsgiServiceManager.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BeanToOsgiServiceManager.java deleted file mode 100644 index 9031f23462..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BeanToOsgiServiceManager.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * 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 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> serviceRegistrations; - @GuardedBy("this") - private final Map serviceNamesToAnnotations; - - public OsgiRegistration(final AutoCloseable instance, final ModuleIdentifier moduleIdentifier, - final BundleContext bundleContext, - final Map serviceNamesToAnnotations) { - this.instance = instance; - this.moduleIdentifier = moduleIdentifier; - this.serviceNamesToAnnotations = serviceNamesToAnnotations; - this.serviceRegistrations = registerToSR(instance, bundleContext, serviceNamesToAnnotations); - } - - private static Set> registerToSR(final AutoCloseable instance, - final BundleContext bundleContext, - final Map serviceNamesToAnnotations) { - Set> serviceRegistrations = new HashSet<>(); - for (Entry 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 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 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> newRegs = registerToSR(instance, bundleContext, newAnnotationMapping); - serviceRegistrations.clear(); - serviceRegistrations.addAll(newRegs); - } - } - - private static Dictionary createProps(final String serviceName) { - Hashtable result = new Hashtable<>(); - result.put(SERVICE_NAME_OSGI_PROP, serviceName); - return result; - } - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTracker.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTracker.java deleted file mode 100644 index 2649b145d0..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTracker.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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 { - 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 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 moduleFactoryServiceReference, - final Object object) { - blankTransactionAsync(); - } - - @Override - public void removedService(final ServiceReference moduleFactoryServiceReference, - final Object object) { - blankTransactionAsync(); - } - - @VisibleForTesting - interface BlankTransaction { - CommitStatus hit() throws ValidationException, ConflictingVersionException; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolver.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolver.java deleted file mode 100644 index 28f512d848..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolver.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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> getAllFactories() { - Collection> serviceReferences; - try { - serviceReferences = bundleContext.getServiceReferences(ModuleFactory.class, null); - } catch (final InvalidSyntaxException e) { - throw new IllegalStateException(e); - } - Map> result = new HashMap<>(serviceReferences.size()); - for (ServiceReference 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 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; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ConfigManagerActivator.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ConfigManagerActivator.java deleted file mode 100644 index d1c3d767bf..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ConfigManagerActivator.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * 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>> 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 serviceTracker = new ServiceTracker<>(context, - ModuleFactory.class, blankTransactionServiceTracker); - serviceTracker.open(); - - final AutoCloseable configMgrReg = OsgiRegistrationUtil.registerService(context, this, - ConfigSystemService.class); - - final List 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(); - } - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTracker.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTracker.java deleted file mode 100644 index 132005ac7c..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTracker.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * 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. - * - *

- * Primary customizer may return tracking object, which will be passed to it - * during invocation of - * {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)} - * - *

- * 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. - * - *

- * 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. - * - *

- * Method - * {@link BundleTrackerCustomizer#removedBundle(Bundle, BundleEvent, Object)} is - * never invoked on registered trackers. - * - * @param value - */ -public final class ExtensibleBundleTracker extends BundleTracker> { - private static final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder() - .setNameFormat("config-bundle-tracker-%d").build(); - private final ExecutorService eventExecutor; - private final BundleTrackerCustomizer primaryTracker; - private final BundleTrackerCustomizer[] additionalTrackers; - - private static final Logger LOG = LoggerFactory.getLogger(ExtensibleBundleTracker.class); - - public ExtensibleBundleTracker(final BundleContext context, - final BundleTrackerCustomizer primaryBundleTrackerCustomizer, - final BundleTrackerCustomizer... additionalBundleTrackerCustomizers) { - this(context, Bundle.ACTIVE, primaryBundleTrackerCustomizer, additionalBundleTrackerCustomizers); - } - - public ExtensibleBundleTracker(final BundleContext context, final int bundleState, - final BundleTrackerCustomizer 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 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 object) { - // Intentionally NOOP - } - - @Override - public void removedBundle(final Bundle bundle, final BundleEvent event, final Future 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); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTracker.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTracker.java deleted file mode 100644 index e89d6c87aa..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTracker.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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 { - 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); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/BindingContextProvider.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/BindingContextProvider.java deleted file mode 100644 index 6cf831510b..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/BindingContextProvider.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/ModuleInfoBundleTracker.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/ModuleInfoBundleTracker.java deleted file mode 100644 index cfbd95a39e..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/ModuleInfoBundleTracker.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * 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>> { - - 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>> tracker; - private boolean starting; - - public ModuleInfoBundleTracker(final RefreshingSCPModuleInfoRegistry moduleInfoRegistry) { - this.moduleInfoRegistry = moduleInfoRegistry; - } - - public void open(final BundleTracker>> 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> 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> 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> object) { - } - - @Override - @SuppressWarnings("IllegalCatch") - public void removedBundle(final Bundle bundle, final BundleEvent event, - final Collection> regs) { - if (regs == null) { - return; - } - - for (ObjectRegistration 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); - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/RefreshingSCPModuleInfoRegistry.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/RefreshingSCPModuleInfoRegistry.java deleted file mode 100644 index d59232cf08..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/RefreshingSCPModuleInfoRegistry.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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 sourceProvider; - private final BindingContextProvider bindingContextProvider; - private final ClassLoadingStrategy classLoadingStrat; - - private volatile ServiceRegistration osgiReg; - - public RefreshingSCPModuleInfoRegistry(final ModuleInfoRegistry moduleInfoRegistry, - final SchemaContextProvider schemaContextProvider, final ClassLoadingStrategy classLoadingStrat, - final SchemaSourceProvider 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()); - } - - public synchronized void updateService() { - if (this.osgiReg != null) { - this.bindingContextProvider.update(this.classLoadingStrat, this.schemaContextProvider); - - final Dictionary 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 registerModuleInfo(final YangModuleInfo yangModuleInfo) { - final ObjectRegistration 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 { - private final ObjectRegistration inner; - - ObjectRegistrationWrapper(final ObjectRegistration 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(); - } - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java deleted file mode 100644 index 059ba45ec9..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelper.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * 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> getAllInterfaces(Class clazz) { - if (clazz.isInterface()) { - throw new IllegalArgumentException(clazz + " should not be an interface"); - } - // getInterfaces gets interfaces implemented directly by this class - Set> 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> getAllSuperInterfaces(final Set> ifcs) { - Set> interfaces = new HashSet<>(ifcs); // create copy to modify - // each interface can extend other interfaces - Set> result = new HashSet<>(); - while (!interfaces.isEmpty()) { - Iterator> 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> getMXInterfaces(final Class configBeanClass) { - Set> allInterfaces = getAllInterfaces(configBeanClass); - Set> 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> getServiceInterfaces(final Class configBeanClass) { - Set> allInterfaces = getAllInterfaces(configBeanClass); - Set> 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> getAllAbstractServiceClasses( - final Class configBeanClass) { - - Set> foundGeneratedSIClasses = new HashSet<>(); - for (Class clazz : getAllInterfaces(configBeanClass)) { - if (AbstractServiceInterface.class.isAssignableFrom(clazz) - && !AbstractServiceInterface.class.equals(clazz)) { - foundGeneratedSIClasses.add((Class) 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> getOsgiRegistrationTypes(final Class configBeanClass) { - Set> serviceInterfaces = getServiceInterfaces(configBeanClass); - Set> result = new HashSet<>(); - for (Class clazz : serviceInterfaces) { - ServiceInterfaceAnnotation annotation = clazz.getAnnotation(ServiceInterfaceAnnotation.class); - result.add(annotation.osgiRegistrationType()); - } - return result; - } - - public static Set getQNames(final Set siAnnotations) { - Set names = new HashSet<>(); - for (ServiceInterfaceAnnotation sia : siAnnotations) { - names.add(sia.value()); - } - return ImmutableSet.copyOf(names); - } - - public static Set getServiceInterfaceAnnotations(final ModuleFactory factory) { - Set> implementedServiceIntefaces = Collections - .unmodifiableSet(factory.getImplementedServiceIntefaces()); - return getServiceInterfaceAnnotations(implementedServiceIntefaces); - } - - private static Set getServiceInterfaceAnnotations( - final Set> implementedServiceIntefaces) { - Set> inspected = getAllAbstractServiceInterfaceClasses( - implementedServiceIntefaces); - Set 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> getAllAbstractServiceInterfaceClasses( - final Set> directlyImplementedAbstractSIs) { - - Set> allInterfaces = getAllSuperInterfaces(directlyImplementedAbstractSIs); - Set> result = new HashSet<>(); - for (Class ifc : allInterfaces) { - if (AbstractServiceInterface.class.isAssignableFrom(ifc) && !ifc.equals(AbstractServiceInterface.class)) { - result.add((Class) ifc); - } - } - return result; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/LookupBeansUtil.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/LookupBeansUtil.java deleted file mode 100644 index 92184f4048..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/LookupBeansUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 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(); - } - -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/ModuleQNameUtil.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/ModuleQNameUtil.java deleted file mode 100644 index e1c73df413..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/ModuleQNameUtil.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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 getQNames(final Map> resolved) { - final Set result = new HashSet<>(); - for (final Entry 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; - } -} diff --git a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java b/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java deleted file mode 100644 index 816f9c6ca0..0000000000 --- a/opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtil.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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 AutoCloseable registerService(final BundleContext bundleContext, final T service, - final Class... interfaces) { - checkNotNull(service); - checkNotNull(interfaces); - List autoCloseableList = new ArrayList<>(); - for (Class ifc : interfaces) { - ServiceRegistration 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 list) { - checkNotNull(list); - - return () -> { - Exception firstException = null; - for (ListIterator 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; - } - }; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/ConfigRegistryImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/ConfigRegistryImplTest.java deleted file mode 100644 index 55e8bb2a66..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/ConfigRegistryImplTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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); - } - } - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java deleted file mode 100644 index 628baeebab..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractConfigTest.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * 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 registrations = new LinkedList<>(); - - @Override - public void handleServiceRegistration(final Class clazz, final Object serviceInstance, - final Dictionary props) { - this.registrations.add(new RegistrationHolder(clazz, serviceInstance, props)); - } - - public List getRegistrations() { - return this.registrations; - } - - protected static class RegistrationHolder { - protected final Class clazz; - protected final Object instance; - protected final Dictionary props; - - public RegistrationHolder(final Class clazz, final Object instance, final Dictionary 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.any(), any(), - Matchers.>any()); - doAnswer(answer).when(this.mockedContext).registerService(Matchers.>any(), any(), - Matchers.>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 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 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 props); - } - - private class RegisterServiceAnswer implements Answer> { - @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 props = (Dictionary) 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 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 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 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(); - } - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractLockedPlatformMBeanServerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractLockedPlatformMBeanServerTest.java deleted file mode 100644 index ced512203e..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractLockedPlatformMBeanServerTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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 { - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractMockedModule.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractMockedModule.java deleted file mode 100644 index 1acf6b2fee..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/AbstractMockedModule.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ClassBasedModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ClassBasedModuleFactory.java deleted file mode 100644 index 93661699c4..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ClassBasedModuleFactory.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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 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 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 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 serviceInterface) { - Class[] classes = configBeanClass.getInterfaces(); - List> 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 getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, - final BundleContext bundleContext) { - return new HashSet<>(); - } - - @Override - public Set> getImplementedServiceIntefaces() { - return InterfacesHelper.getAllAbstractServiceClasses(configBeanClass); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplLookupTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplLookupTest.java deleted file mode 100644 index 8368a2723f..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigRegistryImplLookupTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * 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.emptyMap()); - private static final ObjectName NAME6 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEA, INSTANCE_NAMEB, - Collections.emptyMap()); - private static final ObjectName NAME8 = ObjectNameUtil.createRuntimeBeanName(MODULE_NAMEB, INSTANCE_NAMEA, - Collections.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 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 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 bean = configRegistryImpl.lookupConfigBeans(MODULE_NAMEA); - assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3), bean); - } - - @Test - public void testLookupConfigBeanWithModuleNameAndInstanceName() throws Exception { - Set bean = configRegistryImpl.lookupConfigBeans(MODULE_NAMEA, INSTANCE_NAMEA); - assertEquals(Sets.newHashSet(NAME1), bean); - } - - @Test - public void testLookupRuntimeBeans() throws Exception { - Set 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 beans = configRegistryImpl.lookupRuntimeBeans(MODULE_NAMEA, INSTANCE_NAMEA); - assertEquals(Sets.newHashSet(NAME5), beans); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplTest.java deleted file mode 100644 index 82666e8e6a..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionControllerImplTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * 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> 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 beans = testedTxController.lookupConfigBeans(); - assertEquals(Sets.newHashSet(NAME1, NAME2, NAME3), beans); - } - - @Test - public void testLookupConfigBeansWithModuleName() { - Set beans = testedTxController.lookupConfigBeans(MODULE_NAME124); - assertEquals(Sets.newHashSet(NAME1, NAME2), beans); - } - - @Test - public void lookupConfigBeansWithModuleNameAndImplName() throws Exception { - Set beans = testedTxController.lookupConfigBeans(MODULE_NAME124, INSTANCE_NAME134); - assertEquals(Sets.newHashSet(NAME1), beans); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionManagerImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionManagerImplTest.java deleted file mode 100644 index ede2a805a8..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ConfigTransactionManagerImplTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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(); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java deleted file mode 100644 index 5ab1557023..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * 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 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> serviceMapping = configRegistryClient.getServiceMapping(); - Map> expectedMapping = ImmutableMap.of(TestingThreadPoolServiceInterface.QNAME, - (Map) ImmutableMap.of(refName, withoutTransactionName(scheduledTPTransactionON))); - assertEquals(expectedMapping, serviceMapping); - - // destroy all - ConfigTransactionJMXClient transaction4 = configRegistryClient.createTransaction(); - Set 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")); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java deleted file mode 100644 index 0f099e77b0..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dependencyresolver/DependencyResolverManagerTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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 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; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapperTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapperTest.java deleted file mode 100644 index 6f65a1e153..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AbstractDynamicWrapperTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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()); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsTest.java deleted file mode 100644 index 4efbebbf46..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/AnnotationsTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * 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> inspectedInterfaces, final Class 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> 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> 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> 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> 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> exportedInterfaces = Sets.>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"); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapperTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapperTest.java deleted file mode 100644 index ed8e588d23..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicReadableWrapperTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * 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()); - } - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapperTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapperTest.java deleted file mode 100644 index 48accc56ac..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapperTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * 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); - } - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HardcodedModuleFactoriesResolver.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HardcodedModuleFactoriesResolver.java deleted file mode 100644 index b6cc61e1e3..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HardcodedModuleFactoriesResolver.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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> 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 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> getAllFactories() { - return factories; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolderTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolderTest.java deleted file mode 100644 index 7611b92d7a..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/factoriesresolver/HierarchicalConfigMBeanFactoriesHolderTest.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * 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 { -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java deleted file mode 100644 index ca21fef902..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BlankTransactionServiceTrackerTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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.emptyList(), Collections.emptyList(), - Collections.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 getMockServiceReference() { - return mock(ServiceReference.class); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java deleted file mode 100644 index 4ac414616b..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/BundleContextBackedModuleFactoriesResolverTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * 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> 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(); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTrackerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTrackerTest.java deleted file mode 100644 index ed128799a2..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ExtensibleBundleTrackerTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * 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 primaryTracker; - @Mock - private BundleTrackerCustomizer additionalTracker; - - private ExtensibleBundleTracker 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); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java deleted file mode 100644 index 7f6253ea46..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/osgi/ModuleFactoryBundleTrackerTest.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * 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 serviceInterface) { - throw new UnsupportedOperationException(); - } - - @Override - public Set> getImplementedServiceIntefaces() { - throw new UnsupportedOperationException(); - } - - @Override - public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, - final BundleContext bundleContext) { - throw new UnsupportedOperationException(); - } - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/RuntimeBeanRegistratorImplTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/RuntimeBeanRegistratorImplTest.java deleted file mode 100644 index e55e4f76b1..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/RuntimeBeanRegistratorImplTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * 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 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.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(); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/TestingRuntimeBean.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/TestingRuntimeBean.java deleted file mode 100644 index 96960d3378..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/TestingRuntimeBean.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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() { - - } - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/TestingRuntimeBeanMXBean.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/TestingRuntimeBeanMXBean.java deleted file mode 100644 index 3d4634f45d..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/runtimembean/TestingRuntimeBeanMXBean.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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(); -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java deleted file mode 100644 index ba105bc09e..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/InterfacesHelperTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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> expected = Sets.>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.>emptySet(), InterfacesHelper.getServiceInterfaces(SubClass.class)); - assertEquals(Sets.>newHashSet(Service.class, SubService.class), - InterfacesHelper.getServiceInterfaces(SubClassWithService.class)); - } - - @Test - public void testGetOsgiRegistrationTypes() throws Exception { - assertEquals(Collections.>emptySet(), InterfacesHelper.getOsgiRegistrationTypes(SubClass.class)); - assertEquals(Sets.>newHashSet(SuperA.class, SuperC.class), - InterfacesHelper.getOsgiRegistrationTypes(SubClassWithService.class)); - } - - @Test - public void testGetMXInterfaces() { - Set> expected = Sets.>newHashSet(SuperBMXBean.class, SubA.class); - assertEquals(expected, InterfacesHelper.getMXInterfaces(SubClass.class)); - } - - @Test - public void testGetAllAbstractServiceInterfaceClasses() { - Class clazz = TestingScheduledThreadPoolServiceInterface.class; - Set> input = new HashSet<>(); - input.add(clazz); - Set> result = InterfacesHelper - .getAllAbstractServiceInterfaceClasses(input); - - Set> expected = ImmutableSet.of((Class) TestingScheduledThreadPoolServiceInterface.class, - TestingThreadPoolServiceInterface.class); - assertEquals(expected, result); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java deleted file mode 100644 index 6763facae5..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/util/OsgiRegistrationUtilTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 { - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingAPSP.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingAPSP.java deleted file mode 100644 index a4c1a6f0bf..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingAPSP.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPConfigMXBean.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPConfigMXBean.java deleted file mode 100644 index e215d8853a..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPConfigMXBean.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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(); -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPImpl.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPImpl.java deleted file mode 100644 index 377a176136..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModule.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModule.java deleted file mode 100644 index 656cf04c28..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModule.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModuleFactory.java deleted file mode 100644 index 4ce5dc91dd..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPModuleFactory.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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 serviceInterface) { - return false; - } - - @Override - public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, - final BundleContext context) { - return new HashSet<>(); - } - - @Override - public Set> getImplementedServiceIntefaces() { - return Collections.emptySet(); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/package-info.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/package-info.java deleted file mode 100644 index f37aa5a2ff..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * 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; diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/AbstractParallelAPSPTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/AbstractParallelAPSPTest.java deleted file mode 100644 index 4f1664ad46..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/AbstractParallelAPSPTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/DependentWiringTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/DependentWiringTest.java deleted file mode 100644 index e6f5490864..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/DependentWiringTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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> exception : e.getFailedValidations() - .entrySet()) { - for (Map.Entry 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> exception : e.getFailedValidations() - .entrySet()) { - for (Map.Entry 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(); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/MockedDependenciesTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/MockedDependenciesTest.java deleted file mode 100644 index 1e0bebbf06..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/test/MockedDependenciesTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * 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(); - } - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolConfigBeanMXBean.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolConfigBeanMXBean.java deleted file mode 100644 index e2610d9773..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolConfigBeanMXBean.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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); - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolIfc.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolIfc.java deleted file mode 100644 index 3437eca29a..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolIfc.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolImpl.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolImpl.java deleted file mode 100644 index 459e458384..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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 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; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModule.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModule.java deleted file mode 100644 index a16c7c5092..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModule.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java deleted file mode 100644 index 1011951055..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/TestingScheduledThreadPoolModuleFactory.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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> ifc = ImmutableSet.of( - (Class) TestingScheduledThreadPoolServiceInterface.class, - TestingThreadPoolServiceInterface.class); - - @Override - public boolean isModuleImplementingServiceInterface( - final Class 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 getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, - final BundleContext bundleContext) { - return new HashSet<>(); - } - - @Override - public Set> getImplementedServiceIntefaces() { - return ifc; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/package-info.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/package-info.java deleted file mode 100644 index aac933cf29..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/package-info.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * 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; diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/runtimebeans/TestingScheduledRuntimeBean.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/runtimebeans/TestingScheduledRuntimeBean.java deleted file mode 100644 index c16e95d0dd..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/runtimebeans/TestingScheduledRuntimeBean.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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; - } - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/runtimebeans/TestingScheduledRuntimeMXBean.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/runtimebeans/TestingScheduledRuntimeMXBean.java deleted file mode 100644 index 31902dfebd..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/runtimebeans/TestingScheduledRuntimeMXBean.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/AbstractScheduledTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/AbstractScheduledTest.java deleted file mode 100644 index 2a9aa16088..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/AbstractScheduledTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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()); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/RuntimeBeanTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/RuntimeBeanTest.java deleted file mode 100644 index 12753002af..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/RuntimeBeanTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * 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:
- * {@link org.opendaylight.controller.config.manager.testingservices - * .scheduledthreadpool.TestingScheduledThreadPoolModuleFactory#NAME} - * ,
- * {@link org.opendaylight.controller.config.manager - * .testingservices.threadpool.TestingFixedThreadPoolModuleFactory#NAME} - *
- *
- * 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.newHashMap()); - // additional runtime bean - ObjectName ifc1runtimeON2 = ObjectNameUtil.createRuntimeBeanName(TestingScheduledThreadPoolModuleFactory.NAME, - SCHEDULED1, ImmutableMap.of("a", "b")); - - List 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 newInstances = Collections.emptyList(); - List reusedInstances = Lists.newArrayList(readableConfigBean); - List recreatedInstaces = Collections.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 newInstances = Collections.emptyList(); - List reusedInstances = Collections.emptyList(); - List 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); - } - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java deleted file mode 100644 index 9c6ba0700c..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/scheduledthreadpool/test/TwoInterfacesExportTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * 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(); - - } - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/ModifiableThreadPoolServiceInterface.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/ModifiableThreadPoolServiceInterface.java deleted file mode 100644 index b87f3cd077..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/ModifiableThreadPoolServiceInterface.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * 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 { -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingScheduledThreadPoolServiceInterface.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingScheduledThreadPoolServiceInterface.java deleted file mode 100644 index 5ddc1892e3..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingScheduledThreadPoolServiceInterface.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * 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 { -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingThreadPoolServiceInterface.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingThreadPoolServiceInterface.java deleted file mode 100644 index 66fdf301d3..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/seviceinterface/TestingThreadPoolServiceInterface.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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"; -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/AbstractTestingFixedThreadPoolModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/AbstractTestingFixedThreadPoolModuleFactory.java deleted file mode 100644 index a7024ca39e..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/AbstractTestingFixedThreadPoolModuleFactory.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * 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 { -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPool.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPool.java deleted file mode 100644 index 35413a1b1f..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPool.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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 ALL_EXECUTORS = Collections - .synchronizedList(Lists.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); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolConfigMXBean.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolConfigMXBean.java deleted file mode 100644 index 34f24c6802..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolConfigMXBean.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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); - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModule.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModule.java deleted file mode 100644 index 8ac0c32223..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModule.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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; - } - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java deleted file mode 100644 index 5975ce141e..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingFixedThreadPoolModuleFactory.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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> IFC = ImmutableSet.of( - (Class) 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 serviceInterface) { - return IFC.contains(serviceInterface); - } - - @Override - public Set getDefaultModules(final DependencyResolverFactory dependencyResolverFactory, - final BundleContext bundleContext) { - return new HashSet<>(); - } - - @Override - public Set> getImplementedServiceIntefaces() { - return IFC; - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingModifiableThreadPoolIfc.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingModifiableThreadPoolIfc.java deleted file mode 100644 index b51c6e3d84..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingModifiableThreadPoolIfc.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * 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); -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingThreadPoolConfigMXBean.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingThreadPoolConfigMXBean.java deleted file mode 100644 index b537ad2080..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingThreadPoolConfigMXBean.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * 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(); -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingThreadPoolIfc.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingThreadPoolIfc.java deleted file mode 100644 index 2e99aa09bd..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/TestingThreadPoolIfc.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/package-info.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/package-info.java deleted file mode 100644 index dc1bdf4b02..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/package-info.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * 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; diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/ShutdownTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/ShutdownTest.java deleted file mode 100644 index 9198c4b8a9..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/ShutdownTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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> allFactories = ImmutableMap.of( - testingFixedThreadPoolModuleFactory.getImplementationName(), - Maps.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()); - } -} diff --git a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/SimpleConfigurationTest.java b/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/SimpleConfigurationTest.java deleted file mode 100644 index f2dc012bc8..0000000000 --- a/opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/threadpool/test/SimpleConfigurationTest.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * 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: - *
    - *
  1. Creation of instance
  2. - *
  3. Destruction of instance
  4. - *
  5. Reconfiguration of live object
  6. - *
  7. Reconfiguration that triggers new object creation
  8. - *
  9. Replacement of running instance with different one with same name
  10. - *
- * 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 EMPTYO_NS = Collections.emptyList(); - private static final ObjectName PLATFORM_FIXED1ON = ObjectNameUtil - .createReadOnlyModuleON(TestingFixedThreadPoolModuleFactory.NAME, FIXED1); - private static final List 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> exception : e.getFailedValidations() - .entrySet()) { - for (Map.Entry 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> exception : e.getFailedValidations() - .entrySet()) { - for (Map.Entry 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> exception : e.getFailedValidations() - .entrySet()) { - for (Map.Entry 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 availableModuleFactoryQNames = configRegistryClient.getAvailableModuleFactoryQNames(); - String expected = "(namespace?revision=2012-12-12)name"; - - assertEquals(Sets.newHashSet(expected), availableModuleFactoryQNames); - } -} diff --git a/opendaylight/config/config-manager/src/test/resources/module-factories/module-factory-fail b/opendaylight/config/config-manager/src/test/resources/module-factories/module-factory-fail deleted file mode 100644 index fbd810841f..0000000000 --- a/opendaylight/config/config-manager/src/test/resources/module-factories/module-factory-fail +++ /dev/null @@ -1 +0,0 @@ -org.opendaylight.controller.config.manager.impl.osgi.ModuleFactoryBundleTrackerTest$NotExtendingTestingFactory \ No newline at end of file diff --git a/opendaylight/config/config-manager/src/test/resources/module-factories/module-factory-ok b/opendaylight/config/config-manager/src/test/resources/module-factories/module-factory-ok deleted file mode 100644 index 031b622bba..0000000000 --- a/opendaylight/config/config-manager/src/test/resources/module-factories/module-factory-ok +++ /dev/null @@ -1 +0,0 @@ -org.opendaylight.controller.config.manager.impl.osgi.ModuleFactoryBundleTrackerTest$TestingFactory \ No newline at end of file diff --git a/opendaylight/config/config-netty-config/pom.xml b/opendaylight/config/config-netty-config/pom.xml deleted file mode 100644 index 35c15caa64..0000000000 --- a/opendaylight/config/config-netty-config/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - 4.0.0 - - org.opendaylight.odlparent - bundle-parent - 3.1.0 - - - - org.opendaylight.controller - config-netty-config - 0.9.0-SNAPSHOT - Configuration files for sal-rest-connector - bundle - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - src/main/config/default-config.xml - xml - config - - - - - - - - - diff --git a/opendaylight/config/config-netty-config/src/main/config/default-config.xml b/opendaylight/config/config-netty-config/src/main/config/default-config.xml deleted file mode 100644 index dc1ace2a41..0000000000 --- a/opendaylight/config/config-netty-config/src/main/config/default-config.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - urn:opendaylight:params:xml:ns:yang:controller:netty?module=netty&revision=2013-11-19 - urn:opendaylight:params:xml:ns:yang:controller:netty:eventexecutor?module=netty-event-executor&revision=2013-11-12 - urn:opendaylight:params:xml:ns:yang:controller:netty:threadgroup?module=threadgroup&revision=2013-11-07 - urn:opendaylight:params:xml:ns:yang:controller:netty:timer?module=netty-timer&revision=2013-11-19 - - - - - - - netty:netty-threadgroup-fixed - global-boss-group - - - netty:netty-threadgroup-fixed - global-worker-group - - - netty:netty-hashed-wheel-timer - global-timer - - - netty:netty-global-event-executor - singleton - - - - - - netty:netty-threadgroup - - global-boss-group - /modules/module[type='netty-threadgroup-fixed'][name='global-boss-group'] - - - global-worker-group - /modules/module[type='netty-threadgroup-fixed'][name='global-worker-group'] - - - - netty:netty-event-executor - - global-event-executor - /modules/module[type='netty-global-event-executor'][name='singleton'] - - - - netty:netty-timer - - global-timer - /modules/module[type='netty-hashed-wheel-timer'][name='global-timer'] - - - - - - - diff --git a/opendaylight/config/config-parent/pom.xml b/opendaylight/config/config-parent/pom.xml deleted file mode 100644 index 4096ec932a..0000000000 --- a/opendaylight/config/config-parent/pom.xml +++ /dev/null @@ -1,217 +0,0 @@ - - - - - org.opendaylight.mdsal - binding-parent - 0.13.0-SNAPSHOT - - - - 4.0.0 - org.opendaylight.controller - config-parent - 0.9.0-SNAPSHOT - pom - - - 0.9.0-SNAPSHOT - 1.8.0-SNAPSHOT - 2.0.5 - ${project.build.directory}/generated-sources/config-binding - src/main/config/default-config.xml - - - - - - - org.opendaylight.controller - config-artifacts - ${config.version} - pom - import - - - org.opendaylight.controller - mdsal-artifacts - ${mdsal.version} - pom - import - - - org.opendaylight.yangtools - yangtools-artifacts - 2.0.5 - pom - import - - - org.opendaylight.mdsal - mdsal-artifacts - 2.5.0-SNAPSHOT - pom - import - - - - - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.controller - config-api - - - - - - - org.opendaylight.yangtools - yang-maven-plugin - 2.0.5 - - - org.opendaylight.controller - yang-jmx-generator-plugin - ${config.version} - - - - - config - - generate-sources - - - - - org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator - ${jmxGeneratorPath} - - urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang - - - - true - - - - - - maven-clean-plugin - - - - ${jmxGeneratorPath} - - ** - - - - ${salGeneratorPath} - - ** - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - add-yang-sources - generate-sources - - add-source - - - - ${jmxGeneratorPath} - ${salGeneratorPath} - - - - - - - - - org.apache.maven.plugins - maven-pmd-plugin - - - cpd - process-sources - - cpd-check - - - - ${jmxGeneratorPath} - ${salGeneratorPath} - - - - - - - - - - - attach-config-without-filtering - - - ${config.file} - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${config.file} - xml - config - - - - - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - - - - diff --git a/opendaylight/config/config-persister-api/pom.xml b/opendaylight/config/config-persister-api/pom.xml deleted file mode 100644 index 082dcbf4cc..0000000000 --- a/opendaylight/config/config-persister-api/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-subsystem - 0.9.0-SNAPSHOT - .. - - config-persister-api - bundle - ${project.artifactId} - - - - ${project.groupId} - config-util - - - com.google.guava - guava - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - org.apache.felix - maven-bundle-plugin - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - package - - - - - - diff --git a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigPusher.java b/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigPusher.java deleted file mode 100644 index a7d1a7d94b..0000000000 --- a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigPusher.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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 configs) throws InterruptedException; -} diff --git a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolder.java b/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolder.java deleted file mode 100644 index 9c4145ce1a..0000000000 --- a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolder.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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 getCapabilities(); -} diff --git a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolderImpl.java b/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolderImpl.java deleted file mode 100644 index 05af40a851..0000000000 --- a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolderImpl.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 caps; - private final String fileName; - - public ConfigSnapshotHolderImpl(final String configSnapshot, - final SortedSet capabilities, - final String fileName) { - this.snapshot = configSnapshot; - this.caps = capabilities; - this.fileName = fileName; - } - - @Override - public String getConfigSnapshot() { - return snapshot; - } - - @Override - public SortedSet getCapabilities() { - return caps; - } - - public String getFileName() { - return fileName; - } - - @Override - public String toString() { - return "snapshot='" + "ConfigSnapshotHolderImpl{" - + snapshot + '\'' + ", caps=" - + caps + ", fileName='" - + fileName + '\'' + '}'; - } -} diff --git a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/Persister.java b/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/Persister.java deleted file mode 100644 index 5509c99437..0000000000 --- a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/Persister.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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 loadLastConfigs() throws IOException; - - @Override - void close(); - -} diff --git a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/PropertiesProvider.java b/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/PropertiesProvider.java deleted file mode 100644 index 0bea336eaa..0000000000 --- a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/PropertiesProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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); -} diff --git a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/StorageAdapter.java b/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/StorageAdapter.java deleted file mode 100644 index 524e7b5633..0000000000 --- a/opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/StorageAdapter.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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); - - -} diff --git a/opendaylight/config/config-persister-api/src/test/java/org/opendaylight/controller/config/persist/test/PropertiesProviderTest.java b/opendaylight/config/config-persister-api/src/test/java/org/opendaylight/controller/config/persist/test/PropertiesProviderTest.java deleted file mode 100644 index e88968125c..0000000000 --- a/opendaylight/config/config-persister-api/src/test/java/org/opendaylight/controller/config/persist/test/PropertiesProviderTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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 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; - } -} diff --git a/opendaylight/config/config-persister-directory-xml-adapter/pom.xml b/opendaylight/config/config-persister-directory-xml-adapter/pom.xml deleted file mode 100644 index 38750342b0..0000000000 --- a/opendaylight/config/config-persister-directory-xml-adapter/pom.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-subsystem - 0.9.0-SNAPSHOT - .. - - config-persister-directory-xml-adapter - bundle - ${project.artifactId} - - - - - ${project.groupId} - config-persister-api - - - com.google.guava - guava - - - org.apache.commons - commons-lang3 - - - javax.validation - validation-api - - - - org.eclipse.persistence - org.eclipse.persistence.core - - - - org.apache.geronimo.specs - geronimo-jta_1.1_spec - - 1.1.1 - - - javax.mail - mail - - 1.4.4 - - - org.eclipse.persistence - org.eclipse.persistence.antlr - - - - org.eclipse.persistence - org.eclipse.persistence.moxy - - - org.opendaylight.controller - config-persister-file-xml-adapter - - - - - org.opendaylight.yangtools - mockito-configuration - - - - org.slf4j - slf4j-api - - - xmlunit - xmlunit - - - ${project.groupId} - config-persister-api - test-jar - test - - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - org.apache.felix - maven-bundle-plugin - - - ${project.groupId}.config-persister-impl - org.opendaylight.controller.config.persister.storage.adapter - - - - - - diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryPersister.java b/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryPersister.java deleted file mode 100644 index da4fbfbd23..0000000000 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryPersister.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * 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 extensionsFilter; - - /** - * Creates XmlDirectoryPersister that picks up all files in specified folder. - */ - public XmlDirectoryPersister(final File storage) { - this(storage, Optional.absent()); - } - - /** - * Creates XmlDirectoryPersister that picks up files only with specified file extension. - */ - public XmlDirectoryPersister(final File storage, final Set fileExtensions) { - this(storage, Optional.of(getFilter(fileExtensions))); - } - - private XmlDirectoryPersister(final File storage, final Optional 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 loadLastConfigs() throws IOException { - File[] filesArray = - extensionsFilter.isPresent() ? storage.listFiles(extensionsFilter.get()) : storage.listFiles(); - if (filesArray == null || filesArray.length == 0) { - return Collections.emptyList(); - } - List sortedFiles = new ArrayList<>(Arrays.asList(filesArray)); - Collections.sort(sortedFiles); - // combine all found files - LOG.debug("Reading files in following order: {}", sortedFiles); - - List result = new ArrayList<>(); - for (File file : sortedFiles) { - LOG.trace("Adding file '{}' to combined result", file); - Optional configSnapshotHolderOptional = fromXmlSnapshot(file); - // Ignore non valid snapshot - if (!configSnapshotHolderOptional.isPresent()) { - continue; - } - - result.add(configSnapshotHolderOptional.get()); - } - return result; - } - - private Optional 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 getCapabilities() { - return unmarshalled.getCapabilities(); - } - - @Override - public String toString() { - return unmarshalled.toString(); - } - }; - } - - private static FilenameFilter getFilter(final Set 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 diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryStorageAdapter.java b/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryStorageAdapter.java deleted file mode 100644 index 576a24a41f..0000000000 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/directory/xml/XmlDirectoryStorageAdapter.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 splitExtensions(final String fileExtensions) { - return Sets.newHashSet(Splitter.on(EXTENSIONS_SEPARATOR).trimResults().omitEmptyStrings() - .split(fileExtensions)); - } -} diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/directory/xml/DirectoryStorageAdapterTest.java b/opendaylight/config/config-persister-directory-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/directory/xml/DirectoryStorageAdapterTest.java deleted file mode 100644 index 1142e060aa..0000000000 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/directory/xml/DirectoryStorageAdapterTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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 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.absent()); - } - - @Test - public void testEmptyDirectory() throws Exception { - File folder = new File("target/emptyFolder"); - folder.mkdir(); - - tested = instantiatePersisterFromAdapter(folder); - assertEquals(Collections.emptyList(), tested.loadLastConfigs()); - - try { - tested.persistConfig(new ConfigSnapshotHolder() { - @Override - public String getConfigSnapshot() { - throw new RuntimeException(); - } - - @Override - public SortedSet 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 results = tested.loadLastConfigs(); - assertEquals(1, results.size()); - ConfigSnapshotHolder result = results.get(0); - assertResult(result, "1", "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 results = tested.loadLastConfigs(); - assertEquals(2, results.size()); - - assertResult(results.get(0), "1", "cap1-a", "cap2-a", "capa a-a"); - assertResult(results.get(1), "2", "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 results = tested.loadLastConfigs(); - assertEquals(1, results.size()); - - assertResult(results.get(0), "1", "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 results = tested.loadLastConfigs(); - assertEquals(1, results.size()); - - assertResult(results.get(0), "1", "cap1-a", "cap2-a", "capa a-a"); - } - -} diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/oneFile/controller.config.xml b/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/oneFile/controller.config.xml deleted file mode 100644 index aa8b14c9c4..0000000000 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/oneFile/controller.config.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - cap1&rev - cap2 - capa a - - - 1 - - \ No newline at end of file diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles/controller.config1.xml b/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles/controller.config1.xml deleted file mode 100644 index 28f112e4fa..0000000000 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles/controller.config1.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - cap1-a - cap2-a - capa a-a - - - 1 - - \ No newline at end of file diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles/controller.config2.xml2 b/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles/controller.config2.xml2 deleted file mode 100644 index 8fed29d182..0000000000 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles/controller.config2.xml2 +++ /dev/null @@ -1,10 +0,0 @@ - - - cap1-b - cap2-b - capa a-b - - - 2 - - \ No newline at end of file diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles_corrupt/controller.config1.xml b/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles_corrupt/controller.config1.xml deleted file mode 100644 index 28f112e4fa..0000000000 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles_corrupt/controller.config1.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - cap1-a - cap2-a - capa a-a - - - 1 - - \ No newline at end of file diff --git a/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles_corrupt/controller.config2.xml b/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles_corrupt/controller.config2.xml deleted file mode 100644 index ed781d5ee2..0000000000 --- a/opendaylight/config/config-persister-directory-xml-adapter/src/test/resources/twoFiles_corrupt/controller.config2.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - cap1-b - cap2-b - capa a-b - - - 2 - - \ No newline at end of file diff --git a/opendaylight/config/config-persister-feature-adapter/pom.xml b/opendaylight/config/config-persister-feature-adapter/pom.xml deleted file mode 100644 index c178ac66e9..0000000000 --- a/opendaylight/config/config-persister-feature-adapter/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - 4.0.0 - - - org.opendaylight.controller - config-subsystem - 0.9.0-SNAPSHOT - .. - - - config-persister-feature-adapter - bundle - - - - com.google.guava - guava - - - org.osgi - org.osgi.core - provided - - - org.apache.karaf.features - org.apache.karaf.features.core - ${karaf.version} - provided - - - org.opendaylight.controller - config-persister-impl - - - org.opendaylight.controller - config-persister-api - - - org.opendaylight.controller - config-persister-directory-xml-adapter - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.version} - org.opendaylight.controller.configpusherfeature.ConfigPusherFeatureActivator - - org.apache.felix.utils.version, - org.opendaylight.controller.configpusherfeature.internal - - - - - - - - diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/ConfigPusherFeatureActivator.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/ConfigPusherFeatureActivator.java deleted file mode 100644 index 99334da488..0000000000 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/ConfigPusherFeatureActivator.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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 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; - } -} diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/AbstractFeatureWrapper.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/AbstractFeatureWrapper.java deleted file mode 100644 index 3c8622a168..0000000000 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/AbstractFeatureWrapper.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * 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 getFeatureConfigSnapshotHolders() throws Exception { - final Set snapShotHolders = new LinkedHashSet<>(); - for (final ConfigFileInfo c : getConfigurationFiles()) { - // Skip non config snapshot XML files - if (isConfigSnapshot(c.getFinalname())) { - final Optional featureConfigSnapshotHolder = - getFeatureConfigSnapshotHolder(c); - if (featureConfigSnapshotHolder.isPresent()) { - snapShotHolders.add(featureConfigSnapshotHolder.get()); - } - } - } - return snapShotHolders; - } - - protected Optional - 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 getDependencies() { - return feature.getDependencies(); - } - - @Override - public List getBundles() { - return feature.getBundles(); - } - - @Override - public List getConfigurations() { - return feature.getConfigurations(); - } - - @Override - public List getConfigurationFiles() { - return feature.getConfigurationFiles(); - } - - @Override - public List getConditional() { - return feature.getConditional(); - } - - @Override - public int getStartLevel() { - return feature.getStartLevel(); - } - - @Override - public List getCapabilities() { - return feature.getCapabilities(); - } - - @Override - public List getLibraries() { - return feature.getLibraries(); - } - - @Override - public String getNamespace() { - return feature.getNamespace(); - } - - @Override - public String getRepositoryUrl() { - return feature.getRepositoryUrl(); - } - - @Override - public List getRequirements() { - return feature.getRequirements(); - } - - @Override - public List getResourceRepositories() { - return feature.getResourceRepositories(); - } - - @Override - public Scoping getScoping() { - return feature.getScoping(); - } - - @Override - public boolean isHidden() { - return feature.isHidden(); - } - -} diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ChildAwareFeatureWrapper.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ChildAwareFeatureWrapper.java deleted file mode 100644 index 2a23fd2537..0000000000 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ChildAwareFeatureWrapper.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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 getChildFeatures() throws Exception { - List dependencies = feature.getDependencies(); - Set 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 getFeatureConfigSnapshotHolders() throws Exception { - Set snapShotHolders = new LinkedHashSet<>(); - for (ChildAwareFeatureWrapper c : getChildFeatures()) { - for (FeatureConfigSnapshotHolder h : c.getFeatureConfigSnapshotHolders()) { - final Optional 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; - } -} diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigFeaturesListener.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigFeaturesListener.java deleted file mode 100644 index d5d590aadc..0000000000 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigFeaturesListener.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 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; - } - } -} diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPusherCustomizer.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPusherCustomizer.java deleted file mode 100644 index e665309c92..0000000000 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPusherCustomizer.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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, AutoCloseable { - private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherCustomizer.class); - private ConfigFeaturesListener configFeaturesListener = null; - private FeatureServiceCustomizer featureServiceCustomizer = null; - private ServiceTracker fsst = null; - - @Override - public ConfigPusher addingService(final ServiceReference 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 configPusherServiceReference, - final ConfigPusher configPusher) { - // we don't care if the properties change - } - - @Override - public void removedService(final ServiceReference 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 diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPushingRunnable.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPushingRunnable.java deleted file mode 100644 index 010a273154..0000000000 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/ConfigPushingRunnable.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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 queue; - private FeatureConfigPusher configPusher; - - public ConfigPushingRunnable(final ConfigPusher configPusher, final FeaturesService featuresService, - final BlockingQueue featureEvents) { - queue = featureEvents; - this.configPusher = new FeatureConfigPusher(configPusher, featuresService); - } - - @Override - @SuppressWarnings("IllegalCatch") - public void run() { - List 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 toInstall) throws Exception { - if (event.getType() == EventType.FeatureInstalled) { - toInstall.add(event.getFeature()); - LinkedHashMultimap result = configPusher.pushConfigs(toInstall); - toInstall.removeAll(result.keySet()); - } else if (event.getType() == EventType.FeatureUninstalled) { - toInstall.remove(event.getFeature()); - } - } - - protected void logPushResult(final LinkedHashMultimap results) { - for (Feature f : results.keySet()) { - LOG.info("Pushed configs for feature {} {}", f, results.get(f)); - } - } -} diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigPusher.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigPusher.java deleted file mode 100644 index 2737954884..0000000000 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigPusher.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * 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 pushedConfigs = new LinkedHashSet<>(); - - /* - * LinkedHashMultimap to track which configs we pushed for each Feature installation - * For future use - */ - private final LinkedHashMultimap 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 pushConfigs( - final List features) throws Exception { - LinkedHashMultimap pushedFeatures = LinkedHashMultimap.create(); - for (Feature feature : features) { - Set configSnapShots = pushConfig(feature); - if (!configSnapShots.isEmpty()) { - pushedFeatures.putAll(feature, configSnapShots); - } - } - return pushedFeatures; - } - - private Set 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 configs = wrappedFeature.getFeatureConfigSnapshotHolders(); - if (!configs.isEmpty()) { - configs = pushConfig(configs, feature); - feature2configs.putAll(feature, configs); - } - return configs; - } - - private Set pushConfig(final Set configs, - final Feature feature) throws InterruptedException { - Set configsToPush = new LinkedHashSet<>(configs); - configsToPush.removeAll(pushedConfigs); - if (!configsToPush.isEmpty()) { - - // Ignore features that are present in persisted current config - final Optional 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 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; - } -} diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigSnapshotHolder.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigSnapshotHolder.java deleted file mode 100644 index f99e763177..0000000000 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureConfigSnapshotHolder.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * 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 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 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 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); - } -} diff --git a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureServiceCustomizer.java b/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureServiceCustomizer.java deleted file mode 100644 index 9e9c26cbf3..0000000000 --- a/opendaylight/config/config-persister-feature-adapter/src/main/java/org/opendaylight/controller/configpusherfeature/internal/FeatureServiceCustomizer.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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, - 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 reference) { - BundleContext bc = reference.getBundle().getBundleContext(); - final FeaturesService featureService = bc.getService(reference); - final Optional currentPersister = XmlFileStorageAdapter.getInstance(); - - if (XmlFileStorageAdapter.getInstance().isPresent()) { - final Set 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 reference, final FeaturesService service) { - // we don't care if the properties change - } - - @Override - public void removedService(final ServiceReference reference, final FeaturesService service) { - close(); - } - - @Override - public void close() { - if (registration != null) { - registration.unregister(); - registration = null; - } - } -} diff --git a/opendaylight/config/config-persister-file-xml-adapter/pom.xml b/opendaylight/config/config-persister-file-xml-adapter/pom.xml deleted file mode 100644 index 405aa4dafb..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-subsystem - 0.9.0-SNAPSHOT - .. - - config-persister-file-xml-adapter - bundle - ${project.artifactId} - - - - - ${project.groupId} - config-persister-api - - - com.google.guava - guava - - - org.apache.commons - commons-lang3 - - - javax.validation - validation-api - - - org.eclipse.persistence - org.eclipse.persistence.core - - - - org.eclipse.persistence - org.eclipse.persistence.moxy - - - - - org.opendaylight.yangtools - mockito-configuration - - - org.slf4j - slf4j-api - - - xmlunit - xmlunit - - - ${project.groupId} - config-persister-api - test-jar - test - - - - - - - org.apache.felix - maven-bundle-plugin - - - ${project.groupId}.config-persister-impl - org.opendaylight.controller.config.persister.storage.adapter - - - - - - - diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/FeatureListProvider.java b/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/FeatureListProvider.java deleted file mode 100644 index 21c353a489..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/FeatureListProvider.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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 listFeatures(); -} diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/XmlFileStorageAdapter.java b/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/XmlFileStorageAdapter.java deleted file mode 100644 index 7ad0734159..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/XmlFileStorageAdapter.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * 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 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 getInstance() { - return Optional.fromNullable(instance); - } - - public Set getPersistedFeatures() { - return lastCfgSnapshotCache == null ? Collections.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 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 loadLastConfigs() throws IOException { - Preconditions.checkNotNull(storage, "Storage file is null"); - - if (!storage.exists()) { - return Collections.emptyList(); - } - - Optional 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 getCapabilities() { - return configSnapshot.getCapabilities(); - } - - @Override - public String toString() { - return configSnapshot.toString(); - } - }; - } - - @Override - public void close() { - - } - - @Override - public String toString() { - return "XmlFileStorageAdapter [storage=" + storage + "]"; - } - -} diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/Config.java b/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/Config.java deleted file mode 100644 index e043e45feb..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/Config.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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 snapshots; - - Config(final List snapshots) { - this.snapshots = snapshots; - } - - public Config() { - this.snapshots = Lists.newArrayList(); - } - - @XmlElement(name = "snapshot") - @XmlElementWrapper(name = "snapshots") - public List getSnapshots() { - return snapshots; - } - - public void setSnapshots(final List 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 getLastSnapshot() { - ConfigSnapshot last = Iterables.getLast(snapshots, null); - return last == null ? Optional.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(); - } -} diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigSnapshot.java b/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigSnapshot.java deleted file mode 100644 index 05372dd105..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigSnapshot.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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 capabilities = new TreeSet<>(); - private Set features = new HashSet<>(); - - ConfigSnapshot(final String configXml, final SortedSet capabilities) { - this.configXml = configXml; - this.capabilities = capabilities; - } - - ConfigSnapshot(final String configXml, final SortedSet capabilities, final Set 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 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 getCapabilities() { - return capabilities; - } - - public void setCapabilities(final SortedSet capabilities) { - this.capabilities = capabilities; - } - - @XmlElement(name = "feature") - @XmlElementWrapper(name = "features") - @XmlJavaTypeAdapter(value=StringTrimAdapter.class) - public Set getFeatures() { - return features; - } - - public void setFeatures(final Set features) { - this.features = features; - } - - @Override - public String toString() { - return "ConfigSnapshot{" - + "configSnapshot='" + configXml + '\'' - + ", capabilities=" + capabilities - + ", features=" + features + - '}'; - } -} - diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/PersistException.java b/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/PersistException.java deleted file mode 100644 index 0c7d22c1dd..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/PersistException.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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); - } -} diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/SnapshotHandler.java b/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/SnapshotHandler.java deleted file mode 100644 index e99694751b..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/SnapshotHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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 { - - private static final String START_TAG = ""; - private static final String END_TAG = ""; - - 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); - } - } - -} diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/StringTrimAdapter.java b/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/StringTrimAdapter.java deleted file mode 100644 index 0308a726ab..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/StringTrimAdapter.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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 { - @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(); - } -} diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/FileStorageAdapterTest.java b/opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/FileStorageAdapterTest.java deleted file mode 100644 index 0b9e1b3a09..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/FileStorageAdapterTest.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - * 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 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 getCapabilities() { - return createCaps(); - } - }; - storage.persistConfig(holder); - - storage.persistConfig(holder); - - assertEquals(29, com.google.common.io.Files.readLines(file, StandardCharsets.UTF_8).size()); - List lastConf = storage.loadLastConfigs(); - assertEquals(1, lastConf.size()); - ConfigSnapshotHolder configSnapshotHolder = lastConf.get(0); - assertXMLEqual("2", configSnapshotHolder.getConfigSnapshot()); - assertEquals(createCaps(), configSnapshotHolder.getCapabilities()); - - storage = new XmlFileStorageAdapter(); - storage.setFileStorage(file); - storage.setNumberOfBackups(Integer.MAX_VALUE); - - List last = storage.loadLastConfigs(); - assertEquals(createCaps(), last.get(0).getCapabilities()); - } - - private SortedSet createCaps() { - SortedSet 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 getCapabilities() { - return createCaps(); - } - }; - storage.persistConfig(holder); - - storage.persistConfig(holder); - - assertEquals(29, com.google.common.io.Files.readLines(file, StandardCharsets.UTF_8).size()); - - List lastConf = storage.loadLastConfigs(); - assertEquals(1, lastConf.size()); - ConfigSnapshotHolder configSnapshotHolder = lastConf.get(0); - assertXMLEqual("2", 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 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 lastConf = storage.loadLastConfigs(); - assertEquals(1, lastConf.size()); - ConfigSnapshotHolder configSnapshotHolder = lastConf.get(0); - assertXMLEqual("1", 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("\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " cap12\n" + - " \n" + - " \n" + - " 1\n" + - " \n" + - " \n" + - " \n" + - "", file, StandardCharsets.UTF_8); - - List lastConf = storage.loadLastConfigs(); - assertEquals(1, lastConf.size()); - ConfigSnapshotHolder configSnapshotHolder = lastConf.get(0); - assertXMLEqual("1", 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 getCapabilities() { - return createCaps(); - } - }; - storage.persistConfig(holder); - - storage.persistConfig(holder); - storage.persistConfig(holder); - - List readLines = com.google.common.io.Files.readLines(file, StandardCharsets.UTF_8); - assertEquals(29, readLines.size()); - - List lastConf = storage.loadLastConfigs(); - assertEquals(1, lastConf.size()); - ConfigSnapshotHolder configSnapshotHolder = lastConf.get(0); - assertXMLEqual("3", 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 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 getCapabilities() { - return new TreeSet<>(); - } - }); - } - } - - static String createConfig() { - return "" + i++ + ""; - } - - 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); - } - } -} diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigTest.java b/opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigTest.java deleted file mode 100644 index 49b5319340..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/src/test/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigTest.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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 diff --git a/opendaylight/config/config-persister-file-xml-adapter/src/test/resources/illegalSnapshot.xml b/opendaylight/config/config-persister-file-xml-adapter/src/test/resources/illegalSnapshot.xml deleted file mode 100644 index f3fd13a36d..0000000000 --- a/opendaylight/config/config-persister-file-xml-adapter/src/test/resources/illegalSnapshot.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - prefix:clustering-service-provider - - clustering-service-provider - - - binding:binding-rpc-registry - binding-rpc-broker - - - - - - - - - - - prefix:clustering-service-change-registry - - openflow-role-change-registry - /modules/module[type='clustering-service-provider'][name='clustering-service-provider'] - - - - - - urn:opendaylight:params:xml:ns:yang:controller:config:clustering-service-provider?module=clustering-service-provider&revision=2014-11-19 - - - - \ No newline at end of file diff --git a/opendaylight/config/config-persister-impl/pom.xml b/opendaylight/config/config-persister-impl/pom.xml deleted file mode 100644 index 70470e948a..0000000000 --- a/opendaylight/config/config-persister-impl/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - - - 4.0.0 - - - config-subsystem - org.opendaylight.controller - 0.9.0-SNAPSHOT - - config-persister-impl - bundle - ${project.artifactId} - - - - com.google.guava - guava - - - - org.opendaylight.controller - config-persister-api - - - org.osgi - org.osgi.core - - - org.slf4j - slf4j-api - - - org.opendaylight.controller - config-manager-facade-xml - - - - org.opendaylight.controller - config-persister-directory-xml-adapter - test - - - org.opendaylight.controller - config-persister-file-xml-adapter - test - - - org.opendaylight.yangtools - mockito-configuration - test - - - - - - - org.apache.felix - maven-bundle-plugin - - - org.opendaylight.controller.config.persist.impl.osgi.ConfigPersisterActivator - org.opendaylight.controller.config.persister.storage.adapter - - - - - - diff --git a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/CapabilityStrippingConfigSnapshotHolder.java b/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/CapabilityStrippingConfigSnapshotHolder.java deleted file mode 100644 index 3d916f60f4..0000000000 --- a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/CapabilityStrippingConfigSnapshotHolder.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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 capabilities) { - final XmlElement configElement = XmlElement.fromDomElement(snapshot); - configSnapshot = XmlUtil.toString(configElement.getDomElement()); - stripCapabilitiesResult = stripCapabilities(configElement, capabilities); - } - - private static class StripCapabilitiesResult { - private final SortedSet requiredCapabilities; - private final SortedSet obsoleteCapabilities; - - private StripCapabilitiesResult(final SortedSet requiredCapabilities, final SortedSet obsoleteCapabilities) { - this.requiredCapabilities = Collections.unmodifiableSortedSet(requiredCapabilities); - this.obsoleteCapabilities = Collections.unmodifiableSortedSet(obsoleteCapabilities); - } - } - - - @VisibleForTesting - static StripCapabilitiesResult stripCapabilities(final XmlElement configElement, final Set allCapabilitiesFromHello) { - // collect all namespaces - Set foundNamespacesInXML = getNamespaces(configElement); - LOG.trace("All capabilities {}\nFound namespaces in XML {}", allCapabilitiesFromHello, foundNamespacesInXML); - // required are referenced both in xml and hello - SortedSet requiredCapabilities = new TreeSet<>(); - // can be removed - SortedSet 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 getNamespaces(final XmlElement element){ - Set result = new HashSet<>(); - for (Entry 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 getCapabilities() { - return stripCapabilitiesResult.requiredCapabilities; - } - - @VisibleForTesting - Set getObsoleteCapabilities(){ - return stripCapabilitiesResult.obsoleteCapabilities; - } - - @Override - public String getConfigSnapshot() { - return configSnapshot; - } -} diff --git a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/ConfigPersisterNotificationHandler.java b/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/ConfigPersisterNotificationHandler.java deleted file mode 100644 index 9d6ef5e1ab..0000000000 --- a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/ConfigPersisterNotificationHandler.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * 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 currentCapabilities = facade.getCurrentCapabilities(); - final Element configSnapshot = facade.createFacade("config-persister").getConfiguration(XmlUtil.newDocument(), Datastore.running, Optional.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); - } - } -} diff --git a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/ConfigPusherImpl.java b/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/ConfigPusherImpl.java deleted file mode 100644 index 08c3330a27..0000000000 --- a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/ConfigPusherImpl.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * 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> 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 autoCloseables, final MBeanServerConnection platformMBeanServer, - final Persister persisterAggregator, final boolean propagateExceptions) throws InterruptedException { - while(processSingle(autoCloseables, platformMBeanServer, persisterAggregator, propagateExceptions)) { - } - } - - boolean processSingle(final List autoCloseables, final MBeanServerConnection platformMBeanServer, - final Persister persisterAggregator, final boolean propagateExceptions) throws InterruptedException { - final List 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 configs) throws InterruptedException { - LOG.debug("Requested to push configs {}", configs); - this.queue.put(configs); - } - - private LinkedHashMap internalPushConfigs(final List configs) - throws DocumentedException { - LOG.debug("Last config snapshots to be pushed to netconf: {}", configs); - LinkedHashMap 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 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 expectedCapabilities, final String idForReporting) { - Stopwatch stopwatch = Stopwatch.createStarted(); - ConfigPusherException lastException; - do { - try { - final Set currentCaps = facade.getCurrentCapabilities(); - final Set 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 computeNotFoundCapabilities(final Set expectedCapabilities, final Set currentCapabilities) { - Collection actual = transformCapabilities(currentCapabilities); - Set allNotFound = new HashSet<>(expectedCapabilities); - allNotFound.removeAll(actual); - return allNotFound; - } - - static Set transformCapabilities(final Set 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 missingCaps; - - NotEnoughCapabilitiesException(final String message, final Set missingCaps) { - super(message); - this.missingCaps = missingCaps; - } - - public Set 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); - } - -} diff --git a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/NoOpStorageAdapter.java b/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/NoOpStorageAdapter.java deleted file mode 100644 index c8f48d7fc3..0000000000 --- a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/NoOpStorageAdapter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 loadLastConfigs() throws IOException { - LOG.debug("loadLastConfig called"); - return Collections.emptyList(); - } - - @Override - public void close() { - LOG.debug("close called"); - } -} diff --git a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/PersisterAggregator.java b/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/PersisterAggregator.java deleted file mode 100644 index 8926b4ce61..0000000000 --- a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/PersisterAggregator.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * 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:
- 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
-
- 
- * 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 persisterWithConfigurations; - - public PersisterAggregator(final List 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 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 loadLastConfigs() { - // iterate in reverse order - ListIterator li = persisterWithConfigurations.listIterator(persisterWithConfigurations.size()); - while(li.hasPrevious()) { - PersisterWithConfiguration persisterWithConfiguration = li.previous(); - List 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 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 + - '}'; - } -} diff --git a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/PropertiesProviderAdapterImpl.java b/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/PropertiesProviderAdapterImpl.java deleted file mode 100644 index acef56ff1a..0000000000 --- a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/PropertiesProviderAdapterImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/osgi/ConfigPersisterActivator.java b/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/osgi/ConfigPersisterActivator.java deleted file mode 100644 index c99fa767e2..0000000000 --- a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/osgi/ConfigPersisterActivator.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * 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 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 configs = persisterAggregator.loadLastConfigs(); - final long conflictingVersionTimeoutMillis = getConflictingVersionTimeoutMillis(propertiesProvider); - LOG.debug("Following configs will be pushed: {}", configs); - - ServiceTrackerCustomizer schemaServiceTrackerCustomizer = new ServiceTrackerCustomizer() { - - @Override - public ConfigSubsystemFacadeFactory addingService(final ServiceReference 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 reference, final ConfigSubsystemFacadeFactory service) { - LOG.warn("Config manager facade was modified unexpectedly"); - } - - @Override - public void removedService(final ServiceReference reference, final ConfigSubsystemFacadeFactory service) { - LOG.warn("Config manager facade was removed unexpectedly"); - } - }; - - ServiceTracker 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 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(); - } -} - diff --git a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/osgi/PropertiesProviderBaseImpl.java b/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/osgi/PropertiesProviderBaseImpl.java deleted file mode 100644 index 5a5f7e77b5..0000000000 --- a/opendaylight/config/config-persister-impl/src/main/java/org/opendaylight/controller/config/persist/impl/osgi/PropertiesProviderBaseImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/CapabilityStrippingConfigSnapshotHolderTest.java b/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/CapabilityStrippingConfigSnapshotHolderTest.java deleted file mode 100644 index 2a20939ba7..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/CapabilityStrippingConfigSnapshotHolderTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 allCapabilities = readLines("/capabilities-all.txt"); - Set 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 obsoleteCapabilities = Sets.difference(allCapabilities, expectedCapabilities); - - assertEquals(obsoleteCapabilities, tested.getObsoleteCapabilities()); - } - - private Set 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); - } - -} diff --git a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/ConfigPersisterNotificationHandlerTest.java b/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/ConfigPersisterNotificationHandlerTest.java deleted file mode 100644 index a89520a7a8..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/ConfigPersisterNotificationHandlerTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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)); - } -} diff --git a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/ConfigPersisterNotificationListenerTest.java b/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/ConfigPersisterNotificationListenerTest.java deleted file mode 100644 index 1d5d0132d9..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/ConfigPersisterNotificationListenerTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * 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("")).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)); - } -} diff --git a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/ConfigPusherImplTest.java b/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/ConfigPusherImplTest.java deleted file mode 100644 index 28f6ce83c8..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/ConfigPusherImplTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * 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("").when(mockedConfigSnapshot).getConfigSnapshot(); - doReturn(Collections.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.newArrayList(), ManagementFactory.getPlatformMBeanServer(), - mockedAggregator, true); - } catch(final IllegalStateException e) { - Throwable cause = Throwables.getRootCause(e); - assertTrue(cause instanceof ConfigPusherImpl.NotEnoughCapabilitiesException); - final Set 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.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.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.newArrayList(), mBeanServer, mockedAggregator, true); - - verify(facade, times(3)).executeConfigExecution(cfgExec); - verify(facade, times(3)).commitSilentTransaction(); - } - -} diff --git a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/DummyAdapter.java b/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/DummyAdapter.java deleted file mode 100644 index 9984b143db..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/DummyAdapter.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 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() { - } - -} diff --git a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/PersisterAggregatorTest.java b/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/PersisterAggregatorTest.java deleted file mode 100644 index f17626783d..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/java/org/opendaylight/controller/config/persist/impl/PersisterAggregatorTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * 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 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 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 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 configSnapshotHolderOptional = persisterAggregator.loadLastConfigs(); - assertEquals(1, configSnapshotHolderOptional.size()); - assertEquals(used, configSnapshotHolderOptional.get(0)); - } - } -} diff --git a/opendaylight/config/config-persister-impl/src/test/resources/capabilities-all.txt b/opendaylight/config/config-persister-impl/src/test/resources/capabilities-all.txt deleted file mode 100644 index b40741103d..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/resources/capabilities-all.txt +++ /dev/null @@ -1,19 +0,0 @@ -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 diff --git a/opendaylight/config/config-persister-impl/src/test/resources/capabilities-stripped.txt b/opendaylight/config/config-persister-impl/src/test/resources/capabilities-stripped.txt deleted file mode 100644 index 4a0b7ffffd..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/resources/capabilities-stripped.txt +++ /dev/null @@ -1,5 +0,0 @@ -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 diff --git a/opendaylight/config/config-persister-impl/src/test/resources/snapshot.xml b/opendaylight/config/config-persister-impl/src/test/resources/snapshot.xml deleted file mode 100644 index a6a57d704a..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/resources/snapshot.xml +++ /dev/null @@ -1,103 +0,0 @@ - - - - prefix:schema-service-singleton - yang-schema-service - - - prefix:hash-map-data-store - hash-map-data-store - - - prefix:dom-broker-impl - dom-broker - - dom:dom-data-store - ref_hash-map-data-store - - - - prefix:binding-broker-impl - binding-broker-impl - - binding:binding-notification-service - ref_binding-notification-broker - - - binding:binding-data-broker - ref_binding-data-broker - - - - prefix:runtime-generated-mapping - runtime-mapping-singleton - - - prefix:binding-notification-broker - binding-notification-broker - - - prefix:binding-data-broker - binding-data-broker - - dom:dom-broker-osgi-registry - ref_dom-broker - - - binding:binding-dom-mapping-service - ref_runtime-mapping-singleton - - - - - - dom:schema-service - - ref_yang-schema-service - /config/modules/module[name='schema-service-singleton']/instance[name='yang-schema-service'] - - - - binding:binding-notification-service - - ref_binding-notification-broker - /config/modules/module[name='binding-notification-broker']/instance[name='binding-notification-broker'] - - - - dom:dom-data-store - - ref_hash-map-data-store - /config/modules/module[name='hash-map-data-store']/instance[name='hash-map-data-store'] - - - - binding:binding-broker-osgi-registry - - ref_binding-broker-impl - /config/modules/module[name='binding-broker-impl']/instance[name='binding-broker-impl'] - - - - binding-impl:binding-dom-mapping-service - - ref_runtime-mapping-singleton - /config/modules/module[name='runtime-generated-mapping']/instance[name='runtime-mapping-singleton'] - - - - dom:dom-broker-osgi-registry - - ref_dom-broker - /config/modules/module[name='dom-broker-impl']/instance[name='dom-broker'] - - - - binding:binding-data-broker - - ref_binding-data-broker - /config/modules/module[name='binding-data-broker']/instance[name='binding-data-broker'] - - - - diff --git a/opendaylight/config/config-persister-impl/src/test/resources/test1.properties b/opendaylight/config/config-persister-impl/src/test/resources/test1.properties deleted file mode 100644 index 0270c1a930..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/resources/test1.properties +++ /dev/null @@ -1,3 +0,0 @@ -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/ diff --git a/opendaylight/config/config-persister-impl/src/test/resources/test2.properties b/opendaylight/config/config-persister-impl/src/test/resources/test2.properties deleted file mode 100644 index 729c67d6c5..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/resources/test2.properties +++ /dev/null @@ -1,9 +0,0 @@ -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 diff --git a/opendaylight/config/config-persister-impl/src/test/resources/test3.properties b/opendaylight/config/config-persister-impl/src/test/resources/test3.properties deleted file mode 100644 index 90ba77273b..0000000000 --- a/opendaylight/config/config-persister-impl/src/test/resources/test3.properties +++ /dev/null @@ -1,4 +0,0 @@ -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 diff --git a/opendaylight/config/config-plugin-parent/pom.xml b/opendaylight/config/config-plugin-parent/pom.xml deleted file mode 100644 index e06f975183..0000000000 --- a/opendaylight/config/config-plugin-parent/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.controller - config-subsystem - 0.9.0-SNAPSHOT - ../ - - config-plugin-parent - pom - ${project.artifactId} - - - ${project.build.directory}/generated-sources/config-binding - - - - - - - org.opendaylight.yangtools - yang-maven-plugin - - - org.opendaylight.controller - yang-jmx-generator-plugin - 0.9.0-SNAPSHOT - - - - - config - - generate-sources - - - - - org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator - ${jmxGeneratorPath} - - urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang - - - - true - - - - - - - - diff --git a/opendaylight/config/config-util/.gitignore b/opendaylight/config/config-util/.gitignore deleted file mode 100644 index fc1d35eb24..0000000000 --- a/opendaylight/config/config-util/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -target -.classpath -.settings diff --git a/opendaylight/config/config-util/pom.xml b/opendaylight/config/config-util/pom.xml deleted file mode 100644 index d1b48bf638..0000000000 --- a/opendaylight/config/config-util/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-subsystem - 0.9.0-SNAPSHOT - .. - - config-util - bundle - ${project.artifactId} - - - - - ${project.groupId} - config-api - - - com.google.guava - guava - - - org.opendaylight.yangtools - yang-data-api - - - org.opendaylight.yangtools - yang-model-api - - - - org.opendaylight.yangtools - mockito-configuration - - - xmlunit - xmlunit - test - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - package - - - - - org.apache.felix - maven-bundle-plugin - - - org.opendaylight.controller.config.util.* - - - - - - - diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/AttributeEntry.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/AttributeEntry.java deleted file mode 100644 index 47c41290cc..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/AttributeEntry.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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; - } - -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/BeanReader.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/BeanReader.java deleted file mode 100644 index 09bb7fc24f..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/BeanReader.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * 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); -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/CloseableUtil.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/CloseableUtil.java deleted file mode 100644 index 5803da0ab2..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/CloseableUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 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; - } - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryClient.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryClient.java deleted file mode 100644 index d384ae55c0..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryClient.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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); - -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryJMXClient.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryJMXClient.java deleted file mode 100644 index 395e0837c2..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryJMXClient.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * 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 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 newMBeanProxy(final ObjectName on, final Class 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 newMXBeanProxy(final ObjectName on, final Class 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 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 getAvailableModuleNames() { - return configRegistryMXBeanProxy.getAvailableModuleNames(); - } - - @Override - public boolean isHealthy() { - return configRegistryMXBeanProxy.isHealthy(); - } - - @Override - public Set lookupConfigBeans() { - return configRegistryMXBeanProxy.lookupConfigBeans(); - } - - @Override - public Set lookupConfigBeans(final String moduleName) { - return configRegistryMXBeanProxy.lookupConfigBeans(moduleName); - } - - @Override - public Set 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 lookupRuntimeBeans() { - return configRegistryMXBeanProxy.lookupRuntimeBeans(); - } - - @Override - public Set 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> getServiceMapping() { - return configRegistryMXBeanProxy.getServiceMapping(); - } - - @Override - public Map lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) { - return configRegistryMXBeanProxy.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName); - } - - @Override - public Set 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 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); - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionClient.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionClient.java deleted file mode 100644 index c7c072d39d..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionClient.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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); -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionJMXClient.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionJMXClient.java deleted file mode 100644 index f135923646..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionJMXClient.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * 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 newMXBeanProxy(final ObjectName on, final Class 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 newMBeanProxy(final ObjectName on, final Class 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 getAvailableModuleNames() { - return configTransactionControllerMXBeanProxy.getAvailableModuleNames(); - } - - @Override - public ObjectName getObjectName() { - return configTransactionControllerON; - } - - @Override - public Set lookupConfigBeans() { - return configTransactionControllerMXBeanProxy.lookupConfigBeans(); - } - - @Override - public Set 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 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> getServiceMapping() { - return configTransactionControllerMXBeanProxy.getServiceMapping(); - } - - @Override - public Map lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) { - return configTransactionControllerMXBeanProxy.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName); - } - - @Override - public Set 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 getAvailableModuleFactoryQNames() { - return configTransactionControllerMXBeanProxy.getAvailableModuleFactoryQNames(); - } - - @Override - public Set lookupRuntimeBeans() { - return configTransactionControllerMXBeanProxy.lookupRuntimeBeans(); - } - - @Override - public Set lookupRuntimeBeans(final String moduleName, final String instanceName) { - return configTransactionControllerMXBeanProxy.lookupRuntimeBeans(moduleName, instanceName); - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/BasicCapability.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/BasicCapability.java deleted file mode 100644 index 9efd01b748..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/BasicCapability.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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 getModuleNamespace() { - return Optional.absent(); - } - - @Override - public Optional getModuleName() { - return Optional.absent(); - } - - @Override - public Optional getRevision() { - return Optional.absent(); - } - - @Override - public Optional getCapabilitySchema() { - return Optional.absent(); - } - - @Override - public Collection getLocation() { - return Collections.emptyList(); - } - - @Override - public String toString() { - return capability; - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/Capability.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/Capability.java deleted file mode 100644 index 28134617f0..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/Capability.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 getModuleNamespace(); - - Optional getModuleName(); - - Optional getRevision(); - - Optional getCapabilitySchema(); - - Collection getLocation(); -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/ModuleListener.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/ModuleListener.java deleted file mode 100644 index f2624c06b1..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/ModuleListener.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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 added, Set removed); -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/YangModuleCapability.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/YangModuleCapability.java deleted file mode 100644 index 521a09f921..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/capability/YangModuleCapability.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 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 rev = module.getRevision(); - if (rev.isPresent()) { - sb.append("&revision=").append(rev.get()); - } - return sb.toString(); - } - - @Override - public Optional getModuleName() { - return Optional.of(moduleName); - } - - @Override - public Optional getModuleNamespace() { - return Optional.of(moduleNamespace); - } - - @Override - public Optional getRevision() { - return Optional.of(revision); - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/DocumentedException.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/DocumentedException.java deleted file mode 100644 index 6554c6fed5..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/DocumentedException.java +++ /dev/null @@ -1,375 +0,0 @@ -/* - * 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 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. emptyMap()); - } - - public DocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag, - final ErrorSeverity errorSeverity, final Map 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. emptyMap()); - } - - public DocumentedException(final String message, final Exception cause, final ErrorType errorType, - final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map errorInfo) { - super(message, cause); - this.errorType = errorType; - this.errorTag = errorTag; - this.errorSeverity = errorSeverity; - this.errorInfo = errorInfo; - } - - public static DocumentedException wrap(final E exception) throws DocumentedException { - final Map 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 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 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 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 parseErrorInfo( final Node node ) { - Map 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 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 errorInfoMap = getErrorInfo(); - if( errorInfoMap != null && !errorInfoMap.isEmpty() ) { - /* - * - * message-id - * rpc - * - */ - - Node errorInfoNode = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, ERROR_INFO ); - errorInfoNode.setPrefix( rpcReply.getPrefix() ); - rpcError.appendChild( errorInfoNode ); - - for ( Entry 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 + '}'; - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/MissingNameSpaceException.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/MissingNameSpaceException.java deleted file mode 100644 index d809fd6b15..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/MissingNameSpaceException.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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. emptyMap()); - } - - public MissingNameSpaceException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag, - final DocumentedException.ErrorSeverity errorSeverity, final Map errorInfo){ - super(message,errorType,errorTag,errorSeverity,errorInfo); - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/UnexpectedElementException.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/UnexpectedElementException.java deleted file mode 100644 index 804473da47..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/UnexpectedElementException.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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. emptyMap()); - } - - public UnexpectedElementException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag, - final DocumentedException.ErrorSeverity errorSeverity, final Map errorInfo) { - super(message,errorType,errorTag,errorSeverity,errorInfo); - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/UnexpectedNamespaceException.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/UnexpectedNamespaceException.java deleted file mode 100644 index 04dfeea140..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/UnexpectedNamespaceException.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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. emptyMap()); - } - - public UnexpectedNamespaceException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag, - final DocumentedException.ErrorSeverity errorSeverity, final Map errorInfo){ - super(message,errorType,errorTag,errorSeverity,errorInfo); - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/XmlElement.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/XmlElement.java deleted file mode 100644 index f7ecde687c..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/XmlElement.java +++ /dev/null @@ -1,496 +0,0 @@ -/* - * 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 extractNamespaces() throws DocumentedException { - Map 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 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 getAttributes() { - - Map 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 getChildElementsInternal(final ElementFilteringStrategy strat) { - NodeList childNodes = element.getChildNodes(); - final List 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 getChildElements() { - return getChildElementsInternal(e -> true); - } - - public List getChildElementsWithinNamespace(final String childName, final String namespace) { - return Lists.newArrayList(Collections2.filter(getChildElementsWithinNamespace(namespace), - xmlElement -> xmlElement.getName().equals(childName))); - } - - public List 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 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 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 getOnlyChildElementOptionally(final String childName) { - List nameElements = getChildElements(childName); - if (nameElements.size() != 1) { - return Optional.absent(); - } - return Optional.of(nameElements.get(0)); - } - - public Optional getOnlyChildElementOptionally(final String childName, final String namespace) { - List 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 getOnlyChildElementWithSameNamespaceOptionally(final String childName) { - Optional namespace = getNamespaceOptionally(); - if (namespace.isPresent()) { - List 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 getOnlyChildElementWithSameNamespaceOptionally() { - Optional 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 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 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 getOnlyChildElementOptionally() { - List 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 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 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 getNamespaceOptionally() { - String namespaceURI = element.getNamespaceURI(); - if (Strings.isNullOrEmpty(namespaceURI)) { - return Optional.absent(); - } else { - return Optional.of(namespaceURI); - } - } - - public String getNamespace() throws MissingNameSpaceException { - Optional 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. - * - *
-     * <type
-     * xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">th-java:threadfactory-naming</type>
-     * 
- * - * 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 findNamespaceOfTextContent() throws DocumentedException { - Map 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 getChildElementsWithSameNamespace(final String childName) throws MissingNameSpaceException { - List children = getChildElementsWithinNamespace(getNamespace()); - return Lists.newArrayList(Collections2.filter(children, xmlElement -> xmlElement.getName().equals(childName))); - } - - public void checkUnrecognisedElements(final List recognisedElements, - final XmlElement... additionalRecognisedElements) throws DocumentedException { - List 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.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); - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/XmlMappingConstants.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/XmlMappingConstants.java deleted file mode 100644 index e896772b1d..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/XmlMappingConstants.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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() { - } -} diff --git a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/XmlUtil.java b/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/XmlUtil.java deleted file mode 100644 index fb27d6eae2..0000000000 --- a/opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/xml/XmlUtil.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * 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 DEFAULT_DOM_BUILDER = new ThreadLocal(){ - @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 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 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.absent()); - } - - public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix, - final String namespace, final String contentWithoutPrefix, final Optional 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; - } -} diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/AttributeEntryTest.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/AttributeEntryTest.java deleted file mode 100644 index 20181721e5..0000000000 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/AttributeEntryTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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()); - } -} diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/ConfigRegistryClientsTest.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/ConfigRegistryClientsTest.java deleted file mode 100644 index d0fcc7b6cd..0000000000 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/ConfigRegistryClientsTest.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * 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 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 son = jmxRegistryClient.lookupConfigBeans(); - assertEquals(3, son.size()); - } - - @Test - public void testLookupConfigBeans2() throws Exception{ - Set son = jmxRegistryClient.lookupConfigBeans(TestingConfigRegistry.moduleName1); - assertEquals(2, son.size()); - } - - @Test - public void testLookupConfigBeans() throws Exception{ - Set son = jmxRegistryClient.lookupConfigBeans(TestingConfigRegistry.moduleName1, TestingConfigRegistry.instName1); - Set 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 jmxLookup = lookupRuntimeBeans(jmxRegistryClient); - assertEquals(Sets.newHashSet(TestingConfigRegistry.run2, TestingConfigRegistry.run1, TestingConfigRegistry.run3), jmxLookup); - } - - private Set lookupRuntimeBeans(final ConfigRegistryClient client) - throws Exception { - Set 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 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 clientLookupRuntimeBeansWithModuleAndInstance( - final ConfigRegistryClient client, final String moduleName, final String instanceName) { - Set 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 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); - } -} diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/ConfigTransactionClientsTest.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/ConfigTransactionClientsTest.java deleted file mode 100644 index 29cddab15b..0000000000 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/ConfigTransactionClientsTest.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * 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 jmxLookup = testClientLookupConfigBeans(jmxTransactionClient); - assertEquals(Sets.newHashSet(transactionController.conf1, - transactionController.conf2, transactionController.conf3), - jmxLookup); - } - - private Set testClientLookupConfigBeans( - final ConfigTransactionClient client) { - Set 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 jmxMN = testClientGetAvailableModuleNames(jmxTransactionClient); - assertNull(jmxMN); - } - - private Set 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 jmxLookup = testClientLookupConfigBeans2( - jmxTransactionClient, "moduleB"); - assertEquals(Sets.newHashSet(transactionController.conf3), jmxLookup); - } - - private Set testClientLookupConfigBeans2( - final ConfigTransactionClient client, final String moduleName) { - Set beans = client.lookupConfigBeans(moduleName); - assertEquals(1, beans.size()); - return beans; - } - - @Test - public void testLookupConfigBean() throws Exception { - Set jmxLookup = testClientLookupConfigBean( - jmxTransactionClient, "moduleB", "instB"); - assertEquals(Sets.newHashSet(transactionController.conf3), jmxLookup); - } - - private Set testClientLookupConfigBean( - final ConfigTransactionClient client, final String moduleName, - final String instanceName) { - Set beans = client.lookupConfigBeans(moduleName, - instanceName); - assertEquals(1, beans.size()); - return beans; - } - - @Test - public void testLookupConfigBeans3() throws Exception { - Set jmxLookup = testClientLookupConfigBeans3( - jmxTransactionClient, "moduleB", "instB"); - assertEquals(Sets.newHashSet(transactionController.conf3), jmxLookup); - } - - private Set testClientLookupConfigBeans3( - final ConfigTransactionClient client, final String moduleName, - final String instanceName) { - Set 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.>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()); - } -} diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/LookupTest.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/LookupTest.java deleted file mode 100644 index 9a6f931afd..0000000000 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/LookupTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * 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> 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 registryClients = Sets.newHashSet(jmxRegistryClient); - HashSet 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> 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> entry : lookupProvidersToClients - .entrySet()) { - for (LookupRegistry client : entry.getValue()) { - try { - client.lookupConfigBean( - InstanceNotFoundException.class.getSimpleName(), ""); - fail(client.toString()); - } catch (final InstanceNotFoundException e) { - - } - } - } - } -} diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingBeanImpl.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingBeanImpl.java deleted file mode 100644 index 1d0b9d6131..0000000000 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingBeanImpl.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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() { - - } -} diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingBeanMXBean.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingBeanMXBean.java deleted file mode 100644 index 5d8bad361d..0000000000 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingBeanMXBean.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingConfigRegistry.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingConfigRegistry.java deleted file mode 100644 index cf1fe92638..0000000000 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingConfigRegistry.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * 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 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 getOpenConfigs() { - return null; - } - - @Override - public boolean isHealthy() { - return false; - } - - @Override - public Set getAvailableModuleNames() { - return null; - } - - @Override - public Set lookupConfigBeans() { - return Sets.newHashSet(conf1, conf2, conf3); - } - - @Override - public Set 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 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 lookupRuntimeBeans() { - return Sets. newHashSet(run1, run2, run3); - } - - @Override - public Set lookupRuntimeBeans(final String moduleName, - final String instanceName) { - if (moduleName.equals(moduleName1) && instanceName.equals(instName1)) { - return Sets. newHashSet(run2); - } else if (moduleName.equals(moduleName2) - && instanceName.equals(instName2)) { - return Sets. newHashSet(run3); - } else { - return Sets. newHashSet(); - } - } - - @Override - public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException { - Set configBeans = Sets. 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> getServiceMapping() { - return null; - } - - @Override - public Map 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 lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException { - return Sets. newHashSet(serviceQName1, serviceQName2); - } - - @Override - public String getServiceInterfaceName(final String namespace, final String localName) { - return null; - } - - @Override - public Set getAvailableModuleFactoryQNames() { - return Sets. 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(); - } -} diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingConfigTransactionController.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingConfigTransactionController.java deleted file mode 100644 index b1826e028a..0000000000 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/TestingConfigTransactionController.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * 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 mapSub; - Map> 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 getAvailableModuleNames() { - return null; - } - - @Override - public Set lookupConfigBeans() { - return Sets.newHashSet(conf1, conf2, conf3); - } - - @Override - public Set 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 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> getServiceMapping() { - mapSub.put("A",conf2); - map.put("AA", mapSub); - return map; - } - - @Override - public Map lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) { - mapSub.put("A",conf2); - return mapSub; - } - - @Override - public Set 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 getAvailableModuleFactoryQNames() { - return Sets.newHashSet("availableModuleFactoryQNames"); - } - - @Override - public Set lookupRuntimeBeans() { - return Collections.emptySet(); - } - - @Override - public Set 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"; - } -} diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/xml/XmlElementTest.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/xml/XmlElementTest.java deleted file mode 100644 index 28266bb502..0000000000 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/xml/XmlElementTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * 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 = "" + - "" + - "deepValue" + - "" + - "innerNamespaceValue" + - "b:valueWithPrefix" + - ""; - 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(""); - 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.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 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"))); - } - } -} diff --git a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/xml/XmlUtilTest.java b/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/xml/XmlUtilTest.java deleted file mode 100644 index 5ccee8679a..0000000000 --- a/opendaylight/config/config-util/src/test/java/org/opendaylight/controller/config/util/xml/XmlUtilTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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 = "\n" + - "value\n" + - "prefix:value\n" + - "prefix:value\n" + - ""; - - @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("\n" + - "]>\n" + - "\n" + - " \n" + - " urn:ietf:params:netconf:base:1.0 &xxe;\n" + - " \n" + - " ]]>]]>"); - } - -} \ No newline at end of file diff --git a/opendaylight/config/pom.xml b/opendaylight/config/pom.xml index 1afe5f4864..d350871ccd 100644 --- a/opendaylight/config/pom.xml +++ b/opendaylight/config/pom.xml @@ -16,32 +16,13 @@ ${project.artifactId} - config-api - config-manager - config-plugin-parent - config-util - config-persister-api - config-persister-file-xml-adapter - config-persister-feature-adapter - config-manager-facade-xml - yang-jmx-generator - yang-jmx-generator-plugin threadpool-config-api netty-config-api threadpool-config-impl netty-threadgroup-config netty-event-executor-config netty-timer-config - config-persister-directory-xml-adapter - yang-test-plugin - shutdown-api - shutdown-impl - config-netty-config config-artifacts - config-parent - config-filtering-parent - config-persister-impl - config-it-base @@ -55,16 +36,4 @@
- - - - integrationtests - - false - - - yang-jmx-generator-it - - - diff --git a/opendaylight/config/shutdown-api/pom.xml b/opendaylight/config/shutdown-api/pom.xml deleted file mode 100644 index 25d5b52635..0000000000 --- a/opendaylight/config/shutdown-api/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-plugin-parent - 0.9.0-SNAPSHOT - ../config-plugin-parent - - shutdown-api - bundle - - - - com.google.guava - guava - - - org.opendaylight.controller - config-api - - - - - - - org.apache.felix - maven-bundle-plugin - - - org.opendaylight.yangtools - yang-maven-plugin - - - - - diff --git a/opendaylight/config/shutdown-api/src/main/java/org/opendaylight/controller/config/shutdown/ShutdownService.java b/opendaylight/config/shutdown-api/src/main/java/org/opendaylight/controller/config/shutdown/ShutdownService.java deleted file mode 100644 index 5cbe4931ef..0000000000 --- a/opendaylight/config/shutdown-api/src/main/java/org/opendaylight/controller/config/shutdown/ShutdownService.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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 reason); -} diff --git a/opendaylight/config/shutdown-api/src/main/yang/shutdown.yang b/opendaylight/config/shutdown-api/src/main/yang/shutdown.yang deleted file mode 100644 index eb09178841..0000000000 --- a/opendaylight/config/shutdown-api/src/main/yang/shutdown.yang +++ /dev/null @@ -1,29 +0,0 @@ -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"; - } - -} diff --git a/opendaylight/config/shutdown-impl/pom.xml b/opendaylight/config/shutdown-impl/pom.xml deleted file mode 100644 index 32320223bd..0000000000 --- a/opendaylight/config/shutdown-impl/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-plugin-parent - 0.9.0-SNAPSHOT - ../config-plugin-parent - - shutdown-impl - bundle - - - - com.google.guava - guava - - - org.opendaylight.controller - config-api - - - org.opendaylight.controller - shutdown-api - - - org.opendaylight.yangtools - mockito-configuration - - - org.opendaylight.controller - config-manager - test-jar - test - - - org.opendaylight.controller - config-manager - test - - - org.opendaylight.controller - config-util - test - - - - - - - org.apache.felix - maven-bundle-plugin - - - org.opendaylight.yangtools - yang-maven-plugin - - - - - diff --git a/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownModule.java b/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownModule.java deleted file mode 100644 index 57efe52827..0000000000 --- a/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownModule.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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()); - } -} diff --git a/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownModuleFactory.java b/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownModuleFactory.java deleted file mode 100644 index de7ed0fa66..0000000000 --- a/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownModuleFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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 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)); - } -} diff --git a/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownServiceImpl.java b/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownServiceImpl.java deleted file mode 100644 index 74634dd157..0000000000 --- a/opendaylight/config/shutdown-impl/src/main/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownServiceImpl.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * 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 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 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 optionalReason; - if (nullableReason == null) { - optionalReason = Optional.absent(); - } else { - optionalReason = Optional.of(nullableReason); - } - impl.shutdown(inputSecret, maxWaitTime, optionalReason); - } -} diff --git a/opendaylight/config/shutdown-impl/src/main/yang/shutdown-impl.yang b/opendaylight/config/shutdown-impl/src/main/yang/shutdown-impl.yang deleted file mode 100644 index 883735c0c8..0000000000 --- a/opendaylight/config/shutdown-impl/src/main/yang/shutdown-impl.yang +++ /dev/null @@ -1,71 +0,0 @@ -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; - } - } - } -} diff --git a/opendaylight/config/shutdown-impl/src/test/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownTest.java b/opendaylight/config/shutdown-impl/src/test/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownTest.java deleted file mode 100644 index 5dd856a605..0000000000 --- a/opendaylight/config/shutdown-impl/src/test/java/org/opendaylight/controller/config/yang/shutdown/impl/ShutdownTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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.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(); - } -} diff --git a/opendaylight/config/yang-jmx-generator-it/pom.xml b/opendaylight/config/yang-jmx-generator-it/pom.xml deleted file mode 100644 index 8f3f29b179..0000000000 --- a/opendaylight/config/yang-jmx-generator-it/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-subsystem - 0.9.0-SNAPSHOT - - - yang-jmx-generator-it - ${project.artifactId} - - - - org.opendaylight.yangtools - mockito-configuration - - - ${project.groupId} - config-api - test - - - ${project.groupId} - config-manager - test-jar - test - - - ${project.groupId} - config-manager - test - - - ${project.groupId} - config-util - test - - - ${project.groupId} - yang-test - test - - - diff --git a/opendaylight/config/yang-jmx-generator-it/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/it/ITTest.java b/opendaylight/config/yang-jmx-generator-it/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/it/ITTest.java deleted file mode 100644 index 9f5498cf70..0000000000 --- a/opendaylight/config/yang-jmx-generator-it/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/it/ITTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * 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; - - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/pom.xml b/opendaylight/config/yang-jmx-generator-plugin/pom.xml deleted file mode 100644 index d1010d2f3b..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/pom.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-subsystem - 0.9.0-SNAPSHOT - .. - - yang-jmx-generator-plugin - - - - - ${project.groupId} - config-api - - - - com.google.guava - guava - - - - org.apache.commons - commons-lang3 - - - - org.opendaylight.controller - yang-jmx-generator - - - - org.opendaylight.mdsal - mdsal-binding-generator-impl - - - - org.opendaylight.yangtools - mockito-configuration - - - - org.opendaylight.yangtools - yang-maven-plugin-spi - - - org.apache.maven - maven-core - 3.1.1 - provided - - - - org.slf4j - slf4j-api - - - - net.sourceforge.pmd - pmd - 5.1.0 - test - - - - com.github.javaparser - javaparser-core - 2.3.0 - test - - - - org.opendaylight.controller - yang-jmx-generator - test-jar - test - - - - org.opendaylight.yangtools - yang-test-util - - - - - diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/CodeWriter.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/CodeWriter.java deleted file mode 100644 index 93a432c3fe..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/CodeWriter.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * 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 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 writeMbe(final ModuleMXBeanEntry mbe, final File targetBaseDir, - final File mainBaseDir) { - try { - List generatedFiles = Lists.newArrayList(); - - - Map gos = new HashMap<>(); - - // generate mx interface and abstract factory - - // TOs - Map 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.absent()), false); - - // write runtime bean MXBeans and registrators - List 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 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 persistGeneratedObjects(final File targetBaseDir, final File mainBaseDir, - final Map gos) throws IOException { - List generatedFiles = new ArrayList<>(); - for (Entry entry : gos.entrySet()) { - boolean overwrite = entry.getValue(); - File dst; - if (overwrite) { - dst = targetBaseDir; - } else { - dst = mainBaseDir; - } - Optional> maybePersistEntry = entry.getKey().persist(dst, overwrite); - - if (maybePersistEntry.isPresent()) { - generatedFiles.add(maybePersistEntry.get().getValue()); - } - } - return generatedFiles; - } - - private static List getRuntimeBeanFtlTemplates(final Collection runtimeBeans) { - if (runtimeBeans.isEmpty()) { - return Collections.emptyList(); - } - List allFtlFiles = new ArrayList<>(); - { // registrators - Map registratorNamesToFtls = RuntimeRegistratorFtlTemplate - .create(RuntimeRegistratorFtlTemplate.findRoot(runtimeBeans)); - - allFtlFiles.addAll(registratorNamesToFtls.values()); - } - { // TOs, MXBean interfaces - for (RuntimeBeanEntry runtimeBeanEntry : runtimeBeans) { - Collection ftlFiles = TemplateFactory - .getTOAndMXInterfaceFtlFiles(runtimeBeanEntry) - .values(); - allFtlFiles.addAll(ftlFiles); - } - } - return allFtlFiles; - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGenerator.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGenerator.java deleted file mode 100644 index 18eb601747..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGenerator.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * 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 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 generateSources(final SchemaContext context, final File outputBaseDir, - final Set currentModules, final Function> 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 qNamesToSIEs = new HashMap<>(); - - - final Map knownSEITracker = new HashMap<>(); - for (final Module module : context.getModules()) { - final String packageName = packageTranslator.getPackageName(module); - final Map namesToSIEntries = ServiceInterfaceEntry - .create(module, packageName, knownSEITracker); - - for (final Entry 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 namesToMBEs = ModuleMXBeanEntry - .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)), - packageName); - - for (final Entry mbeEntry : namesToMBEs - .entrySet()) { - final ModuleMXBeanEntry mbe = mbeEntry.getValue(); - try { - final List 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 additionalCfg) { - LOG.debug("{}: Additional configuration received: {}", getClass().getCanonicalName(), additionalCfg); - this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg); - this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg); - } - - private static boolean extractModuleFactoryBoolean(final Map additionalCfg) { - final String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN); - return !"false".equals(bool); - } - - private static Map extractNamespaceMapping( - final Map additionalCfg) { - final Map 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 files = new HashSet<>(); - - void addFile(final File file) { - if (this.files.contains(file)) { - final List 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 files) { - for (final File file : files) { - addFile(file); - } - } - - public Set getFiles() { - return this.files; - } - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/AbstractFactoryTemplate.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/AbstractFactoryTemplate.java deleted file mode 100644 index 52b6bc165a..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/AbstractFactoryTemplate.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 IMPLEMENTED_IFCS = Lists - .newArrayList(ModuleFactory.class.getCanonicalName()); - - public AbstractFactoryTemplate(Header header, String packageName, - String abstractFactoryName, - List fields) { - super(header, packageName, abstractFactoryName, Collections - . emptyList(), IMPLEMENTED_IFCS, fields, Collections - . emptyList(), true, false, Collections - . emptyList()); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/AbstractFtlTemplate.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/AbstractFtlTemplate.java deleted file mode 100644 index edcd11d9de..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/AbstractFtlTemplate.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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 fields; - private final List annotations; - private final List methods; - private String javadoc = null; - private final TypeDeclaration typeDeclaration; - private final Header header; - - protected AbstractFtlTemplate(Header header, String packageName, - List fields, List 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 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 getMaybeJavadoc() { - if (javadoc == null) { - return Optional.absent(); - } else { - return Optional.of(javadoc); - } - } - - public void setJavadoc(String javadoc) { - this.javadoc = javadoc; - } - - @Override - public List getAnnotations() { - return annotations; - } - - @Override - public List getFields() { - return fields; - } - - @Override - public List getMethods() { - return methods; - } - - - @Override - public List getConstructors() { - return Collections.emptyList(); - } - - @Override - public String toString() { - return "AbstractFtlTemplate{" + "typeDeclaration=" + typeDeclaration - + ", packageName='" + packageName + '\'' + '}'; - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/AbstractModuleTemplate.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/AbstractModuleTemplate.java deleted file mode 100644 index 487bf63e62..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/AbstractModuleTemplate.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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 moduleFields; - private final boolean runtime; - private final String registratorType; - - public AbstractModuleTemplate(Header header, String packageName, - String abstractModuleName, List extendedClasses, - List implementedIfcs, List moduleFields, List methods, - boolean isRuntime, String registratorType) { - super(header, packageName, abstractModuleName, extendedClasses, - implementedIfcs, Collections. emptyList(), methods, - true, false, Collections. emptyList()); - this.moduleFields = moduleFields; - this.runtime = isRuntime; - this.registratorType = registratorType; - } - - public List getModuleFields() { - return moduleFields; - } - - public String getRegistratorType() { - return registratorType; - } - - public boolean isRuntime() { - return runtime; - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/FtlTemplate.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/FtlTemplate.java deleted file mode 100644 index 68d0b717a9..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/FtlTemplate.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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 getHeaderString(); - - String getPackageName(); - - Optional getMaybeJavadoc(); - - List getAnnotations(); - - TypeDeclaration getTypeDeclaration(); - - String getFullyQualifiedName(); - - List getFields(); - - List getMethods(); - - List getConstructors(); -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/GeneralClassTemplate.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/GeneralClassTemplate.java deleted file mode 100644 index 4adb2b0cf5..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/GeneralClassTemplate.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 constructors; - - public GeneralClassTemplate(Header header, String packageName, String name, - List extendedClasses, List implementedIfcs, - List fields, List methods) { - this(header, packageName, name, extendedClasses, implementedIfcs, - fields, methods, false, false, Collections - . emptyList()); - } - - public GeneralClassTemplate(Header header, String packageName, String name, - List extendedClasses, List implementedIfcs, - List fields, List methods, - boolean isAbstract, boolean isFinal, List constructors) { - super(header, packageName, fields, methods, new TypeDeclaration( - "class", name, checkCardinality(extendedClasses), - implementedIfcs, isAbstract, isFinal)); - this.constructors = constructors; - } - - static List checkCardinality(List extendedClass) { - if (extendedClass.size() > 1) { - throw new IllegalArgumentException( - "Class cannot have more than one super class, found: " + extendedClass); - } - return extendedClass; - } - - public List getConstructors() { - return constructors; - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/GeneralInterfaceTemplate.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/GeneralInterfaceTemplate.java deleted file mode 100644 index 6842ed1cf5..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/GeneralInterfaceTemplate.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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 extendedInterfaces, - List methods) { - super(header, packageName, Collections. emptyList(), methods, - new TypeDeclaration("interface", name, extendedInterfaces, - Collections. emptyList())); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/RuntimeRegistratorFtlTemplate.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/RuntimeRegistratorFtlTemplate.java deleted file mode 100644 index 47a1dfcfb1..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/RuntimeRegistratorFtlTemplate.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * 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 fields, List methods) { - // TODO header - super(null, runtimeBeanEntry.getPackageName(), name, Collections - .emptyList(), Collections.singletonList(Closeable.class - .getCanonicalName()), fields, methods); - } - - public static RuntimeBeanEntry findRoot( - Collection 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 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 create(RuntimeBeanEntry rootRB) { - checkArgument(rootRB.isRoot(), "RuntimeBeanEntry must be root"); - String registratorName = getJavaNameOfRuntimeRegistrator(rootRB); - List methods = new ArrayList<>(); - Field rootRuntimeBeanRegistratorField = new Field( - Collections.singletonList(Modifier.FINAL), - RootRuntimeBeanRegistrator.class.getName(), - "rootRuntimeBeanRegistrator"); - List constructorParameters = Lists - .newArrayList(rootRuntimeBeanRegistratorField); - String constructorBody = constructConstructorBody(constructorParameters); - MethodDefinition constructor = MethodDefinition.createConstructor( - registratorName, constructorParameters, constructorBody); - methods.add(constructor); - - LinkedHashMap 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 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 createRegistrationHierarchy( - RuntimeBeanEntry parent, Set occupiedKeys) { - LinkedHashMap unorderedResult = new LinkedHashMap<>(); - List methods = new ArrayList<>(); - - // hierarchy of ON is created as follows: - // root RB: , type=RuntimeBean - // 1st RB in hierarchy: , type=RuntimeBean, : key or counter - // n-th RB in hierarchy has same ON as n-1, with added : 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 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 childRegistratorMap = createRegistrationHierarchy( - child, currentOccupiedKeys); - for (Entry 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 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 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 privateFields = Lists.newArrayList(registratorsMapField); - privateFields.addAll(constructorParameters); - - RuntimeRegistratorFtlTemplate created = new RuntimeRegistratorFtlTemplate( - parent, createdName, privateFields, methods); - - LinkedHashMap 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. emptyList(), "void", - // "close", Collections. emptyList(), - // Arrays.asList(IOException.class.getCanonicalName()), - // Collections. emptyList(), body); - List 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"; - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/StubFactoryTemplate.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/StubFactoryTemplate.java deleted file mode 100644 index 1dd23a153b..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/StubFactoryTemplate.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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. emptyList(), Collections - . emptyList(), Collections - . emptyList()); - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TemplateFactory.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TemplateFactory.java deleted file mode 100644 index 2f63795ae0..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TemplateFactory.java +++ /dev/null @@ -1,729 +0,0 @@ -/* - * 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 getTOAndMXInterfaceFtlFiles( - final RuntimeBeanEntry entry) { - final Map result = new HashMap<>(); - { // create GeneralInterfaceFtlFile for runtime MXBean. Attributes will - // be transformed to getter methods - final String mxBeanTypeName = entry.getJavaNameOfRuntimeMXBean(); - final List extendedInterfaces = Collections.singletonList(RuntimeBean.class - .getCanonicalName()); - final List 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. emptyList()); - methods.add(getter); - } - - // add rpc methods - for (final Rpc rpc : entry.getRpcs()) { - // convert JavaAttribute parameters into fields - final List 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 ? ""); - 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 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. 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 moduleFields = attrProcessor.getModuleFields(); - final List 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 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. newArrayList(), - attrProcessor.getMethods()); - ifcTemplate.setJavadoc(mbe.getNullableDescription()); - return ifcTemplate; - } - - public static Map tOsFromMbe( - final ModuleMXBeanEntry mbe) { - final Map 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 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. emptyList(), - Collections. emptyList(), to.getFields(), - to.getMethods(), false, false, constructors)); - } - return retVal; - } - - public static Map tOsFromRbe( - final RuntimeBeanEntry rbe) { - final Map retVal = Maps.newHashMap(); - final TOAttributesProcessor processor = new TOAttributesProcessor(); - final Map 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 constructors = Lists.newArrayList(); - constructors.add(new Constructor(to.getName(), "super();")); - - // TODO header - retVal.put( - to.getType(), - new GeneralClassTemplate(null, rbe.getPackageName(), to - .getName(), Collections. emptyList(), - Collections. 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 tos = Lists.newArrayList(); - - void processAttributes(final Map attributes) { - for (final Entry 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 attrs = toAttribute.getCapitalizedPropertiesToTypesMap(); - // recursive processing of TO's attributes - processAttributes(attrs); - - this.tos.add(new TOInternal(toAttribute.getType(), attrs)); - } - - List getTOs() { - return this.tos; - } - - private static class TOInternal { - private final String fullyQualifiedName, name; - private List fields; - private List methods; - - public TOInternal(final Type type, final Map attrs) { - this(type.getFullyQualifiedName(), type.getName(), attrs, type.getPackageName()); - } - - public TOInternal(final String fullyQualifiedName, final String name, - final Map 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 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 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.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. 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 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.emptyList())), equalsBodyBuilder.toString()); - } - - private static MethodDefinition getHash(final Map 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.emptyList(), - Collections.singletonList(new Annotation("Override", Collections.emptyList())), hashBodyBuilder.toString()); - } - - String getType() { - return this.fullyQualifiedName; - } - - String getName() { - return this.name; - } - - List getFields() { - return this.fields; - } - - List getMethods() { - return this.methods; - } - } - } - - - private static class MXBeanInterfaceAttributesProcessor { - private final List methods = Lists.newArrayList(); - - void processAttributes(final Map attributes) { - for (final Entry 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. 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 getMethods() { - return this.methods; - } - } - - private static final Type identityRefType = new Type() { - public final Class 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 fields = Lists.newArrayList(); - - void processAttributes(final Map 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 getFields() { - return this.fields; - } - } - - private static class AbstractModuleAttributesProcessor { - private static class Holder { - private final List moduleFields; - private final List methods; - - private Holder(final List moduleFields, final List methods) { - this.moduleFields = Collections.unmodifiableList(moduleFields); - this.methods = Collections.unmodifiableList(methods); - } - } - - private final Holder holder; - - - private AbstractModuleAttributesProcessor(final Map attributes) { - this.holder = processAttributes(attributes); - } - - private static Holder processAttributes(final Map attributes) { - final List moduleFields = new ArrayList<>(); - final List methods = new ArrayList<>(); - for (final Entry 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. emptyList()); - final List 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. emptyList(), - Collections. 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. 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. 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 getModuleFields() { - return this.holder.moduleFields; - } - - List 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]); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TypeHelper.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TypeHelper.java deleted file mode 100644 index 468d20c0db..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/TypeHelper.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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" 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(); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Annotation.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Annotation.java deleted file mode 100644 index 541c28a0c5..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Annotation.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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 params; - - public Annotation(final String name, final List params) { - this.name = name; - this.params = params; - } - - public String getName() { - return name; - } - - public List getParams() { - return params; - } - - public static Annotation createFromMap(final Class annotationClass, final Map parameters) { - List parameterList = new ArrayList<>(); - for(Entry 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 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 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 result = new ArrayList<>(); - { - List 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 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); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/AnnotationSerializer.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/AnnotationSerializer.java deleted file mode 100644 index 6b4ce38621..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/AnnotationSerializer.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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(" +", " "); - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Constructor.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Constructor.java deleted file mode 100644 index 915e8c5753..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Constructor.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/ConstructorSerializer.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/ConstructorSerializer.java deleted file mode 100644 index 23d3ac254f..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/ConstructorSerializer.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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(); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Field.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Field.java deleted file mode 100644 index c08a440f7f..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Field.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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 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 modifiers, String type, String name) { - this(modifiers, type, name, null, false); - } - - public Field(List modifiers, String type, String name, - String definition) { - this(modifiers, type, name, definition, false); - } - - public Field(List 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 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); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/FieldSerializer.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/FieldSerializer.java deleted file mode 100644 index 1f61f8f0ee..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/FieldSerializer.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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(); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Header.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Header.java deleted file mode 100644 index f8f58d073f..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Header.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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); - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/HeaderSerializer.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/HeaderSerializer.java deleted file mode 100644 index 5eabeabd0d..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/HeaderSerializer.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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 "; - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/IdentityRefModuleField.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/IdentityRefModuleField.java deleted file mode 100644 index f50bdb98cf..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/IdentityRefModuleField.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Method.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Method.java deleted file mode 100644 index 2394fc0d1d..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/Method.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 getVisibility(); - - List getModifiers(); - - String getReturnType(); - - String getName(); - - List getParameters(); - - String getJavadoc(); - - List getAnnotations(); - - List getThrowsExceptions(); - - Optional getBody(); -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/MethodDeclaration.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/MethodDeclaration.java deleted file mode 100644 index 958eaba9fc..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/MethodDeclaration.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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 parameters; - private String javadoc = null; - private final List annotations; - - public MethodDeclaration(String returnType, String name, - List parameters) { - this(returnType, name, parameters, Collections.emptyList()); - } - - public MethodDeclaration(String returnType, String name, - List parameters, List annotations) { - this.returnType = returnType; - this.name = name; - this.parameters = parameters; - this.annotations = annotations; - } - - @Override - public List getAnnotations() { - return annotations; - } - - @Override - public List getThrowsExceptions() { - return Collections.emptyList(); - } - - @Override - public Optional getBody() { - return Optional.empty(); - } - - @Override - public String getJavadoc() { - return javadoc; - } - - public void setJavadoc(String javadoc) { - this.javadoc = javadoc; - } - - @Override - public Optional getVisibility() { - return Optional.empty(); - } - - @Override - public String getReturnType() { - return returnType; - } - - @Override - public String getName() { - return name; - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public List getModifiers() { - return Collections.emptyList(); - } - - @Override - public String toString() { - return MethodSerializer.toString(this); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/MethodDefinition.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/MethodDefinition.java deleted file mode 100644 index 8a2909d81c..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/MethodDefinition.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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 modifiers; - private final String returnType; - private final String name; - private final List parameters; - private final List throwsExceptions; - private final String body; - private String javadoc = null; - private final List annotations; - - // TODO remove, Constructor is in separate class - public static MethodDefinition createConstructor(String name, - List parameters, String body) { - return new MethodDefinition("", name, parameters, body); - - } - - public MethodDefinition(String returnType, String name, - List parameters, String body) { - this(Collections.emptyList(), returnType, name, parameters, - Collections.emptyList(), Collections.emptyList(), body); - } - - public MethodDefinition(String returnType, String name, - List parameters, List annotations, String body) { - this(Collections.emptyList(), returnType, name, parameters, - Collections.emptyList(), annotations, body); - } - - public MethodDefinition(List modifiers, String returnType, - String name, List parameters, List throwsExceptions, - List 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 getAnnotations() { - return annotations; - } - - @Override - public String getJavadoc() { - return javadoc; - } - - public void setJavadoc(String javadoc) { - this.javadoc = javadoc; - } - - @Override - public Optional getVisibility() { - return Optional.of(Modifier.PUBLIC); - } - - @Override - public String getReturnType() { - return returnType; - } - - @Override - public String getName() { - return name; - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public List getThrowsExceptions() { - return throwsExceptions; - } - - @Override - public Optional getBody() { - return Optional.of(body); - } - - @Override - public List getModifiers() { - return modifiers; - } - - @Override - public String toString() { - return MethodSerializer.toString(this); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/MethodSerializer.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/MethodSerializer.java deleted file mode 100644 index a37a8d653b..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/MethodSerializer.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 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 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(); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/ModuleField.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/ModuleField.java deleted file mode 100644 index bd28d93756..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/ModuleField.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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 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"); - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/ModuleFieldSerializer.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/ModuleFieldSerializer.java deleted file mode 100644 index bad7618c12..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/ModuleFieldSerializer.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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(); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/TypeDeclaration.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/TypeDeclaration.java deleted file mode 100644 index be917dfdda..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ftl/model/TypeDeclaration.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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 extended, implemented; - private final boolean isAbstract, isFinal; - - public TypeDeclaration(String type, String name, List extended, - List 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 extended, - List 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 getExtended() { - return extended; - } - - public List 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 - + '\'' + '}'; - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsFactoryGeneratedObjectFactory.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsFactoryGeneratedObjectFactory.java deleted file mode 100644 index dad6222c26..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsFactoryGeneratedObjectFactory.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * 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 copyright) { - FullyQualifiedName absFactoryFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getAbstractFactoryName()); - FullyQualifiedName moduleFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getStubModuleName()); - Optional classJavaDoc = Optional.fromNullable(mbe.getNullableDescription()); - - AbstractFactoryTemplate abstractFactoryTemplate = TemplateFactory.abstractFactoryTemplateFromMbe(mbe); - Optional header = abstractFactoryTemplate.getHeaderString(); - - List 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 copyright, - Optional header, Optional classJavaDoc, QName yangModuleQName, - String globallyUniqueName, - List providedServices, - FullyQualifiedName moduleFQN, - List 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> 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 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 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 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 providedServices) { - String generic = format("Class", 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 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> getImplementedServiceIntefaces() {\n" - + "return serviceIfcs;\n" - + "}\n", AbstractServiceInterface.class.getCanonicalName())); - - return result.toString(); - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java deleted file mode 100644 index 044431844d..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java +++ /dev/null @@ -1,407 +0,0 @@ -/* - * 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 copyright) { - FullyQualifiedName abstractFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getAbstractModuleName()); - Optional classJavaDoc = Optional.fromNullable(mbe.getNullableDescription()); - AbstractModuleTemplate abstractModuleTemplate = TemplateFactory.abstractModuleTemplateFromMbe(mbe); - Optional header = abstractModuleTemplate.getHeaderString(); - - List implementedInterfaces = - Lists.transform(abstractModuleTemplate.getTypeDeclaration().getImplemented(), - FullyQualifiedName::fromString); - - Optional extended = - Optional.fromNullable( - Iterables.getFirst( - Collections2.transform(abstractModuleTemplate.getTypeDeclaration().getExtended(), - FullyQualifiedName::fromString), null)); - - Optional 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 copyright, - Optional header, - Optional classJavaDoc, - Optional extended, - List implementedInterfaces, - List moduleFields, - Optional maybeRegistratorType, - List 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 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 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 moduleFields) { - // loop through dependent fields, use dependency resolver to instantiate dependencies. Do it in loop in case field represents list of dependencies. - Map 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 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 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 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 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 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 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 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 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.emptyList(), "return LOG;").toString(); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/ConcreteModuleGeneratedObjectFactory.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/ConcreteModuleGeneratedObjectFactory.java deleted file mode 100644 index e597bba8bb..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/ConcreteModuleGeneratedObjectFactory.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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 copyright, Optional header) { - FullyQualifiedName concreteFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getStubModuleName()); - FullyQualifiedName abstractFQN = new FullyQualifiedName(mbe.getPackageName(), mbe.getAbstractModuleName()); - Optional classJavaDoc = Optional.fromNullable(mbe.getNullableDescription()); - return toGeneratedObject(concreteFQN, abstractFQN, copyright, header, classJavaDoc); - } - - GeneratedObject toGeneratedObject(FullyQualifiedName concreteFQN, - FullyQualifiedName abstractFQN, - Optional copyright, - Optional header, - Optional 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 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 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 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"+ - "}"; - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/GenericGeneratedObjectFactory.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/GenericGeneratedObjectFactory.java deleted file mode 100644 index 11bb6774ae..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/GenericGeneratedObjectFactory.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 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(); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/FullyQualifiedName.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/FullyQualifiedName.java deleted file mode 100644 index c4a1b270a7..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/FullyQualifiedName.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/GeneratedObject.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/GeneratedObject.java deleted file mode 100644 index 14619a2480..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/GeneratedObject.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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> 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> 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(); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/GeneratedObjectBuilder.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/GeneratedObjectBuilder.java deleted file mode 100644 index 13418f3a47..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/GeneratedObjectBuilder.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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 comment) { - return maybeAddComment(comment, false); - } - - private static String maybeAddComment(Optional comment, boolean isJavadoc) { - if (comment.isPresent()) { - String input = comment.get(); - return StringUtil.writeComment(input, isJavadoc); - } else { - return ""; - } - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/JavaFileInput.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/JavaFileInput.java deleted file mode 100644 index 085b31a2d8..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/JavaFileInput.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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 getCopyright(); - - Optional getHeader(); - - List getImports(); - - TypeName getType(); - - Optional getClassJavaDoc(); - - List getClassAnnotations(); - - List getExtends(); - - List getImplements(); - - List getBodyElements(); - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/JavaFileInputBuilder.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/JavaFileInputBuilder.java deleted file mode 100644 index c498c5bf9f..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/JavaFileInputBuilder.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * 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 copyright = Optional.absent(), header = Optional.absent(), classJavaDoc = Optional.absent(); - - private TypeName typeName = TypeName.classType; - - private FullyQualifiedName fqn; - - private final List classAnnotations = new ArrayList<>(); - - private final List importFQNs = new ArrayList<>(); - - private final List extendsFQNs = new ArrayList<>(); - - private final List implementsFQNs = new ArrayList<>(); - - private final List 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 getCopyright() { - return copyright; - } - - public void setCopyright(Optional copyright) { - this.copyright = checkNotNull(copyright); - } - - public Optional getHeader() { - return header; - } - - public void setHeader(Optional header) { - this.header = checkNotNull(header); - } - - - public Optional getClassJavaDoc() { - return classJavaDoc; - } - - public void setClassJavaDoc(Optional classJavaDoc) { - this.classJavaDoc = checkNotNull(classJavaDoc); - } - - - public FullyQualifiedName getFqn() { - return fqn; - } - - public void setFqn(FullyQualifiedName fqn) { - this.fqn = fqn; - } - - public List getExtendsFQNs() { - return extendsFQNs; - } - - - public List 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 getCopyright() { - return copyright; - } - - @Override - public Optional getHeader() { - return header; - } - - @Override - public List getImports() { - return Collections.unmodifiableList(importFQNs); - } - - @Override - public Optional getClassJavaDoc() { - return classJavaDoc; - } - - @Override - public TypeName getType() { - return typeName; - } - - @Override - public List getExtends() { - return Collections.unmodifiableList(extendsFQNs); - } - - @Override - public List getImplements() { - return Collections.unmodifiableList(implementsFQNs); - } - - @Override - public List getClassAnnotations() { - return Collections.unmodifiableList(classAnnotations); - } - - @Override - public List getBodyElements() { - return Collections.unmodifiableList(bodyElements); - } - - }; - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/TypeName.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/TypeName.java deleted file mode 100644 index 14046170f6..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/java/TypeName.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/StringUtil.java b/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/StringUtil.java deleted file mode 100644 index 01a495bf15..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/StringUtil.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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 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 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 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()); - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/AbstractGeneratorTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/AbstractGeneratorTest.java deleted file mode 100644 index a17d50da52..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/AbstractGeneratorTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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(); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/AbstractVerifier.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/AbstractVerifier.java deleted file mode 100644 index d9dd5d0cb0..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/AbstractVerifier.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 { - 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); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorFileNamesValidationTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorFileNamesValidationTest.java deleted file mode 100644 index de868d6e89..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorFileNamesValidationTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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")); - } - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorGeneratedFilesTrackerTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorGeneratedFilesTrackerTest.java deleted file mode 100644 index 1e48d9a8c9..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorGeneratedFilesTrackerTest.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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")); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorTest.java deleted file mode 100644 index c306a1bbd1..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/JMXGeneratorTest.java +++ /dev/null @@ -1,466 +0,0 @@ -/* - * 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 map = new HashMap<>(); - protected File outputBaseDir; - File generatedResourcesDir; - - private static final List 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 expectedBGPNames = ServiceInterfaceEntryTest - .toFileNames("[AbstractBgpListenerImplModule.java, " + "AbstractBgpListenerImplModuleFactory.java, " + - "BgpListenerImplModule.java, " + "BgpListenerImplModuleFactory.java, " + - "BgpListenerImplModuleMXBean.java, Peers.java]"); - - private static final List 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 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 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 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 files = jmxGenerator.generateSources(context, outputBaseDir, context.getModules(), - m -> Optional.empty()); - List 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 toFileNames(final Collection files) { - List result = new ArrayList<>(); - for (File f : files) { - result.add(f.getName()); - } - Collections.sort(result); - return result; - } - - @Test - public void generateSIEsTest() throws IOException, ParseException { - Collection 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 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 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 lines = ImmutableSet.copyOf(Files.readLines(moduleFactoryFile, StandardCharsets.UTF_8)); - Set 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 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> serviceIfcs"); - - assertFactoryMethods(visitor.methods, 10); - visitor.assertMethodDescriptions(0); - visitor.assertMethodJavadocs(0); - } - - private static void assertFactoryMethods(final Set methods, final int expectedSize) { - - List 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", "getDefaultModules", args)); - - args.clear(); - args.add(new ArgumentAssertion("Class", "serviceInterface")); - assertMethodPresent(methods, new MethodAssertion("boolean", "isModuleImplementingServiceInterface", args)); - - assertEquals(expectedSize, methods.size()); - } - - private static void assertMethodPresent(final Set 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 arguments; - - - MethodAssertion(final String type, final String name, final List arguments) { - super(type, name); - this.arguments = arguments; - } - - MethodAssertion(final String type, final String name) { - this(type, name, Collections.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; - } - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/MbeASTVisitor.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/MbeASTVisitor.java deleted file mode 100644 index 57770c3927..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/MbeASTVisitor.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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 constructors = new HashSet<>(); - private final Set fieldDeclarations = new HashSet<>(); - final Set methods = new HashSet<>(); - private final Map methodJavadoc = new HashMap<>(); - final Map 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 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()); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ModuleMXBeanEntryPluginTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ModuleMXBeanEntryPluginTest.java deleted file mode 100644 index d05ef0e2b9..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ModuleMXBeanEntryPluginTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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 namesToMBEs = loadThreadsJava(); - {// check threadfactory-naming - ModuleMXBeanEntry threadFactoryNaming = namesToMBEs - .get(THREADFACTORY_NAMING_MXB_NAME); - Collection 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 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 runtimeBeans = threadFactoryNaming - .getRuntimeBeans(); - assertThat(runtimeBeans.size(), is(4)); - - { - RuntimeBeanEntry streamRB = findFirstByNamePrefix(runtimeBeans, - "ThreadStream"); - assertNotNull(streamRB); - assertFalse(streamRB.getKeyYangName().isPresent()); - assertFalse(streamRB.getKeyJavaName().isPresent()); - Map 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 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 methods, final String name) { - for (Method ms : methods) { - if (name.equals(ms.getName())) { - return ms; - } - } - throw new IllegalArgumentException("Method with given name not found"); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ModuleMXBeanEntryTemplatesTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ModuleMXBeanEntryTemplatesTest.java deleted file mode 100644 index e4e955987d..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/ModuleMXBeanEntryTemplatesTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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 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; - } - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/RuntimeRegistratorFtlFileTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/RuntimeRegistratorFtlFileTest.java deleted file mode 100644 index 925f95ab83..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/RuntimeRegistratorFtlFileTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 - . emptyList()); - Map 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. emptyList(), "grand"); - RuntimeBeanEntry childRB = prepareChildRB(Arrays.asList(grandChildRB), - ""); - RuntimeBeanEntry rootRB = prepareRootRB(Arrays.asList(childRB)); - - Map createdFtls = RuntimeRegistratorFtlTemplate - .create(rootRB); - assertThat(createdFtls.values().size(), is(4)); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/SieASTVisitor.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/SieASTVisitor.java deleted file mode 100644 index 9624239943..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/SieASTVisitor.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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 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()); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/module/AbstractGeneratedObjectTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/module/AbstractGeneratedObjectTest.java deleted file mode 100644 index 34b38bfa50..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/module/AbstractGeneratedObjectTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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)); - } - - -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/module/abs/AbsModuleGeneratedObjectFactoryTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/module/abs/AbsModuleGeneratedObjectFactoryTest.java deleted file mode 100644 index ba9f544e6e..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/module/abs/AbsModuleGeneratedObjectFactoryTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 serviceInterfaceEntryMap = loadThreadsServiceInterfaceEntries("packages.sis"); - Map namesToMBEs = loadThreadsJava(serviceInterfaceEntryMap, "packages.pack2"); - ModuleMXBeanEntry dynamicThreadPool = namesToMBEs.get(THREADPOOL_DYNAMIC_MXB_NAME); - parseGeneratedFile(dynamicThreadPool); - - } - - private void parseGeneratedFile(ModuleMXBeanEntry moduleMXBeanEntry) throws IOException { - Optional copyright = Optional.absent(); - GeneratedObject generatedObject = new AbsModuleGeneratedObjectFactory().toGeneratedObject(moduleMXBeanEntry, copyright); - Entry entry = generatedObject.persist(generatorOutputPath).get(); - - File dstFile = entry.getValue(); - parse(dstFile); - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/module/concrete/ConcreteModuleGeneratedObjectFactoryTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/module/concrete/ConcreteModuleGeneratedObjectFactoryTest.java deleted file mode 100644 index 2a4a91b897..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/module/concrete/ConcreteModuleGeneratedObjectFactoryTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 copyright = Optional.absent(); - Optional header = Optional.absent(); - GeneratedObject go = new ConcreteModuleGeneratedObjectFactory().toGeneratedObject(moduleMXBeanEntry, copyright, header); - Entry 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/StringUtilTest.java b/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/StringUtilTest.java deleted file mode 100644 index 79da0884d2..0000000000 --- a/opendaylight/config/yang-jmx-generator-plugin/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/StringUtilTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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)); - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/pom.xml b/opendaylight/config/yang-jmx-generator/pom.xml deleted file mode 100644 index 17a3715e09..0000000000 --- a/opendaylight/config/yang-jmx-generator/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-subsystem - 0.9.0-SNAPSHOT - ../ - - - yang-jmx-generator - bundle - ${project.artifactId} - - - - ${project.groupId} - config-api - - - com.google.guava - guava - - - org.opendaylight.mdsal - mdsal-binding-generator-impl - - - org.opendaylight.yangtools - yang-model-util - - - - org.opendaylight.yangtools - mockito-configuration - - - org.slf4j - slf4j-api - - - org.apache.commons - commons-lang3 - test - - - org.opendaylight.yangtools - yang-test-util - - - - - - - org.apache.felix - maven-bundle-plugin - - - org.opendaylight.controller.config.yangjmxgenerator.plugin.util, - org.opendaylight.controller.config.yangjmxgenerator, - org.opendaylight.controller.config.yangjmxgenerator.attribute, - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - package - - - - - - diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/AbstractEntry.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/AbstractEntry.java deleted file mode 100644 index c61229a80e..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/AbstractEntry.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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; - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ConfigConstants.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ConfigConstants.java deleted file mode 100644 index f3ef5f1e0b..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ConfigConstants.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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); - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntry.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntry.java deleted file mode 100644 index ebddb4ff81..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntry.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * 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: - *

- *

- * - *
- *  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;
- *                  }
- *              }
- *          }
- *      }
- * }
- * 
- * - *
- */ -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 yangToAttributes; - - private final Map providedServices; - - private Collection runtimeBeans; - private String nullableDummyContainerName; - - ModuleMXBeanEntry(final ModuleMXBeanEntryInitial initials, final Map yangToAttributes, - final Map providedServices2, final Collection 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 getProvidedServices() { - return providedServices; - } - - public void setRuntimeBeans(final Collection newRuntimeBeans) { - runtimeBeans = newRuntimeBeans; - } - - public Collection 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 create( - final Module currentModule, - final Map 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 getAttributes() { - return yangToAttributes; - } - - void setYangToAttributes(final Map 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; - } - - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryBuilder.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryBuilder.java deleted file mode 100644 index 5f8f4e0cbb..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryBuilder.java +++ /dev/null @@ -1,573 +0,0 @@ -/* - * 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 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 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 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 moduleIdentities = getIdentityMap(); - - Map uniqueGeneratedClassesNames = new HashMap<>(); - - // each currentModule name should have an augmentation defined - Map unaugmentedModuleIdentities = new HashMap<>( - moduleIdentities); - - Map result = new HashMap<>(); - - for (AugmentationSchemaNode augmentation : currentModule.getAugmentations()) { - Collection 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 result) { - for (Map.Entry entry : result.entrySet()) { - ModuleMXBeanEntry module = entry.getValue(); - if (module.getAttributes() == null) { - module.setYangToAttributes(Collections - . emptyMap()); - } else if (module.getRuntimeBeans() == null) { - module.setRuntimeBeans(Collections - . emptyList()); - } - } - } - - private static void checkUnaugumentedIdentities(final Map unaugmentedModuleIdentities) { - if (unaugmentedModuleIdentities.size() > 0) { - LOG.warn("Augmentation not found for all currentModule identities: {}", - unaugmentedModuleIdentities.keySet()); - } - } - - private static void checkAttributeNamesUniqueness(final Map uniqueGeneratedClassesNames, - final Map result) { - for (Map.Entry entry : result.entrySet()) { - checkUniqueRuntimeBeanAttributesName(entry.getValue(), - uniqueGeneratedClassesNames); - } - } - - private Map getIdentityMap() { - Map 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 castChildNodesToChoiceCases(final Collection childNodes) { - return Collections2.transform(childNodes, new Function() { - @Nullable - @Override - public CaseSchemaNode apply(@Nullable final DataSchemaNode input) { - return (CaseSchemaNode) input; - } - }); - } - - private static boolean areAllChildrenCaseSchemaNodes(final Iterable childNodes) { - for (DataSchemaNode childNode : childNodes) { - if (childNode instanceof CaseSchemaNode == false) { - return false; - } - } - return true; - } - - private void processCaseSchemaNode( - final Map result, - final Map uniqueGeneratedClassesNames, final String configModulePrefix, - final Map moduleIdentities, - final Map unaugmentedModuleIdentities, - final AugmentationSchemaNode augmentation, final DataSchemaNode when) { - - CaseSchemaNode choiceCaseNode = (CaseSchemaNode) when; - if (!choiceCaseNode.getWhenCondition().isPresent()) { - return; - } - java.util.Optional 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 providedServices = findProvidedServices(moduleIdentity, currentModule, qNamesToSIEs, - schemaContext); - - String javaNamePrefix = TypeProviderWrapper.findJavaNamePrefix(moduleIdentity); - - Map yangToAttributes = null; - // runtime-data - Collection 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 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 uniqueGeneratedClassesNames, - final DataSchemaNode when, final Collection 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 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 uniqueGeneratedClassNames, - final QName parentQName, final Map yangToAttributes) { - for (Map.Entry 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 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 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 getDataNodeContainer(final CaseSchemaNode choiceCaseNode) { - Collection 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 fillConfiguration(final DataNodeContainer dataNodeContainer, final Module currentModule, - final TypeProviderWrapper typeProviderWrapper, final Map qNamesToSIEs, - final SchemaContext schemaContext, final String packageName) { - Map 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 findProvidedServices(final IdentitySchemaNode moduleIdentity, final Module currentModule, - final Map qNamesToSIEs, final SchemaContext schemaContext) { - Map 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 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 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 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 extractDependency(final DataNodeContainer dataNodeContainer, - final DataSchemaNode attrNode, final Module currentModule, final Map 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 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); - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleUtil.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleUtil.java deleted file mode 100644 index 10267b28e7..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleUtil.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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()); - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/PackageTranslator.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/PackageTranslator.java deleted file mode 100644 index f1aaadbc2b..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/PackageTranslator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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 namespacePrefixToPackageMap; - - public PackageTranslator(final Map 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 longestMatch = null; - int longestMatchLength = 0; - final String namespace = module.getNamespace().toString(); - for (final Entry 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntry.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntry.java deleted file mode 100644 index d94c695106..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntry.java +++ /dev/null @@ -1,527 +0,0 @@ -/* - * 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 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 keyYangName, keyJavaName; - private final Map attributeMap; - private final List children; - private final Set rpcs; - - @VisibleForTesting - RuntimeBeanEntry(final String packageName, - final DataNodeContainer nodeForReporting, final String yangName, - final String javaNamePrefix, final boolean isRoot, - final Optional keyYangName, final List attributes, - final List children, final Set 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 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 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 result = new HashMap<>(); - - List attributes; - Set 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 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 getIdentitiesToRpcs( - final SchemaContext schemaCtx) { - Multimap result = HashMultimap.create(); - for (Module currentModule : schemaCtx.getModules()) { - - // Find all identities in current module for later identity->rpc mapping - Set 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 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 identitiesToRpcs = getIdentitiesToRpcs(ctx); - - List attributes = Lists.newArrayList(); - List 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 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 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 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 sortAttributes(final Collection childNodes) { - final TreeSet 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 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 attributes, final String javaNamePrefix, - final List children, final Set rpcs) { - return new RuntimeBeanEntry(packageName, nodeForReporting, - attributeYangName, javaNamePrefix, true, - Optional. absent(), attributes, children, rpcs); - } - - public boolean isRoot() { - return isRoot; - } - - public Optional getKeyYangName() { - return keyYangName; - } - - public Optional getKeyJavaName() { - return keyJavaName; - } - - public Collection getAttributes() { - return attributeMap.values(); - } - - public Map getYangPropertiesToTypesMap() { - return attributeMap; - } - - public String getYangName() { - return yangName; - } - - public String getPackageName() { - return packageName; - } - - public String getJavaNamePrefix() { - return javaNamePrefix; - } - - public List getChildren() { - return children; - } - - public Set getRpcs() { - return rpcs; - } - - private static class AttributesRpcsAndRuntimeBeans { - private final List runtimeBeanEntries; - private final List attributes; - private final Set rpcs; - - public AttributesRpcsAndRuntimeBeans( - final List runtimeBeanEntries, - final List attributes, final Set rpcs) { - this.runtimeBeanEntries = runtimeBeanEntries; - this.attributes = attributes; - this.rpcs = rpcs; - } - - private List getAttributes() { - return attributes; - } - - public List getRuntimeBeanEntries() { - return runtimeBeanEntries; - } - - public boolean isEmpty() { - return attributes.isEmpty() && rpcs.isEmpty(); - } - - private Set getRpcs() { - return rpcs; - } - } - - public static class Rpc { - private final String name; - private final List parameters; - private final AttributeIfc returnType; - private final String yangName; - - Rpc(final AttributeIfc returnType, final String name, final String yangName, - final List 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 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 + '}'; - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntry.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntry.java deleted file mode 100644 index d7a8065680..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntry.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * 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: - *

- *

- * - *
- *  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";
- *  }
- * 
- * - *
- */ -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 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. absent(), id, packageName, yangModuleQName); - } - - private ServiceInterfaceEntry(final Optional base, - final IdentitySchemaNode id, final String packageName, final QName yangModuleQName) { - checkNotNull(base); - this.maybeBaseCache = base; - List unknownSchemaNodes = id.getUnknownSchemaNodes(); - List 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 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 create(final Module currentModule, - final String packageName,final Map definedSEItracker) { - LOG.debug("Generating ServiceInterfaces from {} to package {}", - currentModule.getNamespace(), packageName); - - Map identitiesToSIs = new HashMap<>(); - Set 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 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 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 + '\'' + '}'; - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/TypeProviderWrapper.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/TypeProviderWrapper.java deleted file mode 100644 index e3e29c79cd..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/TypeProviderWrapper.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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); - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/AbstractAttribute.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/AbstractAttribute.java deleted file mode 100644 index 697f022297..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/AbstractAttribute.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/AbstractDependencyAttribute.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/AbstractDependencyAttribute.java deleted file mode 100644 index 205ba893c4..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/AbstractDependencyAttribute.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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 + '}'; - } - - -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/AttributeIfc.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/AttributeIfc.java deleted file mode 100644 index 23985b262e..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/AttributeIfc.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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(); -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/Dependency.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/Dependency.java deleted file mode 100644 index fd07e269f4..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/Dependency.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/DependencyAttribute.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/DependencyAttribute.java deleted file mode 100644 index 5d7f2c1d8e..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/DependencyAttribute.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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; - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/JavaAttribute.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/JavaAttribute.java deleted file mode 100644 index f1c23cb86e..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/JavaAttribute.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * 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 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> 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 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 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); - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/ListAttribute.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/ListAttribute.java deleted file mode 100644 index 10971e7413..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/ListAttribute.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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); - } - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/ListDependenciesAttribute.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/ListDependenciesAttribute.java deleted file mode 100644 index cf79fa185d..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/ListDependenciesAttribute.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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); - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/SimpleTypeResolver.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/SimpleTypeResolver.java deleted file mode 100644 index cb716745b9..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/SimpleTypeResolver.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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> 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); - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/TOAttribute.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/TOAttribute.java deleted file mode 100644 index d9698cc7e2..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/TOAttribute.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * 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 yangNameToAttributeMap; - private final Map attributeNameMap; - private final String packageName; - - private static final Set> 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 TOAttribute create( - final T containerSchemaNode, final TypeProviderWrapper typeProviderWrapper, final String packageName) { - // Transfer Object: get the leaves - final Map map = new HashMap<>(); - final Map 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 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 isAllowedType( - final DataSchemaNode dataSchemaNode) { - for (final Class 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 transferObject, - final Map 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 getAttributeNameMap() { - return this.attributeNameMap; - } - - public Map getCapitalizedPropertiesToTypesMap() { - final Map capitalizedPropertiesToTypesMap = Maps - .newHashMap(); - for (final Entry entry : this.yangNameToAttributeMap - .entrySet()) { - - capitalizedPropertiesToTypesMap.put( - TypeProviderWrapper.convertToJavaName(entry.getKey(), true), - entry.getValue()); - } - return capitalizedPropertiesToTypesMap; - } - - public Map getJmxPropertiesToTypesMap() { - final Map jmxPropertiesToTypesMap = Maps.newHashMap(); - for (final Entry entry : this.yangNameToAttributeMap - .entrySet()) { - - jmxPropertiesToTypesMap.put( - TypeProviderWrapper.convertToJavaName(entry.getKey(), false), - entry.getValue()); - } - return jmxPropertiesToTypesMap; - } - - public Map 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 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, OpenType> { - private final List itemNames = new ArrayList<>(); - - @Override - public OpenType apply(final Entry 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()]); - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/TypedAttribute.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/TypedAttribute.java deleted file mode 100644 index acd373130d..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/TypedAttribute.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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(); - -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/Util.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/Util.java deleted file mode 100644 index 16c4bd1ec5..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/Util.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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); - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/VoidAttribute.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/VoidAttribute.java deleted file mode 100644 index 1e590a5dbe..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/attribute/VoidAttribute.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/FullyQualifiedNameHelper.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/FullyQualifiedNameHelper.java deleted file mode 100644 index 7c3ebb5916..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/FullyQualifiedNameHelper.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/NameConflictException.java b/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/NameConflictException.java deleted file mode 100644 index ec2d985339..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/NameConflictException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/AbstractYangTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/AbstractYangTest.java deleted file mode 100644 index c0e26688a6..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/AbstractYangTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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 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 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 getConfigApiYangs() { - return ImmutableList.of("/META-INF/yang/config@2013-04-05.yang", "/META-INF/yang/rpc-context@2013-06-17.yang"); - } - - public Map mapIdentitiesByQNames(final Module module) { - final Map 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 getStreams(final String... paths) { - final List 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 loadThreadsServiceInterfaceEntries(final String packageName) { - final Map identitiesToSIs = new HashMap<>(); - return ServiceInterfaceEntry.create(this.threadsModule, packageName,identitiesToSIs); - } - - protected Map loadThreadsJava( - final Map modulesToSIEs, final String packageName) { - final Map namesToMBEs = ModuleMXBeanEntry - .create(this.threadsJavaModule, modulesToSIEs, this.context, new TypeProviderWrapper(new TypeProviderImpl - (this.context)), packageName); - Assert.assertNotNull(namesToMBEs); - final Set 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; - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryNameConflictTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryNameConflictTest.java deleted file mode 100644 index 54a980abfa..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryNameConflictTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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 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 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 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()); - } - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryTest.java deleted file mode 100644 index d7fb213bea..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryTest.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * 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 modulesToSIEs; - - - @Before - public void setUp() { - this.modulesToSIEs = loadThreadsServiceInterfaceEntries("packages.sis"); - } - - - protected Map loadThreadsJava() { - return loadThreadsJava(this.modulesToSIEs, PACKAGE_NAME); - } - - @Test - public void test_jmxImplModule() { - final Map identitiesToSIs = new HashMap<>(); - final Map modulesToSIEs = ServiceInterfaceEntry - .create(this.threadsModule, PACKAGE_NAME,identitiesToSIs); - modulesToSIEs.putAll(ServiceInterfaceEntry.create(this.jmxModule, - PACKAGE_NAME,identitiesToSIs)); - final Map namesToMBEs = ModuleMXBeanEntry - .create(this.jmxImplModule, modulesToSIEs, this.context, new TypeProviderWrapper(new TypeProviderImpl(this.context)) - , PACKAGE_NAME); - final Map 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 namesToMBEs, final Map 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 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 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 namesToMBEs = loadThreadsJava(); - - { // check threadpool-dynamic - final ModuleMXBeanEntry dynamicThreadPool = namesToMBEs - .get(THREADPOOL_DYNAMIC_MXB_NAME); - final Map attributes = dynamicThreadPool - .getAttributes(); - // core-size, keepalive, maximum-size - // threadfactory - final Set 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 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 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 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 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 attributes = threadPoolRegistry.getAttributes(); - assertEquals(1, attributes.size()); - final AttributeIfc threadpoolsAttr = attributes.get("threadpools"); - assertNotNull(threadpoolsAttr); - assertTrue(threadpoolsAttr instanceof ListDependenciesAttribute); - final ListDependenciesAttribute threadpools = (ListDependenciesAttribute) threadpoolsAttr; - } - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/PackageTranslatorTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/PackageTranslatorTest.java deleted file mode 100644 index 10c42a890e..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/PackageTranslatorTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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 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)); - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntryTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntryTest.java deleted file mode 100644 index bdacef8efe..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntryTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * 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 identitiesToSIs = new HashMap<>(); - - @Test - public void createRuntimeBean() { - final CaseSchemaNode caseNode = Mockito.mock(CaseSchemaNode.class); - doReturn(new HashSet()).when(caseNode).getChildNodes(); - doReturn(new ArrayList()).when(caseNode) - .getUnknownSchemaNodes(); - final Map 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 modulesToSIEs = ServiceInterfaceEntry - .create(this.threadsModule, "packages.sis",identitiesToSIs); - assertNotNull(modulesToSIEs); - - // create MXBeans map - final Map 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 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 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 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 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 rpcs, final String name) { - if ((rpcs != null) && !rpcs.isEmpty()) { - for (final RuntimeBeanEntry.Rpc rpc : rpcs) { - if (rpc.getName().equals(name)) { - return rpc; - } - } - } - return null; - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeRegistratorTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeRegistratorTest.java deleted file mode 100644 index 8228eb69ea..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeRegistratorTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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 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 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(); - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/SchemaContextTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/SchemaContextTest.java deleted file mode 100644 index 4ed0bc8027..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/SchemaContextTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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 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> expectedIdentitiesToBases = ImmutableMap - .of("eventbus", Optional.absent(), "threadfactory", Optional.absent(), "threadpool", - Optional.absent(), "scheduled-threadpool", Optional.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 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> expectedIdentitiesToBases) { - Map> copyOfExpectedNames = new HashMap<>( - expectedIdentitiesToBases); - for (IdentitySchemaNode id : module.getIdentities()) { - String localName = id.getQName().getLocalName(); - assertTrue("Unexpected identity " + localName, - copyOfExpectedNames.containsKey(localName)); - Optional 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> 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.absent()); - expected.put(ModuleMXBeanEntryTest.THREADPOOL_REGISTRY_IMPL_NAME, Optional.of(MODULE_TYPE_Q_NAME)); - - assertAllIdentitiesAreExpected(threadsJavaModule, expected); - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntryTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntryTest.java deleted file mode 100644 index 04bd7e79c8..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntryTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * 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 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 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 definedIdentities = new HashMap<>(); - Map namesToSIEntries = ServiceInterfaceEntry - .create(threadsModule, PACKAGE_NAME,definedIdentities); - // expected eventbus, threadfactory, threadpool, - // scheduled-threadpool,thread-rpc-context - assertThat(namesToSIEntries.size(), is(expectedSIEFileNames.size())); - - Set withNoBaseType = Sets.newHashSet(EVENTBUS_QNAME, - THREADFACTORY_QNAME, THREADPOOL_QNAME, - SCHEDULED_EXECUTOR_SERVICE_QNAME); - HashSet withBaseType = new HashSet<>(); - for (Entry 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,}", " "); - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/YangModelSearchUtils.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/YangModelSearchUtils.java deleted file mode 100644 index ce70c9a82b..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/util/YangModelSearchUtils.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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 mapModulesByNames( - Collection modules) { - Map 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; - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/unknownextension/UnknownExtensionTest.java b/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/unknownextension/UnknownExtensionTest.java deleted file mode 100644 index 5daaf0f72e..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/unknownextension/UnknownExtensionTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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 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.")); - } - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/config-bgp-listener-impl.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/config-bgp-listener-impl.yang deleted file mode 100644 index 0a011b772c..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/config-bgp-listener-impl.yang +++ /dev/null @@ -1,45 +0,0 @@ -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; - } - } - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/config-jmx-it-impl.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/config-jmx-it-impl.yang deleted file mode 100644 index b9388c64f3..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/config-jmx-it-impl.yang +++ /dev/null @@ -1,219 +0,0 @@ -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; - } - - } - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/config-jmx-it.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/config-jmx-it.yang deleted file mode 100644 index e2b45b84aa..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/config-jmx-it.yang +++ /dev/null @@ -1,26 +0,0 @@ -// 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"; - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute-in-list.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute-in-list.yang deleted file mode 100644 index ed1f5d62f1..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute-in-list.yang +++ /dev/null @@ -1,84 +0,0 @@ -// 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; - } - - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute-in-runtime-and-mxbean.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute-in-runtime-and-mxbean.yang deleted file mode 100644 index 4f18961eec..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute-in-runtime-and-mxbean.yang +++ /dev/null @@ -1,57 +0,0 @@ -// 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; - } - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute-runtime-bean.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute-runtime-bean.yang deleted file mode 100644 index 8703185d78..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute-runtime-bean.yang +++ /dev/null @@ -1,63 +0,0 @@ -// 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; - } - } - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute.yang deleted file mode 100644 index 8f9116044a..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-duplicate-attribute.yang +++ /dev/null @@ -1,81 +0,0 @@ -// 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; - } - - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-generated-attributes-name-conflict.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-generated-attributes-name-conflict.yang deleted file mode 100644 index 2b46046615..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-generated-attributes-name-conflict.yang +++ /dev/null @@ -1,69 +0,0 @@ -// 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; - } - } - } - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-list-name-conflict.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-list-name-conflict.yang deleted file mode 100644 index 790f0cc866..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-list-name-conflict.yang +++ /dev/null @@ -1,57 +0,0 @@ -// 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; - } - } - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-list-name-conflict2.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-list-name-conflict2.yang deleted file mode 100644 index 45672ec766..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-list-name-conflict2.yang +++ /dev/null @@ -1,57 +0,0 @@ -// 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; - } - } - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-name-conflict.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-name-conflict.yang deleted file mode 100644 index 896eb27782..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-name-conflict.yang +++ /dev/null @@ -1,59 +0,0 @@ -// 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; - } - } - } - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-name-conflict2.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-name-conflict2.yang deleted file mode 100644 index 8be30e1c51..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/duplicates/config-test-runtime-bean-name-conflict2.yang +++ /dev/null @@ -1,77 +0,0 @@ -// 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; - } - - } - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/ietf-inet-types.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/ietf-inet-types.yang deleted file mode 100644 index 5c6f139a27..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/ietf-inet-types.yang +++ /dev/null @@ -1,457 +0,0 @@ -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: - WG List: - - WG Chair: David Kessens - - - WG Chair: Juergen Schoenwaelder - - - Editor: Juergen Schoenwaelder - "; - - 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 . - - 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)"; - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/org/opendaylight/controller/config/yangjmxgenerator/unknownextension/test-ifcWithUnknownExtension.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/org/opendaylight/controller/config/yangjmxgenerator/unknownextension/test-ifcWithUnknownExtension.yang deleted file mode 100644 index e027177837..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/org/opendaylight/controller/config/yangjmxgenerator/unknownextension/test-ifcWithUnknownExtension.yang +++ /dev/null @@ -1,32 +0,0 @@ -// 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"; - } - -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-files.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-files.yang deleted file mode 100644 index 4ad5b74fe9..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-files.yang +++ /dev/null @@ -1,71 +0,0 @@ -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; - } - - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-files1.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-files1.yang deleted file mode 100644 index ac34088347..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-files1.yang +++ /dev/null @@ -1,71 +0,0 @@ -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; - } - - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-threads-java.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-threads-java.yang deleted file mode 100644 index a6d2feaf04..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-threads-java.yang +++ /dev/null @@ -1,279 +0,0 @@ -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; - } - } - } - } - } -} diff --git a/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-threads.yang b/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-threads.yang deleted file mode 100644 index ff4c426063..0000000000 --- a/opendaylight/config/yang-jmx-generator/src/test/resources/test-config-threads.yang +++ /dev/null @@ -1,63 +0,0 @@ -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"; - } -} diff --git a/opendaylight/config/yang-test-plugin/pom.xml b/opendaylight/config/yang-test-plugin/pom.xml deleted file mode 100644 index b3d6241176..0000000000 --- a/opendaylight/config/yang-test-plugin/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - config-plugin-parent - 0.9.0-SNAPSHOT - ../config-plugin-parent - - yang-test-plugin - maven-plugin - ${project.artifactId} - - Remove generated source files, after new files generation, implementation is inserted. - - - - com.google.guava - guava - - - org.apache.maven - maven-plugin-api - 3.3.3 - - - diff --git a/opendaylight/config/yang-test-plugin/src/main/java/org/opendaylight/controller/config/yang/test/plugin/DeleteSources.java b/opendaylight/config/yang-test-plugin/src/main/java/org/opendaylight/controller/config/yang/test/plugin/DeleteSources.java deleted file mode 100644 index 29b37af794..0000000000 --- a/opendaylight/config/yang-test-plugin/src/main/java/org/opendaylight/controller/config/yang/test/plugin/DeleteSources.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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(); - } - } - } -} diff --git a/opendaylight/config/yang-test-plugin/src/main/java/org/opendaylight/controller/config/yang/test/plugin/ProcessSources.java b/opendaylight/config/yang-test-plugin/src/main/java/org/opendaylight/controller/config/yang/test/plugin/ProcessSources.java deleted file mode 100644 index 054edffe68..0000000000 --- a/opendaylight/config/yang-test-plugin/src/main/java/org/opendaylight/controller/config/yang/test/plugin/ProcessSources.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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; - } -} diff --git a/opendaylight/config/yang-test-plugin/src/main/java/org/opendaylight/controller/config/yang/test/plugin/Util.java b/opendaylight/config/yang-test-plugin/src/main/java/org/opendaylight/controller/config/yang/test/plugin/Util.java deleted file mode 100644 index 136733cbff..0000000000 --- a/opendaylight/config/yang-test-plugin/src/main/java/org/opendaylight/controller/config/yang/test/plugin/Util.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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; - } -}