Merge "Bug 6635: Correct WriteRunningTx behavior"
authorTomas Cere <tcere@cisco.com>
Tue, 4 Oct 2016 11:58:28 +0000 (11:58 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Tue, 4 Oct 2016 11:58:28 +0000 (11:58 +0000)
19 files changed:
features/netconf-connector/src/main/features/features.xml
netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModuleFactory.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Main.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TesttoolParameters.java
restconf/sal-rest-connector/src/main/java/org/opendaylight/netconf/sal/rest/impl/StringModuleInstanceIdentifierCodec.java
restconf/sal-rest-connector/src/main/java/org/opendaylight/netconf/sal/rest/impl/XmlNormalizedNodeBodyReader.java
restconf/sal-rest-connector/src/main/java/org/opendaylight/netconf/sal/restconf/impl/RestCodec.java
restconf/sal-rest-connector/src/main/java/org/opendaylight/restconf/restful/utils/PatchDataTransactionUtil.java
restconf/sal-rest-connector/src/main/java/org/opendaylight/restconf/utils/patch/Draft16StringModuleInstanceIdentifierCodec.java
restconf/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/rest/impl/InstanceIdentifierTypeLeafTest.java [new file with mode: 0644]
restconf/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyReader.java
restconf/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/rest/impl/test/providers/TestXmlBodyReaderMountPoint.java
restconf/sal-rest-connector/src/test/java/org/opendaylight/restconf/restful/utils/PatchDataTransactionUtilTest.java [new file with mode: 0644]
restconf/sal-rest-connector/src/test/resources/instanceidentifier/iid-value.yang [new file with mode: 0644]
restconf/sal-rest-connector/src/test/resources/instanceidentifier/xml/xmlDataFindBarContainer.xml [new file with mode: 0644]
restconf/sal-rest-connector/src/test/resources/instanceidentifier/xml/xmlDataFindFooContainer.xml [new file with mode: 0644]
restconf/sal-rest-connector/src/test/resources/instanceidentifier/yang/bar-module.yang [new file with mode: 0644]
restconf/sal-rest-connector/src/test/resources/instanceidentifier/yang/foo-module.yang [new file with mode: 0644]

index 6253a326bb440771e60c33680a8ac07b52944e00..fe3e66dba3ced96accabdbc0f98c5b10115d1d8a 100644 (file)
@@ -45,8 +45,7 @@
     </feature>
 
     <feature name='odl-netconf-connector-ssh' version='${project.version}' description="OpenDaylight :: Netconf Connector :: Netconf Connector + Netconf SSH Server + loopback connection configuration">
-        <feature version='${project.version}'>odl-netconf-ssh</feature>
-        <feature version='${project.version}'>odl-netconf-connector</feature>
+        <feature version='${project.version}'>odl-netconf-topology</feature>
         <configfile finalname="${config.configfile.directory}/${config.netconf.connector.configfile}">mvn:org.opendaylight.netconf/netconf-connector-config/{{VERSION}}/xml/config</configfile>
     </feature>
 
index 6ca1436e952cc1b63f55c7c0b60bc8b98e169857..34f86655964933f13f7db2d1b6235cf93802753e 100644 (file)
  */
 package org.opendaylight.controller.config.yang.md.sal.connector.netconf;
 
-import static com.google.common.base.Preconditions.checkArgument;
 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkCondition;
 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkNotNull;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Strings;
-import com.google.common.collect.Lists;
-import io.netty.util.concurrent.EventExecutor;
-import java.io.File;
-import java.math.BigDecimal;
-import java.net.InetSocketAddress;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ThreadFactory;
-import org.opendaylight.controller.config.api.JmxAttributeValidationException;
-import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
-import org.opendaylight.controller.config.threadpool.ThreadPool;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import javax.annotation.Nullable;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
-import org.opendaylight.netconf.client.NetconfClientDispatcher;
-import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
-import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
-import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
-import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
-import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
-import org.opendaylight.netconf.sal.connect.netconf.LibraryModulesSchemas;
-import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
-import org.opendaylight.netconf.sal.connect.netconf.NetconfDeviceBuilder;
-import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemasResolverImpl;
-import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
-import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
-import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
-import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
-import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceSalFacade;
-import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
-import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
-import org.opendaylight.protocol.framework.ReconnectStrategy;
-import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
-import org.opendaylight.protocol.framework.TimedReconnectStrategy;
+import org.opendaylight.controller.sal.binding.api.BindingAwareConsumer;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
-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.PotentialSchemaSource;
-import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
-import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
-import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
-import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
-import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
-import org.osgi.framework.BundleContext;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
  *
  */
-public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
-{
+public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule implements BindingAwareConsumer {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class);
 
-    /**
-     * Filesystem based caches are stored relative to the cache directory.
-     */
-    private static final String CACHE_DIRECTORY = "cache";
-
-    /**
-     * The default cache directory relative to <code>CACHE_DIRECTORY</code>
-     */
-    private static final String DEFAULT_CACHE_DIRECTORY = "schema";
-
-    /**
-     * The qualified schema cache directory <code>cache/schema</code>
-     */
-    private static final String QUALIFIED_DEFAULT_CACHE_DIRECTORY = CACHE_DIRECTORY + File.separator+ DEFAULT_CACHE_DIRECTORY;
-
-    /**
-     * The name for the default schema repository
-     */
-    private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector";
-
-    /**
-     * The default schema repository in the case that one is not specified.
-     */
-    private static final SharedSchemaRepository DEFAULT_SCHEMA_REPOSITORY =
-            new SharedSchemaRepository(DEFAULT_SCHEMA_REPOSITORY_NAME);
-
-    /**
-     * The default <code>FilesystemSchemaSourceCache</code>, which stores cached files in <code>cache/schema</code>.
-     */
-    private static final FilesystemSchemaSourceCache<YangTextSchemaSource> DEFAULT_CACHE =
-            new FilesystemSchemaSourceCache<>(DEFAULT_SCHEMA_REPOSITORY, YangTextSchemaSource.class,
-                    new File(QUALIFIED_DEFAULT_CACHE_DIRECTORY));
-
-    /**
-     * The default factory for creating <code>SchemaContext</code> instances.
-     */
-    private static final SchemaContextFactory DEFAULT_SCHEMA_CONTEXT_FACTORY =
-            DEFAULT_SCHEMA_REPOSITORY.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
-
-    private static final int LOCAL_IO_FALLBACK_COST = PotentialSchemaSource.Costs.LOCAL_IO.getValue() + 1;
-
-    /**
-     * Keeps track of initialized Schema resources.  A Map is maintained in which the key represents the name
-     * of the schema cache directory, and the value is a corresponding <code>SchemaResourcesDTO</code>.  The
-     * <code>SchemaResourcesDTO</code> is essentially a container that allows for the extraction of the
-     * <code>SchemaRegistry</code> and <code>SchemaContextFactory</code> which should be used for a particular
-     * Netconf mount.  Access to <code>schemaResourcesDTOs</code> should be surrounded by appropriate
-     * synchronization locks.
-     */
-    private static volatile Map<String, NetconfDevice.SchemaResourcesDTO> schemaResourcesDTOs = new HashMap<>();
-
-    // Initializes default constant instances for the case when the default schema repository
-    // directory cache/schema is used.
-    static {
-        schemaResourcesDTOs.put(DEFAULT_CACHE_DIRECTORY,
-                new NetconfDevice.SchemaResourcesDTO(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY,
-                        DEFAULT_SCHEMA_CONTEXT_FACTORY,
-                        new NetconfStateSchemasResolverImpl()));
-        DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(DEFAULT_CACHE);
-        DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(
-                TextToASTTransformer.create(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY));
-    }
-
-    private BundleContext bundleContext;
-    private Optional<NetconfSessionPreferences> userCapabilities;
-    private SchemaSourceRegistry schemaRegistry = DEFAULT_SCHEMA_REPOSITORY;
-    private SchemaRepository schemaRepository = DEFAULT_SCHEMA_REPOSITORY;
-    private SchemaContextFactory schemaContextFactory = DEFAULT_SCHEMA_CONTEXT_FACTORY;
-
-    private Broker domRegistry;
-    private NetconfClientDispatcher clientDispatcher;
-    private BindingAwareBroker bindingRegistry;
-    private ThreadPool processingExecutor;
-    private ScheduledThreadPool keepaliveExecutor;
-    private EventExecutor eventExecutor;
-
-    /**
-     * The name associated with the Netconf mount point.  This value is passed from <code>NetconfConnectorModuleFactory</code>.
-     */
-    private String instanceName;
+    private static final InstanceIdentifier<Topology> TOPOLOGY_PATH = InstanceIdentifier.create(NetworkTopology.class)
+            .child(Topology.class, new TopologyKey(new TopologyId("topology-netconf")));
+    private final String instanceName;
+    private InstanceIdentifier<Node> nodePath;
+    private DataBroker dataBroker;
 
     public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(identifier, dependencyResolver);
+        instanceName = identifier.getInstanceName();
     }
 
     public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
         super(identifier, dependencyResolver, oldModule, oldInstance);
+        instanceName = identifier.getInstanceName();
     }
 
     @Override
