Cleanup use of deprecated constructs
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / handlers / SchemaContextHandler.java
index 0db960f9db5142e36fea3d061173a39dfd76ab53..daeb0c1443e1329748fee3d739dd4ba753770352 100644 (file)
  */
 package org.opendaylight.restconf.nb.rfc8040.handlers;
 
-import com.google.common.base.Preconditions;
+import static java.util.Objects.requireNonNull;
+
+import com.google.common.base.Throwables;
 import java.util.Collection;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import org.apache.aries.blueprint.annotation.service.Reference;
+import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
+import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
+import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
+import org.opendaylight.mdsal.dom.api.DOMSchemaService;
+import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
-import org.opendaylight.restconf.nb.rfc8040.RestConnectorProvider;
 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.IetfYangLibrary;
 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.MonitoringModule;
 import org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUtil;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
 import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
  * Implementation of {@link SchemaContextHandler}.
- *
  */
-public class SchemaContextHandler implements SchemaContextListenerHandler {
+@Singleton
+@SuppressWarnings("checkstyle:FinalClass")
+public class SchemaContextHandler implements SchemaContextListenerHandler, AutoCloseable {
 
     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextHandler.class);
 
+    private final AtomicInteger moduleSetId = new AtomicInteger(0);
+
     private final TransactionChainHandler transactionChainHandler;
-    private SchemaContext context;
+    private final DOMSchemaService domSchemaService;
+    private ListenerRegistration<?> listenerRegistration;
 
-    private int moduleSetId;
+    private volatile EffectiveModelContext schemaContext;
 
     /**
-     * Set module-set-id on initial value - 0.
+     * Constructor.
      *
      * @param transactionChainHandler Transaction chain handler
      */
-    public SchemaContextHandler(final TransactionChainHandler transactionChainHandler) {
+    @Inject
+    public SchemaContextHandler(final TransactionChainHandler transactionChainHandler,
+            final @Reference DOMSchemaService domSchemaService) {
         this.transactionChainHandler = transactionChainHandler;
-        this.moduleSetId = 0;
+        this.domSchemaService = domSchemaService;
+    }
+
+    @PostConstruct
+    public void init() {
+        listenerRegistration = domSchemaService.registerSchemaContextListener(this);
     }
 
     @Override
-    public void onGlobalContextUpdated(final SchemaContext context) {
-        Preconditions.checkNotNull(context);
-        this.context = null;
-        this.context = context;
-        this.moduleSetId++;
+    @PreDestroy
+    public void close() {
+        if (listenerRegistration != null) {
+            listenerRegistration.close();
+        }
+    }
+
+    @Override
+    @SuppressWarnings("checkstyle:hiddenField")
+    public void onModelContextUpdated(final EffectiveModelContext context) {
+        schemaContext = requireNonNull(context);
+
         final Module ietfYangLibraryModule =
-                context.findModuleByNamespaceAndRevision(IetfYangLibrary.URI_MODULE, IetfYangLibrary.DATE);
-        NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode =
-                RestconfMappingNodeUtil.mapModulesByIetfYangLibraryYang(context.getModules(), ietfYangLibraryModule,
-                        context, String.valueOf(this.moduleSetId));
-        putData(normNode);
+                context.findModule(IetfYangLibrary.MODULE_QNAME).orElse(null);
+        if (ietfYangLibraryModule != null) {
+            NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode =
+                    RestconfMappingNodeUtil.mapModulesByIetfYangLibraryYang(context.getModules(), ietfYangLibraryModule,
+                            context, String.valueOf(this.moduleSetId.incrementAndGet()));
+            putData(normNode);
+        }
 
         final Module monitoringModule =
-                this.context.findModuleByNamespaceAndRevision(MonitoringModule.URI_MODULE, MonitoringModule.DATE);
-        normNode = RestconfMappingNodeUtil.mapCapabilites(monitoringModule);
-        putData(normNode);
+                schemaContext.findModule(MonitoringModule.MODULE_QNAME).orElse(null);
+        if (monitoringModule != null) {
+            NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode =
+                    RestconfMappingNodeUtil.mapCapabilites(monitoringModule);
+            putData(normNode);
+        }
     }
 
     @Override
-    public SchemaContext get() {
-        return this.context;
+    public EffectiveModelContext get() {
+        return schemaContext;
     }
 
     private void putData(
             final NormalizedNode<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> normNode) {
-        final DOMDataWriteTransaction wTx = this.transactionChainHandler.get().newWriteOnlyTransaction();
+        final DOMTransactionChain transactionChain = this.transactionChainHandler.get();
+        final DOMDataTreeWriteTransaction wTx = transactionChain.newWriteOnlyTransaction();
         wTx.put(LogicalDatastoreType.OPERATIONAL,
                 YangInstanceIdentifier.create(NodeIdentifier.create(normNode.getNodeType())), normNode);
         try {
-            wTx.submit().checkedGet();
-        } catch (final TransactionCommitFailedException e) {
-            if (!(e.getCause() instanceof ConflictingModificationAppliedException)) {
-                throw new RestconfDocumentedException("Problem occurred while putting data to DS.", e);
+            wTx.commit().get();
+        } catch (InterruptedException e) {
+            throw new RestconfDocumentedException("Problem occurred while putting data to DS.", e);
+        } catch (ExecutionException e) {
+            final TransactionCommitFailedException failure = Throwables.getCauseAs(e,
+                TransactionCommitFailedException.class);
+            if (failure.getCause() instanceof ConflictingModificationAppliedException) {
+                /*
+                 * Ignore error when another cluster node is already putting the same data to DS.
+                 * We expect that cluster is homogeneous and that node was going to write the same data
+                 * (that means no retry is needed). Transaction chain reset must be invoked to be able
+                 * to continue writing data with another transaction after failed transaction.
+                 * This is workaround for bug https://bugs.opendaylight.org/show_bug.cgi?id=7728
+                 */
+                LOG.warn("Ignoring that another cluster node is already putting the same data to DS.", e);
+            } else {
+                throw new RestconfDocumentedException("Problem occurred while putting data to DS.", failure);
             }
-
-            /*
-              Ignore error when another cluster node is already putting the same data to DS.
-              We expect that cluster is homogeneous and that node was going to write the same data
-              (that means no retry is needed). Transaction chain reset must be invoked to be able
-              to continue writing data with another transaction after failed transaction.
-              This is workaround for bug:
-              https://bugs.opendaylight.org/show_bug.cgi?id=7728
-            */
-            LOG.warn("Ignoring that another cluster node is already putting the same data to DS.", e);
-            RestConnectorProvider.resetTransactionChainForAdapaters(this.transactionChainHandler.get());
+        } finally {
+            transactionChain.close();
         }
     }
 }