Make Netty-3 dependency optional
[controller.git] / opendaylight / blueprint / src / main / java / org / opendaylight / controller / blueprint / ext / DataStoreAppConfigDefaultXMLReader.java
index 709e0b4bab1ebeff8d2563a068094d3fc7c4f7e9..4dea3404f9f073677541678671786e7627f9293b 100644 (file)
@@ -7,25 +7,25 @@
  */
 package org.opendaylight.controller.blueprint.ext;
 
-import com.google.common.base.Optional;
 import com.google.common.base.Strings;
 import com.google.common.io.Resources;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URISyntaxException;
 import java.net.URL;
-import javax.xml.parsers.ParserConfigurationException;
+import java.util.Optional;
 import javax.xml.stream.XMLStreamException;
-import org.opendaylight.controller.sal.core.api.model.SchemaService;
 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
+import org.opendaylight.mdsal.dom.api.DOMSchemaService;
 import org.opendaylight.yangtools.util.xml.UntrustedXML;
 import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+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.opendaylight.yangtools.yang.model.api.SchemaTreeInference;
+import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
+import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
@@ -45,15 +45,15 @@ public class DataStoreAppConfigDefaultXMLReader<T extends DataObject> {
 
     private final String logName;
     private final String defaultAppConfigFileName;
-    private final SchemaService schemaService;
+    private final DOMSchemaService schemaService;
     private final BindingNormalizedNodeSerializer bindingSerializer;
     private final BindingContext bindingContext;
     private final ConfigURLProvider inputStreamProvider;
 
     @FunctionalInterface
     public interface FallbackConfigProvider {
-        NormalizedNode<?,?> get(SchemaContext schemaContext, DataSchemaNode dataSchema) throws IOException,
-                XMLStreamException, ParserConfigurationException, SAXException, URISyntaxException;
+        NormalizedNode get(SchemaTreeInference dataSchema)
+            throws IOException, XMLStreamException, SAXException, URISyntaxException;
     }
 
     @FunctionalInterface
@@ -64,7 +64,7 @@ public class DataStoreAppConfigDefaultXMLReader<T extends DataObject> {
     public DataStoreAppConfigDefaultXMLReader(
             final String logName,
             final String defaultAppConfigFileName,
-            final SchemaService schemaService,
+            final DOMSchemaService schemaService,
             final BindingNormalizedNodeSerializer bindingSerializer,
             final BindingContext bindingContext,
             final ConfigURLProvider inputStreamProvider) {
@@ -80,7 +80,7 @@ public class DataStoreAppConfigDefaultXMLReader<T extends DataObject> {
     public DataStoreAppConfigDefaultXMLReader(
             final Class<?> testClass,
             final String defaultAppConfigFileName,
-            final SchemaService schemaService,
+            final DOMSchemaService schemaService,
             final BindingNormalizedNodeSerializer bindingSerializer,
             final Class<T> klass) {
         this(testClass.getName(), defaultAppConfigFileName, schemaService, bindingSerializer,
@@ -92,72 +92,75 @@ public class DataStoreAppConfigDefaultXMLReader<T extends DataObject> {
         return Resources.getResource(testClass, defaultAppConfigFileName);
     }
 
-    public T createDefaultInstance() throws ConfigXMLReaderException, ParserConfigurationException, XMLStreamException,
-            IOException, SAXException, URISyntaxException {
-        return createDefaultInstance((schemaContext, dataSchema) -> {
-            throw new IllegalArgumentException("Failed to read XML "
-                    + "(not creating model from defaults as runtime would, for better clarity in tests)");
+    public T createDefaultInstance() throws ConfigXMLReaderException, XMLStreamException, IOException, SAXException,
+            URISyntaxException {
+        return createDefaultInstance(dataSchema -> {
+            throw new IllegalArgumentException(
+                "Failed to read XML (not creating model from defaults as runtime would, for better clarity in tests)");
         });
     }
 
     @SuppressWarnings("unchecked")
     public T createDefaultInstance(final FallbackConfigProvider fallback) throws ConfigXMLReaderException,
-            URISyntaxException, ParserConfigurationException, XMLStreamException, SAXException, IOException {
+            URISyntaxException, XMLStreamException, SAXException, IOException {
         YangInstanceIdentifier yangPath = bindingSerializer.toYangInstanceIdentifier(bindingContext.appConfigPath);
 
         LOG.debug("{}: Creating app config instance from path {}, Qname: {}", logName, yangPath,
                 bindingContext.bindingQName);
 
-        if (schemaService == null) {
-            throw new ConfigXMLReaderException(
-                    String.format("%s: Could not obtain the SchemaService OSGi service", logName));
-        }
+        checkNotNull(schemaService, "%s: Could not obtain the SchemaService OSGi service", logName);
 
-        SchemaContext schemaContext = schemaService.getGlobalContext();
+        EffectiveModelContext schemaContext = schemaService.getGlobalContext();
 
-        Module module = schemaContext.findModuleByNamespaceAndRevision(bindingContext.bindingQName.getNamespace(),
-                bindingContext.bindingQName.getRevision());
-        if (module == null) {
-            throw new ConfigXMLReaderException(
-                    String.format("%s: Could not obtain the module schema for namespace %s, revision %s",
-                    logName, bindingContext.bindingQName.getNamespace(), bindingContext.bindingQName.getRevision()));
-        }
+        Module module = schemaContext.findModule(bindingContext.bindingQName.getModule()).orElse(null);
+        checkNotNull(module, "%s: Could not obtain the module schema for namespace %s, revision %s",
+                logName, bindingContext.bindingQName.getNamespace(), bindingContext.bindingQName.getRevision());
 
-        DataSchemaNode dataSchema = module.getDataChildByName(bindingContext.bindingQName);
-        if (dataSchema == null) {
+        final SchemaInferenceStack schemaStack = SchemaInferenceStack.of(schemaContext);
+        final SchemaTreeEffectiveStatement<?> dataSchema;
+        try {
+            dataSchema = schemaStack.enterSchemaTree(bindingContext.bindingQName);
+        } catch (IllegalArgumentException e) {
             throw new ConfigXMLReaderException(
-                    String.format("%s: Could not obtain the schema for %s", logName,
-                    bindingContext.bindingQName));
+                logName + ": Could not obtain the schema for " + bindingContext.bindingQName, e);
         }
 
-        if (!bindingContext.schemaType.isAssignableFrom(dataSchema.getClass())) {
-            throw new ConfigXMLReaderException(
-                    String.format("%s: Expected schema type %s for %s but actual type is %s", logName,
-                    bindingContext.schemaType, bindingContext.bindingQName, dataSchema.getClass()));
-        }
+        checkCondition(bindingContext.schemaType.isInstance(dataSchema),
+                "%s: Expected schema type %s for %s but actual type is %s", logName,
+                bindingContext.schemaType, bindingContext.bindingQName, dataSchema.getClass());
 
-        NormalizedNode<?, ?> dataNode = parsePossibleDefaultAppConfigXMLFile(schemaContext, dataSchema);
+        NormalizedNode dataNode = parsePossibleDefaultAppConfigXMLFile(schemaStack);
         if (dataNode == null) {
-            dataNode = fallback.get(schemaService.getGlobalContext(), dataSchema);
+            dataNode = fallback.get(schemaStack.toSchemaTreeInference());
         }
 
         DataObject appConfig = bindingSerializer.fromNormalizedNode(yangPath, dataNode).getValue();
-        if (appConfig == null) {
-            // This shouldn't happen but need to handle it in case...
-            throw new ConfigXMLReaderException(
-                    String.format("%s: Could not create instance for app config binding %s",
-                    logName, bindingContext.appConfigBindingClass));
-        } else {
-            return (T) appConfig;
-        }
+
+        // This shouldn't happen but need to handle it in case...
+        checkNotNull(appConfig, "%s: Could not create instance for app config binding %s", logName,
+                bindingContext.appConfigBindingClass);
+
+        return (T) appConfig;
     }
 
-    private NormalizedNode<?, ?> parsePossibleDefaultAppConfigXMLFile(final SchemaContext schemaContext,
-            final DataSchemaNode dataSchema) throws ConfigXMLReaderException {
+    private static void checkNotNull(final Object reference, final String errorMessageFormat,
+            final Object... formatArgs) throws ConfigXMLReaderException {
+        checkCondition(reference != null, errorMessageFormat, formatArgs);
+    }
+
+    private static void checkCondition(final boolean expression, final String errorMessageFormat,
+            final Object... formatArgs) throws ConfigXMLReaderException {
+        if (!expression) {
+            throw new ConfigXMLReaderException(String.format(errorMessageFormat, formatArgs));
+        }
+    }
 
+    private NormalizedNode parsePossibleDefaultAppConfigXMLFile(final SchemaInferenceStack schemaStack)
+            throws ConfigXMLReaderException {
         String appConfigFileName = defaultAppConfigFileName;
         if (Strings.isNullOrEmpty(appConfigFileName)) {
-            String moduleName = findYangModuleName(bindingContext.bindingQName, schemaContext);
+            String moduleName = schemaStack.currentModule().argument().getLocalName();
+
             appConfigFileName = moduleName + "_" + bindingContext.bindingQName.getLocalName() + ".xml";
         }
 
@@ -172,32 +175,19 @@ public class DataStoreAppConfigDefaultXMLReader<T extends DataObject> {
         if (!optionalURL.isPresent()) {
             return null;
         }
-        URL url = optionalURL.get();
+        URL url = optionalURL.orElseThrow();
         try (InputStream is = url.openStream()) {
             Document root = UntrustedXML.newDocumentBuilder().parse(is);
-            NormalizedNode<?, ?> dataNode = bindingContext.parseDataElement(root.getDocumentElement(), dataSchema,
-                    schemaContext);
+            NormalizedNode dataNode = bindingContext.parseDataElement(root.getDocumentElement(),
+                schemaStack.toSchemaTreeInference());
 
             LOG.debug("{}: Parsed data node: {}", logName, dataNode);
 
             return dataNode;
-        } catch (final IOException | SAXException | XMLStreamException | ParserConfigurationException
-                | URISyntaxException e) {
+        } catch (final IOException | SAXException | XMLStreamException | URISyntaxException e) {
             String msg = String.format("%s: Could not read/parse app config %s", logName, url);
             LOG.error(msg, e);
             throw new ConfigXMLReaderException(msg, e);
         }
     }
-
-    private String findYangModuleName(final QName qname, final SchemaContext schemaContext)
-            throws ConfigXMLReaderException {
-        for (Module m : schemaContext.getModules()) {
-            if (qname.getModule().equals(m.getQNameModule())) {
-                return m.getName();
-            }
-        }
-        throw new ConfigXMLReaderException(
-                String.format("%s: Could not find yang module for QName %s", logName, qname));
-    }
-
 }