@@ -182,12 +75,10 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
 
         // Check username + password in case of ssh
-        if(getTcpOnly() == false) {
+        if (!getTcpOnly()) {
             checkNotNull(getUsername(), usernameJmxAttribute);
             checkNotNull(getPassword(), passwordJmxAttribute);
         }
-
-        userCapabilities = getUserCapabilities();
     }
 
     private boolean isHostAddressPresent(final Host address) {
@@ -195,299 +86,79 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
                address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
     }
 
-    @Deprecated
-    private static ScheduledExecutorService DEFAULT_KEEPALIVE_EXECUTOR;
-
     @Override
     public java.lang.AutoCloseable createInstance() {
-        initDependencies();
-        final RemoteDeviceId id = new RemoteDeviceId(getIdentifier(), getSocketAddress());
-
-        final ExecutorService globalProcessingExecutor = processingExecutor.getExecutor();
-
-        RemoteDeviceHandler<NetconfSessionPreferences> salFacade
-                = new NetconfDeviceSalFacade(id, domRegistry, bindingRegistry);
-
-        final Long keepaliveDelay = getKeepaliveDelay();
-        if (shouldSendKeepalive()) {
-            // Keepalive executor is optional for now and a default instance is supported
-            final ScheduledExecutorService executor = keepaliveExecutor == null ? DEFAULT_KEEPALIVE_EXECUTOR : keepaliveExecutor.getExecutor();
-
-            salFacade = new KeepaliveSalFacade(id, salFacade, executor, keepaliveDelay, getDefaultRequestTimeoutMillis());
-        }
-
-        // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
-        NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
-        final String moduleSchemaCacheDirectory = getSchemaCacheDirectory();
-        // Only checks to ensure the String is not empty or null;  further checks related to directory accessibility and file permissions
-        // are handled during the FilesystemSchemaSourceCache initialization.
-        if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
-            // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry and
-            // SchemaContextFactory remain the default values.
-            if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
-                // Multiple modules may be created at once;  synchronize to avoid issues with data consistency among threads.
-                synchronized(schemaResourcesDTOs) {
-                    // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if they already exist
-                    final NetconfDevice.SchemaResourcesDTO dto =
-                            schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
-                    if (dto == null) {
-                        schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
-                        schemaRegistry.registerSchemaSourceListener(
-                                TextToASTTransformer.create((SchemaRepository) schemaRegistry, schemaRegistry));
-                        schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
-                    } else {
-                        setSchemaContextFactory(dto.getSchemaContextFactory());
-                        setSchemaRegistry(dto.getSchemaRegistry());
-                        schemaResourcesDTO = dto;
-                    }
-                    if (userCapabilities.isPresent()) {
-                        for (QName qname : userCapabilities.get().getModuleBasedCaps()) {
-                            final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier
-                                    .create(qname.getLocalName(), qname.getFormattedRevision());
-                            dto.getSchemaRegistry().registerSchemaSource(DEFAULT_CACHE, PotentialSchemaSource
-                                    .create(sourceIdentifier, YangTextSchemaSource.class, LOCAL_IO_FALLBACK_COST));
-                        }
-                    }
-                }
-                LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
-                        instanceName, moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
-            }
-        } else {
-            LOG.warn("schema-cache-directory for {} is null or empty;  using the default {}",
-                    instanceName, QUALIFIED_DEFAULT_CACHE_DIRECTORY);
-        }
-
-        // pre register yang library sources as fallback schemas to schema registry
-        List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
-        if (getYangLibrary() != null) {
-            final String yangLibURL = getYangLibrary().getYangLibraryUrl().getValue();
-            final String yangLibUsername = getYangLibrary().getUsername();
-            final String yangLigPassword = getYangLibrary().getPassword();
-
-            LibraryModulesSchemas libraryModulesSchemas;
-            if(yangLibURL != null) {
-                if(yangLibUsername != null && yangLigPassword != null) {
-                    libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
-                } else {
-                    libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
-                }
-
-                for (Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry : libraryModulesSchemas.getAvailableModels().entrySet()) {
-                    registeredYangLibSources.
-                            add(schemaRegistry.registerSchemaSource(
-                                    new YangLibrarySchemaYangSourceProvider(id, libraryModulesSchemas.getAvailableModels()),
-                                    PotentialSchemaSource
-                                            .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
-                                                    PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
-                }
-            }
-        }
-
-        if (schemaResourcesDTO == null) {
-            schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaRepository, schemaContextFactory,
-                    new NetconfStateSchemasResolverImpl());
-        }
-
-        final NetconfDevice device = new NetconfDeviceBuilder()
-                .setReconnectOnSchemasChange(getReconnectOnChangedSchema())
-                .setSchemaResourcesDTO(schemaResourcesDTO)
-                .setGlobalProcessingExecutor(globalProcessingExecutor)
-                .setId(id)
-                .setSalFacade(salFacade)
-                .build();
-
-        if (getConcurrentRpcLimit() < 1) {
-            LOG.info("Concurrent rpc limit is smaller than 1, no limit will be enforced for device {}", id);
-        }
-
-        final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
-                new NetconfDeviceCommunicator(id, device,
-                        new UserPreferences(userCapabilities.get(), getYangModuleCapabilities().getOverride()), getConcurrentRpcLimit()):
-                new NetconfDeviceCommunicator(id, device, getConcurrentRpcLimit());
-
-        if (shouldSendKeepalive()) {
-            ((KeepaliveSalFacade) salFacade).setListener(listener);
-        }
-
-        final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
-        listener.initializeRemoteConnection(clientDispatcher, clientConfig);
-
-        return new SalConnectorCloseable(listener, salFacade, registeredYangLibSources);
-    }
-
-    /**
-     * Creates the backing Schema classes for a particular directory.
-     *
-     * @param moduleSchemaCacheDirectory The string directory relative to "cache"
-     * @return A DTO containing the Schema classes for the Netconf mount.
-     */
-    private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) {
-        final SharedSchemaRepository repository = new SharedSchemaRepository(instanceName);
-        final SchemaContextFactory schemaContextFactory
-                = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
-        setSchemaRegistry(repository);
-        setSchemaContextFactory(schemaContextFactory);
-        final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
-                createDeviceFilesystemCache(moduleSchemaCacheDirectory);
-        repository.registerSchemaSourceListener(deviceCache);
-        return new NetconfDevice.SchemaResourcesDTO(repository, repository, schemaContextFactory,
-                new NetconfStateSchemasResolverImpl());
-    }
-
-    /**
-     * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
-     *
-     * @param schemaCacheDirectory The custom cache directory relative to "cache"
-     * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
-     */
-    private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
-        final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
-        return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
-    }
-
-    private void initDependencies() {
-        domRegistry = getDomRegistryDependency();
-        clientDispatcher = getClientDispatcherDependency();
-        bindingRegistry = getBindingRegistryDependency();
-        processingExecutor = getProcessingExecutorDependency();
-        eventExecutor = getEventExecutorDependency();
-
-        if(getKeepaliveExecutor() == null) {
-            LOG.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
-
-            // Instantiate the default executor, now we know its necessary
-            if(DEFAULT_KEEPALIVE_EXECUTOR == null) {
-                DEFAULT_KEEPALIVE_EXECUTOR = Executors.newScheduledThreadPool(2, new ThreadFactory() {
-                    @Override
-                    public Thread newThread(final Runnable r) {
-                        final Thread thread = new Thread(r);
-                        thread.setName("netconf-southound-keepalives-" + thread.getId());
-                        thread.setDaemon(true);
-                        return thread;
-                    }
-                });
-            }
-        } else {
-            keepaliveExecutor = getKeepaliveExecutorDependency();
-        }
-    }
-
-    private boolean shouldSendKeepalive() {
-        return getKeepaliveDelay() > 0;
-    }
-
-    private Optional<NetconfSessionPreferences> getUserCapabilities() {
-        if(getYangModuleCapabilities() == null) {
-            return Optional.absent();
-        }
-
-        final List<String> capabilities = getYangModuleCapabilities().getCapability();
-        if(capabilities == null || capabilities.isEmpty()) {
-            return Optional.absent();
-        }
-
-        final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
-        JmxAttributeValidationException.checkCondition(
-                parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
-                "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
-                        " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
-                yangModuleCapabilitiesJmxAttribute);
-
-        return Optional.of(parsedOverrideCapabilities);
-    }
-
-    public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
-        final InetSocketAddress socketAddress = getSocketAddress();
-        final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
-
-        final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
-                getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor());
-        final ReconnectStrategy strategy = sf.createReconnectStrategy();
-
-        return NetconfReconnectingClientConfigurationBuilder.create()
-        .withAddress(socketAddress)
-        .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
-        .withReconnectStrategy(strategy)
-        .withAuthHandler(new LoginPassword(getUsername(), getPassword()))
-        .withProtocol(getTcpOnly() ?
-                NetconfClientConfiguration.NetconfClientProtocol.TCP :
-                NetconfClientConfiguration.NetconfClientProtocol.SSH)
-        .withConnectStrategyFactory(sf)
-        .withSessionListener(listener)
-        .build();
+        getBindingRegistryDependency().registerConsumer(this);
+        return this::deleteNode;
     }
 
-    private static final class SalConnectorCloseable implements AutoCloseable {
-        private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
-        private final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources;
-        private final NetconfDeviceCommunicator listener;
-
-        public SalConnectorCloseable(final NetconfDeviceCommunicator listener,
-                                     final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
-                                     final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources) {
-            this.listener = listener;
-            this.salFacade = salFacade;
-            this.registeredYangLibSources = registeredYangLibSources;
-        }
-
-        @Override
-        public void close() {
-            for (SchemaSourceRegistration<YangTextSchemaSource> registeredYangLibSource : registeredYangLibSources) {
-                registeredYangLibSource.close();
+    @Override
+    public void onSessionInitialized(final BindingAwareBroker.ConsumerContext session) {
+        dataBroker = session.getSALService(DataBroker.class);
+        final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
+        final NodeId nodeId = new NodeId(instanceName);
+        final NodeKey nodeKey = new NodeKey(nodeId);
+        final Node node = createrNetconfNode(nodeId, nodeKey);
+        nodePath = TOPOLOGY_PATH.child(Node.class, nodeKey);
+        transaction.put(LogicalDatastoreType.CONFIGURATION, nodePath, node);
+        final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = transaction.submit();
+        Futures.addCallback(submitFuture, new FutureCallback<Void>() {
+            @Override
+            public void onSuccess(@Nullable final Void result) {
+                LOG.debug("Node {} was successfully added to the topology", instanceName);
             }
-            listener.close();
-            salFacade.close();
-        }
-    }
 
-    private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
-        private final Long connectionAttempts;
-        private final EventExecutor executor;
-        private final double sleepFactor;
-        private final int minSleep;
-
-        TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
-            if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
-                connectionAttempts = maxConnectionAttempts;
-            } else {
-                LOG.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
-                connectionAttempts = null;
+            @Override
+            public void onFailure(final Throwable t) {
+                LOG.error("Node {} creation failed: {}", instanceName, t);
             }
+        });
+    }
+
+    private void deleteNode() {
+        if (dataBroker != null) {
+            final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
+            transaction.delete(LogicalDatastoreType.CONFIGURATION, nodePath);
+            final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = transaction.submit();
+            Futures.addCallback(submitFuture, new FutureCallback<Void>() {
+                @Override
+                public void onSuccess(@Nullable final Void result) {
+                    LOG.debug("Node {} was successfully deleted from the topology", instanceName);
+                }
 
-            this.sleepFactor = sleepFactor.doubleValue();
-            this.executor = executor;
-            this.minSleep = minSleep;
-        }
-
-        @Override
-        public ReconnectStrategy createReconnectStrategy() {
-            final Long maxSleep = null;
-            final Long deadline = null;
-
-            return new TimedReconnectStrategy(executor, minSleep,
-                    minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
-        }
-    }
+                @Override
+                public void onFailure(final Throwable t) {
+                    LOG.error("Node {} deletion failed: {}", instanceName, t);
+                }
+            });
 
-    private InetSocketAddress getSocketAddress() {
-        if(getAddress().getDomainName() != null) {
-            return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
-        } else {
-            final IpAddress ipAddress = getAddress().getIpAddress();
-            final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
-            return new InetSocketAddress(ip, getPort().getValue());
         }
     }
 
-    public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
-        this.schemaRegistry = schemaRegistry;
-    }
-
-    public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
-        this.schemaContextFactory = schemaContextFactory;
-    }
-
-    public void setInstanceName(final String instanceName) {
-        this.instanceName = instanceName;
+    private Node createrNetconfNode(final NodeId nodeId, final NodeKey nodeKey) {
+        final Credentials credentials = new LoginPasswordBuilder()
+                .setUsername(getUsername())
+                .setPassword(getPassword())
+                .build();
+        final NetconfNode netconfNode = new NetconfNodeBuilder()
+                .setHost(getAddress())
+                .setPort(getPort())
+                .setCredentials(credentials)
+                .setConnectionTimeoutMillis(getConnectionTimeoutMillis())
+                .setDefaultRequestTimeoutMillis(getDefaultRequestTimeoutMillis())
+                .setBetweenAttemptsTimeoutMillis(getBetweenAttemptsTimeoutMillis())
+                .setConcurrentRpcLimit(getConcurrentRpcLimit())
+                .setKeepaliveDelay(getKeepaliveDelay())
+                .setMaxConnectionAttempts(getMaxConnectionAttempts())
+                .setReconnectOnChangedSchema(getReconnectOnChangedSchema())
+                .setSchemaCacheDirectory(getSchemaCacheDirectory())
+                .setSleepFactor(getSleepFactor())
+                .setTcpOnly(getTcpOnly())
+                .build();
+        return new NodeBuilder()
+                .setNodeId(nodeId)
+                .setKey(nodeKey)
+                .addAugmentation(NetconfNode.class, netconfNode)
+                .build();
     }
 }
index 4132e1cd89a74078e9f31a95f4699ab694a79f55..2b31fe05d0e8bba5aea24b984ea62ae287de4b62 100644 (file)
@@ -23,7 +23,6 @@ public class NetconfConnectorModuleFactory extends
             final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
         final NetconfConnectorModule module = (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver,
                 old, bundleContext);
-        module.setInstanceName(instanceName);
         return module;
     }
 
@@ -31,7 +30,6 @@ public class NetconfConnectorModuleFactory extends
     public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
         final NetconfConnectorModule module = (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver,
                 bundleContext);
-        module.setInstanceName(instanceName);
         return module;
     }
 }
index 3ac9c46717a87d21fa08f902eb5d19886d0c8631..66ad61abff3e633673e13722e5b042253cd44867 100644 (file)
@@ -20,7 +20,6 @@ import com.google.common.io.Files;
 import java.io.File;
 import java.io.FileFilter;
 import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.InputStream;
index cc53aa5e218099da101d7a711aedf484f8c5f576..79e849a32428e5046f1d6173a717cf5bc1bffa90 100644 (file)
@@ -13,15 +13,19 @@ import static com.google.common.base.Preconditions.checkArgument;
 import com.google.common.base.Preconditions;
 import com.google.common.io.CharStreams;
 import com.google.common.io.Files;
+import java.io.BufferedReader;
 import java.io.File;
+import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Iterator;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import net.sourceforge.argparse4j.ArgumentParsers;
 import net.sourceforge.argparse4j.annotation.Arg;
@@ -35,6 +39,8 @@ public class TesttoolParameters {
     private static final String TCP_ONLY = "{TCP_ONLY}";
     private static final String ADDRESS_PORT = "{ADDRESS:PORT}";
     private static final String dest = "http://{ADDRESS:PORT}/restconf/config/network-topology:network-topology/topology/topology-netconf/";
+    private static final Pattern YANG_FILENAME_PATTERN = Pattern.compile("(?<name>.*)@(?<revision>\\d{4}-\\d{2}-\\d{2})\\.yang");
+    private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
 
     private static final String RESOURCE = "/config-template.json";
     @Arg(dest = "edit-content")
@@ -284,6 +290,36 @@ public class TesttoolParameters {
             checkArgument(schemasDir.exists(), "Schemas dir has to exist");
             checkArgument(schemasDir.isDirectory(), "Schemas dir has to be a directory");
             checkArgument(schemasDir.canRead(), "Schemas dir has to be readable");
+
+            final List<File> files = Arrays.asList(schemasDir.listFiles());
+            for (final File file : files) {
+                final Matcher matcher = YANG_FILENAME_PATTERN.matcher(file.getName());
+                if (!matcher.matches()) {
+                    BufferedReader reader;
+                    try {
+                        reader = new BufferedReader(new FileReader(file));
+                        String line = reader.readLine();
+                        while (!DATE_PATTERN.matcher(line).find()) {
+                            line = reader.readLine();
+                        }
+                        Matcher m = DATE_PATTERN.matcher(line);
+
+                        if (m.find()) {
+                            String moduleName = file.getAbsolutePath();
+                            if (file.getName().endsWith(".yang")) {
+                                moduleName = moduleName.substring(0, moduleName.length() - 5);
+                            }
+                            final String revision = m.group(1);
+                            String correctName = moduleName + "@" + revision + ".yang";
+                            File correctNameFile = new File(correctName);
+                            file.renameTo(correctNameFile);
+                        }
+
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    }
+                }
+            }
         }
     }
 
index a265ea95a212b40c6dc4bcd5698fb2de57e5c372..77489dec72694c138b0ed0b7e3e6531aee3f103e 100644 (file)
@@ -12,6 +12,7 @@ import com.google.common.base.Preconditions;
 import java.net.URI;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
+import org.opendaylight.restconf.utils.patch.Draft16StringModuleInstanceIdentifierCodec;
 import org.opendaylight.yangtools.yang.data.util.AbstractModuleStringInstanceIdentifierCodec;
 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
 import org.opendaylight.yangtools.yang.model.api.Module;
@@ -19,29 +20,29 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
 /**
  * @deprecated This class will be replaced by
- * {@link org.opendaylight.restconf.utils.patch.Draft11StringModuleInstanceIdentifierCodec}
+ *             {@link Draft16StringModuleInstanceIdentifierCodec}
  */
 @Deprecated
-final class StringModuleInstanceIdentifierCodec extends AbstractModuleStringInstanceIdentifierCodec {
+public final class StringModuleInstanceIdentifierCodec extends AbstractModuleStringInstanceIdentifierCodec {
 
     private final DataSchemaContextTree dataContextTree;
     private final SchemaContext context;
     private final String defaultPrefix;
 
-    StringModuleInstanceIdentifierCodec(SchemaContext context) {
+    public StringModuleInstanceIdentifierCodec(final SchemaContext context) {
         this.context = Preconditions.checkNotNull(context);
         this.dataContextTree = DataSchemaContextTree.from(context);
         this.defaultPrefix = "";
     }
 
-    StringModuleInstanceIdentifierCodec(SchemaContext context, @Nonnull String defaultPrefix) {
+    StringModuleInstanceIdentifierCodec(final SchemaContext context, @Nonnull final String defaultPrefix) {
         this.context = Preconditions.checkNotNull(context);
         this.dataContextTree = DataSchemaContextTree.from(context);
         this.defaultPrefix = defaultPrefix;
     }
 
     @Override
-    protected Module moduleForPrefix(@Nonnull String prefix) {
+    protected Module moduleForPrefix(@Nonnull final String prefix) {
         if (prefix.isEmpty() && !this.defaultPrefix.isEmpty()) {
             return this.context.findModuleByName(this.defaultPrefix, null);
         } else {
@@ -57,7 +58,7 @@ final class StringModuleInstanceIdentifierCodec extends AbstractModuleStringInst
 
     @Nullable
     @Override
-    protected String prefixForNamespace(@Nonnull URI namespace) {
+    protected String prefixForNamespace(@Nonnull final URI namespace) {
         final Module module = this.context.findModuleByNamespaceAndRevision(namespace, null);
         return module == null ? null : module.getName();
     }
index 4377dafabff73d2884b7880bfea2c1b604311dc6..27f3e78cbc99327338a4a2946a2091042a510cf5 100644 (file)
@@ -132,10 +132,11 @@ public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsPro
         } else if (schemaNodeContext instanceof DataSchemaNode) {
             schemaNode = (DataSchemaNode) schemaNodeContext;
         } else {
-            throw new IllegalStateException("Unknow SchemaNode");
+            throw new IllegalStateException("Unknown SchemaNode");
         }
 
         final String docRootElm = doc.getDocumentElement().getLocalName();
+        final String docRootNamespace = doc.getDocumentElement().getNamespaceURI();
         final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
         InstanceIdentifierContext<? extends SchemaNode> outIIContext;
 
@@ -145,7 +146,7 @@ public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsPro
                 DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, pathContext.getSchemaContext());
 
         if (isPost() && !isRpc) {
-            final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm);
+            final Deque<Object> foundSchemaNodes = findPathToSchemaNodeByName(schemaNode, docRootElm, docRootNamespace);
             if (foundSchemaNodes.isEmpty()) {
                 throw new IllegalStateException(String.format("Child \"%s\" was not found in parent schema node \"%s\"",
                         docRootElm, schemaNode.getQName()));
@@ -164,7 +165,7 @@ public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsPro
 
         NormalizedNode<?, ?> parsed = null;
 
-        if(schemaNode instanceof ContainerSchemaNode) {
+        if (schemaNode instanceof ContainerSchemaNode) {
             parsed = parserFactory.getContainerNodeParser().parse(Collections.singletonList(doc.getDocumentElement()), (ContainerSchemaNode) schemaNode);
         } else if(schemaNode instanceof ListSchemaNode) {
             final ListSchemaNode casted = (ListSchemaNode) schemaNode;
@@ -184,28 +185,35 @@ public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsPro
         return new NormalizedNodeContext(outIIContext, parsed);
     }
 
-    private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName) {
+    private static Deque<Object> findPathToSchemaNodeByName(final DataSchemaNode schemaNode, final String elementName,
+                                                            final String namespace) {
         final Deque<Object> result = new ArrayDeque<>();
         final ArrayList<ChoiceSchemaNode> choiceSchemaNodes = new ArrayList<>();
         final Collection<DataSchemaNode> children = ((DataNodeContainer) schemaNode).getChildNodes();
         for (final DataSchemaNode child : children) {
             if (child instanceof ChoiceSchemaNode) {
                 choiceSchemaNodes.add((ChoiceSchemaNode) child);
-            } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)) {
+            } else if (child.getQName().getLocalName().equalsIgnoreCase(elementName)
+                    && child.getQName().getNamespace().toString().equalsIgnoreCase(namespace)) {
+                // add child to result
                 result.push(child);
+
+                // find augmentation
                 if (child.isAugmenting()) {
                     final AugmentationSchema augment = findCorrespondingAugment(schemaNode, child);
                     if (augment != null) {
                         result.push(augment);
                     }
                 }
+
+                // return result
                 return result;
             }
         }
 
         for (final ChoiceSchemaNode choiceNode : choiceSchemaNodes) {
             for (final ChoiceCaseNode caseNode : choiceNode.getCases()) {
-                final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName);
+                final Deque<Object> resultFromRecursion = findPathToSchemaNodeByName(caseNode, elementName, namespace);
                 if (!resultFromRecursion.isEmpty()) {
                     resultFromRecursion.push(choiceNode);
                     if (choiceNode.isAugmenting()) {
index 77e83e367dc71afbfdb443574fabb89fd85f7bf6..c6224663efacbb3e654223c0f016d3161713cbbc 100644 (file)
@@ -14,6 +14,7 @@ import java.util.List;
 import java.util.Map;
 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
 import org.opendaylight.netconf.sal.rest.impl.RestUtil;
+import org.opendaylight.netconf.sal.rest.impl.StringModuleInstanceIdentifierCodec;
 import org.opendaylight.netconf.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
 import org.opendaylight.netconf.sal.restconf.impl.IdentityValuesDTO.Predicate;
 import org.opendaylight.yangtools.concepts.Codec;
@@ -63,16 +64,16 @@ public class RestCodec {
         private final TypeDefinition<?> type;
 
         private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint) {
-            type = RestUtil.resolveBaseTypeFrom(typeDefinition);
-            if (type instanceof IdentityrefTypeDefinition) {
-                identityrefCodec = new IdentityrefCodecImpl(mountPoint);
+            this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
+            if (this.type instanceof IdentityrefTypeDefinition) {
+                this.identityrefCodec = new IdentityrefCodecImpl(mountPoint);
             } else {
-                identityrefCodec = null;
+                this.identityrefCodec = null;
             }
-            if (type instanceof InstanceIdentifierTypeDefinition) {
-                instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint);
+            if (this.type instanceof InstanceIdentifierTypeDefinition) {
+                this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint);
             } else {
-                instanceIdentifier = null;
+                this.instanceIdentifier = null;
             }
         }
 
@@ -80,9 +81,9 @@ public class RestCodec {
         @Override
         public Object deserialize(final Object input) {
             try {
-                if (type instanceof IdentityrefTypeDefinition) {
+                if (this.type instanceof IdentityrefTypeDefinition) {
                     if (input instanceof IdentityValuesDTO) {
-                        return identityrefCodec.deserialize(input);
+                        return this.identityrefCodec.deserialize(input);
                     }
                     if(LOG.isDebugEnabled()) {
                         LOG.debug(
@@ -90,24 +91,24 @@ public class RestCodec {
                             input == null ? "null" : input.getClass(), String.valueOf(input));
                     }
                     return null;
-                } else if (type instanceof InstanceIdentifierTypeDefinition) {
+                } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
                     if (input instanceof IdentityValuesDTO) {
-                        return instanceIdentifier.deserialize(input);
+                        return this.instanceIdentifier.deserialize(input);
+                    } else {
+                        final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
+                                ControllerContext.getInstance().getGlobalSchema());
+                        return codec.deserialize((String) input);
                     }
-                    LOG.info(
-                            "Value is not instance of InstanceIdentifierTypeDefinition but is {}. Therefore NULL is used as translation of  - {}",
-                            input == null ? "null" : input.getClass(), String.valueOf(input));
-                    return null;
                 } else {
                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
-                            .from(type);
+                            .from(this.type);
                     if (typeAwarecodec != null) {
                         if (input instanceof IdentityValuesDTO) {
                             return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
                         }
                         return typeAwarecodec.deserialize(String.valueOf(input));
                     } else {
-                        LOG.debug("Codec for type \"" + type.getQName().getLocalName()
+                        LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
                                 + "\" is not implemented yet.");
                         return null;
                     }
@@ -124,20 +125,20 @@ public class RestCodec {
         @Override
         public Object serialize(final Object input) {
             try {
-                if (type instanceof IdentityrefTypeDefinition) {
-                    return identityrefCodec.serialize(input);
-                } else if (type instanceof LeafrefTypeDefinition) {
+                if (this.type instanceof IdentityrefTypeDefinition) {
+                    return this.identityrefCodec.serialize(input);
+                } else if (this.type instanceof LeafrefTypeDefinition) {
                     return LEAFREF_DEFAULT_CODEC.serialize(input);
-                } else if (type instanceof InstanceIdentifierTypeDefinition) {
-                    return instanceIdentifier.serialize(input);
+                } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
+                    return this.instanceIdentifier.serialize(input);
                 } else {
                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
-                            .from(type);
+                            .from(this.type);
                     if (typeAwarecodec != null) {
                         return typeAwarecodec.serialize(input);
                     } else {
                         if(LOG.isDebugEnabled()) {
-                            LOG.debug("Codec for type \"" + type.getQName().getLocalName()
+                            LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
                                 + "\" is not implemented yet.");
                         }
                         return null;
@@ -171,7 +172,7 @@ public class RestCodec {
         @Override
         public QName deserialize(final IdentityValuesDTO data) {
             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
-            final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
+            final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint);
             if (module == null) {
                 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
                 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
@@ -210,11 +211,11 @@ public class RestCodec {
             final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
             for (final PathArgument pathArgument : data.getPathArguments()) {
                 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
-                if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
+                if ((pathArgument instanceof NodeIdentifierWithPredicates) && (identityValue != null)) {
                     final List<Predicate> predicates = keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument)
                             .getKeyValues());
                     identityValue.setPredicates(predicates);
-                } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
+                } else if ((pathArgument instanceof NodeWithValue) && (identityValue != null)) {
                     final List<Predicate> predicates = new ArrayList<>();
                     final String value = String.valueOf(((NodeWithValue) pathArgument).getValue());
                     predicates.add(new Predicate(null, value));
@@ -229,7 +230,7 @@ public class RestCodec {
         public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
             final List<PathArgument> result = new ArrayList<PathArgument>();
             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
-            final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
+            final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint);
             if (module == null) {
                 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
                         valueWithNamespace.getNamespace());
@@ -242,7 +243,7 @@ public class RestCodec {
             final List<IdentityValue> identities = data.getValuesWithNamespaces();
             for (int i = 0; i < identities.size(); i++) {
                 final IdentityValue identityValue = identities.get(i);
-                URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), mountPoint);
+                URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), this.mountPoint);
                 final DataSchemaNode node = ControllerContext.findInstanceDataChildByNameAndNamespace(
                         parentContainer, identityValue.getValue(), validNamespace);
                 if (node == null) {
@@ -269,7 +270,7 @@ public class RestCodec {
                         final DataNodeContainer listNode = (DataNodeContainer) node;
                         final Map<QName, Object> predicatesMap = new HashMap<>();
                         for (final Predicate predicate : identityValue.getPredicates()) {
-                            validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), mountPoint);
+                            validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint);
                             final DataSchemaNode listKey = ControllerContext
                                     .findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(),
                                             validNamespace);
@@ -284,7 +285,7 @@ public class RestCodec {
                     }
                 }
                 result.add(pathArgument);
-                if (i < identities.size() - 1) { // last element in instance-identifier can be other than
+                if (i < (identities.size() - 1)) { // last element in instance-identifier can be other than
                     // DataNodeContainer
                     if (node instanceof DataNodeContainer) {
                         parentContainer = (DataNodeContainer) node;
index 7890ee035b70b7adc4e859af0a8100a6a39413e3..ded3543a88f3293c7c82dc4ea75de87b040d9cb1 100644 (file)
@@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory;
 public final class PatchDataTransactionUtil {
     private static final Logger LOG = LoggerFactory.getLogger(PatchDataTransactionUtil.class);
 
-    public PatchDataTransactionUtil() {
+    private PatchDataTransactionUtil() {
         throw new UnsupportedOperationException("Util class.");
     }
 
index ffe9565f4c7fe5c195791c8fe9cbc2bba7f10902..148834fcff50fdd37bef6fa5816d5c23183fc554 100644 (file)
@@ -17,26 +17,26 @@ import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
-final class Draft16StringModuleInstanceIdentifierCodec extends AbstractModuleStringInstanceIdentifierCodec {
+public final class Draft16StringModuleInstanceIdentifierCodec extends AbstractModuleStringInstanceIdentifierCodec {
 
     private final DataSchemaContextTree dataContextTree;
     private final SchemaContext context;
     private final String defaultPrefix;
 
-    Draft16StringModuleInstanceIdentifierCodec(SchemaContext context) {
+    public Draft16StringModuleInstanceIdentifierCodec(final SchemaContext context) {
         this.context = Preconditions.checkNotNull(context);
         this.dataContextTree = DataSchemaContextTree.from(context);
         this.defaultPrefix = "";
     }
 
-    Draft16StringModuleInstanceIdentifierCodec(SchemaContext context, @Nonnull String defaultPrefix) {
+    Draft16StringModuleInstanceIdentifierCodec(final SchemaContext context, @Nonnull final String defaultPrefix) {
         this.context = Preconditions.checkNotNull(context);
         this.dataContextTree = DataSchemaContextTree.from(context);
         this.defaultPrefix = defaultPrefix;
     }
 
     @Override
-    protected Module moduleForPrefix(@Nonnull String prefix) {
+    protected Module moduleForPrefix(@Nonnull final String prefix) {
         if (prefix.isEmpty() && !this.defaultPrefix.isEmpty()) {
             return this.context.findModuleByName(this.defaultPrefix, null);
         } else {
@@ -52,7 +52,7 @@ final class Draft16StringModuleInstanceIdentifierCodec extends AbstractModuleStr
 
     @Nullable
     @Override
-    protected String prefixForNamespace(@Nonnull URI namespace) {
+    protected String prefixForNamespace(@Nonnull final URI namespace) {
         final Module module = this.context.findModuleByNamespaceAndRevision(namespace, null);
         return module == null ? null : module.getName();
     }
diff --git a/restconf/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/rest/impl/InstanceIdentifierTypeLeafTest.java b/restconf/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/rest/impl/InstanceIdentifierTypeLeafTest.java
new file mode 100644 (file)
index 0000000..8439d0c
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.rest.impl;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
+import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
+import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class InstanceIdentifierTypeLeafTest {
+
+    @Test
+    public void stringToInstanceIdentifierTest() throws Exception {
+        final SchemaContext schemaContext = TestRestconfUtils.loadSchemaContext("/instanceidentifier");
+        ControllerContext.getInstance().setGlobalSchema(schemaContext);
+        final InstanceIdentifierContext<?> instanceIdentifier =
+                ControllerContext.getInstance().toInstanceIdentifier(
+                        "/iid-value-module:cont-iid/iid-list/%2Fiid-value-module%3Acont-iid%2Fiid-value-module%3A"
+                                + "values-iid%5Biid-value-module:value-iid='value'%5D");
+        final YangInstanceIdentifier yiD = instanceIdentifier.getInstanceIdentifier();
+        Assert.assertNotNull(yiD);
+        final PathArgument lastPathArgument = yiD.getLastPathArgument();
+        Assert.assertTrue(lastPathArgument.getNodeType().getNamespace().toString().equals("iid:value:module"));
+        Assert.assertTrue(lastPathArgument.getNodeType().getLocalName().equals("iid-list"));
+
+        final NodeIdentifierWithPredicates list = (NodeIdentifierWithPredicates) lastPathArgument;
+        final YangInstanceIdentifier value = (YangInstanceIdentifier) list.getKeyValues()
+                .get(QName.create(lastPathArgument.getNodeType(), "iid-leaf"));
+        final PathArgument lastPathArgumentOfValue = value.getLastPathArgument();
+        Assert.assertTrue(lastPathArgumentOfValue.getNodeType().getNamespace().toString().equals("iid:value:module"));
+        Assert.assertTrue(lastPathArgumentOfValue.getNodeType().getLocalName().equals("values-iid"));
+
+        final NodeIdentifierWithPredicates valueList = (NodeIdentifierWithPredicates) lastPathArgumentOfValue;
+        final String valueIid = (String) valueList.getKeyValues()
+                .get(QName.create(lastPathArgumentOfValue.getNodeType(), "value-iid"));
+        Assert.assertEquals("value", valueIid);
+    }
+
+}
index 50ce26a7f4d932ad943f1e590e94aa9559f14c2d..e14246434c06db91f3d6e4d510f478e042762e7a 100644 (file)
@@ -209,4 +209,48 @@ public class TestXmlBodyReader extends AbstractBodyReaderTest {
         assertEquals(dataNodeIdent, nnContext.getInstanceIdentifierContext().getInstanceIdentifier());
         assertNotNull(NormalizedNodes.findNode(nnContext.getData(), dataNodeIdent));
     }
+
+    /**
+     * Test when container with the same name is placed in two modules (foo-module and bar-module). Namespace must be
+     * used to distinguish between them to find correct one. Check if container was found not only according to its name
+     * but also by correct namespace used in payload.
+     */
+    @Test
+    public void findFooContainerUsingNamespaceTest() throws Exception {
+        mockBodyReader("", xmlBodyReader, true);
+        final InputStream inputStream = TestXmlBodyReader.class
+                .getResourceAsStream("/instanceidentifier/xml/xmlDataFindFooContainer.xml");
+        final NormalizedNodeContext returnValue = xmlBodyReader
+                .readFrom(null, null, null, mediaType, null, inputStream);
+
+        // check return value
+        checkNormalizedNodeContext(returnValue);
+        // check if container was found both according to its name and namespace
+        assertEquals("Not correct container found, name was ignored",
+                "foo-bar-container", returnValue.getData().getNodeType().getLocalName());
+        assertEquals("Not correct container found, namespace was ignored",
+                "foo:module", returnValue.getData().getNodeType().getNamespace().toString());
+    }
+
+    /**
+     * Test when container with the same name is placed in two modules (foo-module and bar-module). Namespace must be
+     * used to distinguish between them to find correct one. Check if container was found not only according to its name
+     * but also by correct namespace used in payload.
+     */
+    @Test
+    public void findBarContainerUsingNamespaceTest() throws Exception {
+        mockBodyReader("", xmlBodyReader, true);
+        final InputStream inputStream = TestXmlBodyReader.class
+                .getResourceAsStream("/instanceidentifier/xml/xmlDataFindBarContainer.xml");
+        final NormalizedNodeContext returnValue = xmlBodyReader
+                .readFrom(null, null, null, mediaType, null, inputStream);
+
+        // check return value
+        checkNormalizedNodeContext(returnValue);
+        // check if container was found both according to its name and namespace
+        assertEquals("Not correct container found, name was ignored",
+                "foo-bar-container", returnValue.getData().getNodeType().getLocalName());
+        assertEquals("Not correct container found, namespace was ignored",
+                "bar:module", returnValue.getData().getNodeType().getNamespace().toString());
+    }
 }
index 8376c76b9b07ad72bf4979317cb8bdea968edd71..2bb8ece0e10fa8651e1ae52ec66dd4c38c9015f0 100644 (file)
@@ -8,6 +8,7 @@
 
 package org.opendaylight.controller.sal.rest.impl.test.providers;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Matchers.any;
@@ -189,4 +190,48 @@ public class TestXmlBodyReaderMountPoint extends AbstractBodyReaderTest {
         assertNotNull(NormalizedNodes.findNode(nnContext.getData(),
                 dataNodeIdent));
     }
+
+    /**
+     * Test when container with the same name is placed in two modules (foo-module and bar-module). Namespace must be
+     * used to distinguish between them to find correct one. Check if container was found not only according to its name
+     * but also by correct namespace used in payload.
+     */
+    @Test
+    public void findFooContainerUsingNamespaceTest() throws Exception {
+        mockBodyReader("instance-identifier-module:cont/yang-ext:mount", xmlBodyReader, true);
+        final InputStream inputStream = TestXmlBodyReader.class
+                .getResourceAsStream("/instanceidentifier/xml/xmlDataFindFooContainer.xml");
+        final NormalizedNodeContext returnValue = xmlBodyReader
+                .readFrom(null, null, null, mediaType, null, inputStream);
+
+        // check return value
+        checkMountPointNormalizedNodeContext(returnValue);
+        // check if container was found both according to its name and namespace
+        assertEquals("Not correct container found, name was ignored",
+                "foo-bar-container", returnValue.getData().getNodeType().getLocalName());
+        assertEquals("Not correct container found, namespace was ignored",
+                "foo:module", returnValue.getData().getNodeType().getNamespace().toString());
+    }
+
+    /**
+     * Test when container with the same name is placed in two modules (foo-module and bar-module). Namespace must be
+     * used to distinguish between them to find correct one. Check if container was found not only according to its name
+     * but also by correct namespace used in payload.
+     */
+    @Test
+    public void findBarContainerUsingNamespaceTest() throws Exception {
+        mockBodyReader("instance-identifier-module:cont/yang-ext:mount", xmlBodyReader, true);
+        final InputStream inputStream = TestXmlBodyReader.class
+                .getResourceAsStream("/instanceidentifier/xml/xmlDataFindBarContainer.xml");
+        final NormalizedNodeContext returnValue = xmlBodyReader
+                .readFrom(null, null, null, mediaType, null, inputStream);
+
+        // check return value
+        checkMountPointNormalizedNodeContext(returnValue);
+        // check if container was found both according to its name and namespace
+        assertEquals("Not correct container found, name was ignored",
+                "foo-bar-container", returnValue.getData().getNodeType().getLocalName());
+        assertEquals("Not correct container found, namespace was ignored",
+                "bar:module", returnValue.getData().getNodeType().getNamespace().toString());
+    }
 }
diff --git a/restconf/sal-rest-connector/src/test/java/org/opendaylight/restconf/restful/utils/PatchDataTransactionUtilTest.java b/restconf/sal-rest-connector/src/test/java/org/opendaylight/restconf/restful/utils/PatchDataTransactionUtilTest.java
new file mode 100644 (file)
index 0000000..283db9b
--- /dev/null
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.restconf.restful.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.MockitoAnnotations.initMocks;
+
+import com.google.common.util.concurrent.Futures;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
+import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
+import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
+import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
+import org.opendaylight.netconf.sal.restconf.impl.PATCHEntity;
+import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
+import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusEntity;
+import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
+import org.opendaylight.restconf.RestConnectorProvider;
+import org.opendaylight.restconf.common.references.SchemaContextRef;
+import org.opendaylight.restconf.handlers.TransactionChainHandler;
+import org.opendaylight.restconf.restful.transaction.TransactionVarsWrapper;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+
+public class PatchDataTransactionUtilTest {
+
+    private static final String PATH_FOR_NEW_SCHEMA_CONTEXT = "/jukebox";
+
+    @Mock
+    private DOMTransactionChain transactionChain;
+
+    @Mock
+    private DOMDataReadWriteTransaction rWTransaction;
+
+    private SchemaContextRef refSchemaCtx;
+    private YangInstanceIdentifier iIDCreateAndDelete;
+    private YangInstanceIdentifier iIDMerge;
+    private ContainerNode buildBaseContainerForTests;
+    private YangInstanceIdentifier targetNodeForCreateAndDelete;
+    private YangInstanceIdentifier targetNodeMerge;
+    private MapNode buildArtistList;
+
+    // Fields used when delete operation fails to reset transaction chain
+    private static Field handler;
+    private static Field broker;
+
+    @Before
+    public void setUp() throws Exception {
+        initMocks(this);
+
+        PatchDataTransactionUtilTest.handler = RestConnectorProvider.class.getDeclaredField("transactionChainHandler");
+        PatchDataTransactionUtilTest.broker = RestConnectorProvider.class.getDeclaredField("dataBroker");
+
+        PatchDataTransactionUtilTest.handler.setAccessible(true);
+        PatchDataTransactionUtilTest.handler.set(RestConnectorProvider.class, mock(TransactionChainHandler.class));
+
+        PatchDataTransactionUtilTest.broker.setAccessible(true);
+        PatchDataTransactionUtilTest.broker.set(RestConnectorProvider.class, mock(DOMDataBroker.class));
+
+        refSchemaCtx = new SchemaContextRef(TestRestconfUtils.loadSchemaContext(PATH_FOR_NEW_SCHEMA_CONTEXT));
+        final QName baseQName = QName.create("http://example.com/ns/example-jukebox", "2015-04-04", "jukebox");
+        final QName containerPlayerQName = QName.create(baseQName, "player");
+        final QName leafGapQName = QName.create(baseQName, "gap");
+        final QName containerLibraryQName = QName.create(baseQName, "library");
+        final QName listArtistQName = QName.create(baseQName, "artist");
+        final QName leafNameQName = QName.create(baseQName, "name");
+        final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeWithKey =
+                new YangInstanceIdentifier.NodeIdentifierWithPredicates(listArtistQName, leafNameQName, "name of artist");
+
+        /** instance identifier for accessing leaf node "gap" */
+        iIDCreateAndDelete = YangInstanceIdentifier.builder()
+                .node(baseQName)
+                .node(containerPlayerQName)
+                .node(leafGapQName)
+                .build();
+
+        /** values that are used for creating leaf for testPatchDataCreateAndDelete test */
+        final LeafNode buildGapLeaf = Builders.leafBuilder()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(leafGapQName))
+                .withValue(0.2)
+                .build();
+
+        final ContainerNode buildPlayerContainer = Builders.containerBuilder()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(containerPlayerQName))
+                .withChild(buildGapLeaf)
+                .build();
+
+        buildBaseContainerForTests = Builders.containerBuilder()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(baseQName))
+                .withChild(buildPlayerContainer)
+                .build();
+
+        targetNodeForCreateAndDelete = YangInstanceIdentifier.builder(iIDCreateAndDelete)
+                .node(containerPlayerQName)
+                .node(leafGapQName)
+                .build();
+
+        /** instance identifier for accessing leaf node "name" in list "artist" */
+        iIDMerge = YangInstanceIdentifier.builder()
+                .node(baseQName)
+                .node(containerLibraryQName)
+                .node(listArtistQName)
+                .nodeWithKey(listArtistQName, QName.create(listArtistQName, "name"), "name of artist")
+                .node(leafNameQName)
+                .build();
+
+        /** values that are used for creating leaf for testPatchDataReplaceMergeAndRemove test */
+        final LeafNode<Object> contentName = Builders.leafBuilder()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(baseQName, "name")))
+                .withValue("name of artist")
+                .build();
+
+        final LeafNode<Object> contentDescription = Builders.leafBuilder()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(baseQName, "description")))
+                .withValue("description of artist")
+                .build();
+
+        final MapEntryNode mapEntryNode = Builders.mapEntryBuilder()
+                .withNodeIdentifier(nodeWithKey)
+                .withChild(contentName)
+                .withChild(contentDescription)
+                .build();
+
+        buildArtistList = Builders.mapBuilder()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(listArtistQName))
+                .withChild(mapEntryNode)
+                .build();
+
+        targetNodeMerge = YangInstanceIdentifier.builder()
+                .node(baseQName)
+                .node(containerLibraryQName)
+                .node(listArtistQName)
+                .nodeWithKey(listArtistQName, leafNameQName, "name of artist")
+                .build();
+
+        /** Mocks */
+        doReturn(rWTransaction).when(transactionChain).newReadWriteTransaction();
+        doReturn(Futures.immediateCheckedFuture(null)).when(rWTransaction).submit();
+    }
+
+    @Test
+    public void testPatchDataReplaceMergeAndRemove() {
+        doReturn(Futures.immediateCheckedFuture(false)).doReturn(Futures.immediateCheckedFuture(true))
+                .when(rWTransaction).exists(LogicalDatastoreType.CONFIGURATION, targetNodeMerge);
+
+        final PATCHEntity entityReplace = new PATCHEntity("edit1", "REPLACE", targetNodeMerge, buildArtistList);
+        final PATCHEntity entityMerge = new PATCHEntity("edit2", "MERGE", targetNodeMerge, buildArtistList);
+        final PATCHEntity entityRemove = new PATCHEntity("edit3", "REMOVE", targetNodeMerge);
+        final List<PATCHEntity> entities = new ArrayList<>();
+
+        entities.add(entityReplace);
+        entities.add(entityMerge);
+        entities.add(entityRemove);
+
+        final InstanceIdentifierContext<? extends SchemaNode> iidContext =
+                new InstanceIdentifierContext<>(iIDMerge, null, null, refSchemaCtx.get());
+        final PATCHContext patchContext = new PATCHContext(iidContext, entities, "patchRMRm");
+        final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(iidContext, null, transactionChain);
+        final PATCHStatusContext patchStatusContext =
+                PatchDataTransactionUtil.patchData(patchContext, wrapper, refSchemaCtx);
+
+        for (PATCHStatusEntity entity : patchStatusContext.getEditCollection()) {
+            assertTrue(entity.isOk());
+        }
+        assertTrue(patchStatusContext.isOk());
+    }
+
+    @Test
+    public void testPatchDataCreateAndDelete() throws Exception {
+        doReturn(Futures.immediateCheckedFuture(false)).doReturn(Futures.immediateCheckedFuture(true))
+                .when(rWTransaction).exists(LogicalDatastoreType.CONFIGURATION, targetNodeForCreateAndDelete);
+
+        final PATCHEntity entityCreate =
+                new PATCHEntity("edit1", "CREATE", targetNodeForCreateAndDelete, buildBaseContainerForTests);
+        final PATCHEntity entityDelete =
+                new PATCHEntity("edit2", "DELETE", targetNodeForCreateAndDelete);
+        final List<PATCHEntity> entities = new ArrayList<>();
+
+        entities.add(entityCreate);
+        entities.add(entityDelete);
+
+        final InstanceIdentifierContext<? extends SchemaNode> iidContext =
+                new InstanceIdentifierContext<>(iIDCreateAndDelete, null, null, refSchemaCtx.get());
+        final PATCHContext patchContext = new PATCHContext(iidContext, entities, "patchCD");
+        final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(iidContext, null, transactionChain);
+        final PATCHStatusContext patchStatusContext = PatchDataTransactionUtil.patchData(patchContext, wrapper, refSchemaCtx);
+
+        for (PATCHStatusEntity entity : patchStatusContext.getEditCollection()) {
+            assertTrue(entity.isOk());
+        }
+        assertTrue(patchStatusContext.isOk());
+    }
+
+    @Test
+    public void deleteNonexistentDataTest() {
+        doReturn(Futures.immediateCheckedFuture(false))
+                .when(rWTransaction).exists(LogicalDatastoreType.CONFIGURATION, targetNodeForCreateAndDelete);
+
+        final PATCHEntity entityDelete =
+                new PATCHEntity("edit", "DELETE", targetNodeForCreateAndDelete);
+        final List<PATCHEntity> entities = new ArrayList<>();
+
+        entities.add(entityDelete);
+
+        final InstanceIdentifierContext<? extends SchemaNode> iidContext =
+                new InstanceIdentifierContext<>(iIDCreateAndDelete, null, null, refSchemaCtx.get());
+        final PATCHContext patchContext = new PATCHContext(iidContext, entities, "patchD");
+        final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(iidContext, null, transactionChain);
+        final PATCHStatusContext patchStatusContext = PatchDataTransactionUtil.patchData(patchContext, wrapper, refSchemaCtx);
+
+        assertFalse(patchStatusContext.isOk());
+        assertEquals(RestconfError.ErrorType.PROTOCOL,
+                patchStatusContext.getEditCollection().get(0).getEditErrors().get(0).getErrorType());
+        assertEquals(RestconfError.ErrorTag.DATA_MISSING,
+                patchStatusContext.getEditCollection().get(0).getEditErrors().get(0).getErrorTag());
+    }
+
+    @Test
+    public void testPatchMergePutContainer() throws Exception {
+        doReturn(Futures.immediateCheckedFuture(false)).doReturn(Futures.immediateCheckedFuture(true))
+                .when(rWTransaction).exists(LogicalDatastoreType.CONFIGURATION, targetNodeForCreateAndDelete);
+
+        final PATCHEntity entityMerge =
+                new PATCHEntity("edit1", "MERGE", targetNodeForCreateAndDelete, buildBaseContainerForTests);
+        final List<PATCHEntity> entities = new ArrayList<>();
+
+        entities.add(entityMerge);
+
+        final InstanceIdentifierContext<? extends SchemaNode> iidContext =
+                new InstanceIdentifierContext<>(iIDCreateAndDelete, null, null, refSchemaCtx.get());
+        final PATCHContext patchContext = new PATCHContext(iidContext, entities, "patchM");
+        final TransactionVarsWrapper wrapper = new TransactionVarsWrapper(iidContext, null, transactionChain);
+        final PATCHStatusContext patchStatusContext = PatchDataTransactionUtil.patchData(patchContext, wrapper, refSchemaCtx);
+
+        for (PATCHStatusEntity entity : patchStatusContext.getEditCollection()) {
+            assertTrue(entity.isOk());
+        }
+        assertTrue(patchStatusContext.isOk());
+    }
+}
\ No newline at end of file
diff --git a/restconf/sal-rest-connector/src/test/resources/instanceidentifier/iid-value.yang b/restconf/sal-rest-connector/src/test/resources/instanceidentifier/iid-value.yang
new file mode 100644 (file)
index 0000000..4e536df
--- /dev/null
@@ -0,0 +1,23 @@
+module iid-value-module {
+    namespace "iid:value:module";
+
+    prefix "iidvm";
+    revision 2016-09-12 {
+    }
+
+    container cont-iid {
+        list iid-list{
+            key "iid-leaf";
+            leaf iid-leaf{
+                type instance-identifier;
+            }
+        }
+
+        list values-iid{
+            key "value-iid";
+            leaf value-iid{
+                type string;
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/restconf/sal-rest-connector/src/test/resources/instanceidentifier/xml/xmlDataFindBarContainer.xml b/restconf/sal-rest-connector/src/test/resources/instanceidentifier/xml/xmlDataFindBarContainer.xml
new file mode 100644 (file)
index 0000000..6523345
--- /dev/null
@@ -0,0 +1,10 @@
+<!--
+  ~ Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
+  ~
+  ~ This program and the accompanying materials are made available under the
+  ~ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+  ~ and is available at http://www.eclipse.org/legal/epl-v10.html
+  -->
+
+<foo-bar-container xmlns="bar:module">
+</foo-bar-container>
\ No newline at end of file
diff --git a/restconf/sal-rest-connector/src/test/resources/instanceidentifier/xml/xmlDataFindFooContainer.xml b/restconf/sal-rest-connector/src/test/resources/instanceidentifier/xml/xmlDataFindFooContainer.xml
new file mode 100644 (file)
index 0000000..93aeff8
--- /dev/null
@@ -0,0 +1,10 @@
+<!--
+  ~ Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
+  ~
+  ~ This program and the accompanying materials are made available under the
+  ~ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+  ~ and is available at http://www.eclipse.org/legal/epl-v10.html
+  -->
+
+<foo-bar-container xmlns="foo:module">
+</foo-bar-container>
\ No newline at end of file
diff --git a/restconf/sal-rest-connector/src/test/resources/instanceidentifier/yang/bar-module.yang b/restconf/sal-rest-connector/src/test/resources/instanceidentifier/yang/bar-module.yang
new file mode 100644 (file)
index 0000000..90de085
--- /dev/null
@@ -0,0 +1,11 @@
+module bar-module {
+  namespace "bar:module";
+
+  prefix "bar-module";
+    revision 2016-09-29 {
+  }
+
+  /* This container has the same name as container in foo-module */
+  container foo-bar-container {
+  }
+}
\ No newline at end of file
diff --git a/restconf/sal-rest-connector/src/test/resources/instanceidentifier/yang/foo-module.yang b/restconf/sal-rest-connector/src/test/resources/instanceidentifier/yang/foo-module.yang
new file mode 100644 (file)
index 0000000..16b8e7f
--- /dev/null
@@ -0,0 +1,11 @@
+module foo-module {
+  namespace "foo:module";
+
+  prefix "foo-module";
+    revision 2016-09-29 {
+  }
+
+  /* This container has the same name as container in bar-module */
+  container foo-bar-container {
+  }
+}
\ No newline at end of file