Improve segmented journal actor metrics
[controller.git] / opendaylight / blueprint / src / main / java / org / opendaylight / controller / blueprint / ext / DataStoreAppConfigDefaultXMLReader.java
1 /*
2  * Copyright (c) 2016 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.blueprint.ext;
9
10 import com.google.common.base.Strings;
11 import com.google.common.io.Resources;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.net.URISyntaxException;
15 import java.net.URL;
16 import java.util.Optional;
17 import javax.xml.stream.XMLStreamException;
18 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
19 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
20 import org.opendaylight.yangtools.util.xml.UntrustedXML;
21 import org.opendaylight.yangtools.yang.binding.DataObject;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
24 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
25 import org.opendaylight.yangtools.yang.model.api.Module;
26 import org.opendaylight.yangtools.yang.model.api.SchemaTreeInference;
27 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.w3c.dom.Document;
32 import org.xml.sax.SAXException;
33
34 /**
35  * DataObject XML file reader used by {@link DataStoreAppConfigMetadata}.
36  * Available as a standalone class to make it easy to write unit tests which can
37  * catch malformed default "clustered-app-conf" config data XML files in
38  * downstream projects.
39  *
40  * @author Thomas Pantelis (originally; re-factored by Michael Vorburger.ch)
41  */
42 public class DataStoreAppConfigDefaultXMLReader<T extends DataObject> {
43
44     private static final Logger LOG = LoggerFactory.getLogger(DataStoreAppConfigDefaultXMLReader.class);
45
46     private final String logName;
47     private final String defaultAppConfigFileName;
48     private final DOMSchemaService schemaService;
49     private final BindingNormalizedNodeSerializer bindingSerializer;
50     private final BindingContext bindingContext;
51     private final ConfigURLProvider inputStreamProvider;
52
53     @FunctionalInterface
54     public interface FallbackConfigProvider {
55         NormalizedNode get(SchemaTreeInference dataSchema)
56             throws IOException, XMLStreamException, SAXException, URISyntaxException;
57     }
58
59     @FunctionalInterface
60     public interface ConfigURLProvider {
61         Optional<URL> getURL(String appConfigFileName) throws IOException;
62     }
63
64     public DataStoreAppConfigDefaultXMLReader(
65             final String logName,
66             final String defaultAppConfigFileName,
67             final DOMSchemaService schemaService,
68             final BindingNormalizedNodeSerializer bindingSerializer,
69             final BindingContext bindingContext,
70             final ConfigURLProvider inputStreamProvider) {
71
72         this.logName = logName;
73         this.defaultAppConfigFileName = defaultAppConfigFileName;
74         this.schemaService = schemaService;
75         this.bindingSerializer = bindingSerializer;
76         this.bindingContext = bindingContext;
77         this.inputStreamProvider = inputStreamProvider;
78     }
79
80     public DataStoreAppConfigDefaultXMLReader(
81             final Class<?> testClass,
82             final String defaultAppConfigFileName,
83             final DOMSchemaService schemaService,
84             final BindingNormalizedNodeSerializer bindingSerializer,
85             final Class<T> klass) {
86         this(testClass.getName(), defaultAppConfigFileName, schemaService, bindingSerializer,
87             BindingContext.create(testClass.getName(), klass, null),
88             appConfigFileName -> Optional.of(getURL(testClass, defaultAppConfigFileName)));
89     }
90
91     private static URL getURL(final Class<?> testClass, final String defaultAppConfigFileName) {
92         return Resources.getResource(testClass, defaultAppConfigFileName);
93     }
94
95     public T createDefaultInstance() throws ConfigXMLReaderException, XMLStreamException, IOException, SAXException,
96             URISyntaxException {
97         return createDefaultInstance(dataSchema -> {
98             throw new IllegalArgumentException(
99                 "Failed to read XML (not creating model from defaults as runtime would, for better clarity in tests)");
100         });
101     }
102
103     @SuppressWarnings("unchecked")
104     public T createDefaultInstance(final FallbackConfigProvider fallback) throws ConfigXMLReaderException,
105             URISyntaxException, XMLStreamException, SAXException, IOException {
106         YangInstanceIdentifier yangPath = bindingSerializer.toYangInstanceIdentifier(bindingContext.appConfigPath);
107
108         LOG.debug("{}: Creating app config instance from path {}, Qname: {}", logName, yangPath,
109                 bindingContext.bindingQName);
110
111         checkNotNull(schemaService, "%s: Could not obtain the SchemaService OSGi service", logName);
112
113         EffectiveModelContext schemaContext = schemaService.getGlobalContext();
114
115         Module module = schemaContext.findModule(bindingContext.bindingQName.getModule()).orElse(null);
116         checkNotNull(module, "%s: Could not obtain the module schema for namespace %s, revision %s",
117                 logName, bindingContext.bindingQName.getNamespace(), bindingContext.bindingQName.getRevision());
118
119         final SchemaInferenceStack schemaStack = SchemaInferenceStack.of(schemaContext);
120         final SchemaTreeEffectiveStatement<?> dataSchema;
121         try {
122             dataSchema = schemaStack.enterSchemaTree(bindingContext.bindingQName);
123         } catch (IllegalArgumentException e) {
124             throw new ConfigXMLReaderException(
125                 logName + ": Could not obtain the schema for " + bindingContext.bindingQName, e);
126         }
127
128         checkCondition(bindingContext.schemaType.isInstance(dataSchema),
129                 "%s: Expected schema type %s for %s but actual type is %s", logName,
130                 bindingContext.schemaType, bindingContext.bindingQName, dataSchema.getClass());
131
132         NormalizedNode dataNode = parsePossibleDefaultAppConfigXMLFile(schemaStack);
133         if (dataNode == null) {
134             dataNode = fallback.get(schemaStack.toSchemaTreeInference());
135         }
136
137         DataObject appConfig = bindingSerializer.fromNormalizedNode(yangPath, dataNode).getValue();
138
139         // This shouldn't happen but need to handle it in case...
140         checkNotNull(appConfig, "%s: Could not create instance for app config binding %s", logName,
141                 bindingContext.appConfigBindingClass);
142
143         return (T) appConfig;
144     }
145
146     private static void checkNotNull(final Object reference, final String errorMessageFormat,
147             final Object... formatArgs) throws ConfigXMLReaderException {
148         checkCondition(reference != null, errorMessageFormat, formatArgs);
149     }
150
151     private static void checkCondition(final boolean expression, final String errorMessageFormat,
152             final Object... formatArgs) throws ConfigXMLReaderException {
153         if (!expression) {
154             throw new ConfigXMLReaderException(String.format(errorMessageFormat, formatArgs));
155         }
156     }
157
158     private NormalizedNode parsePossibleDefaultAppConfigXMLFile(final SchemaInferenceStack schemaStack)
159             throws ConfigXMLReaderException {
160         String appConfigFileName = defaultAppConfigFileName;
161         if (Strings.isNullOrEmpty(appConfigFileName)) {
162             String moduleName = schemaStack.currentModule().argument().getLocalName();
163
164             appConfigFileName = moduleName + "_" + bindingContext.bindingQName.getLocalName() + ".xml";
165         }
166
167         Optional<URL> optionalURL;
168         try {
169             optionalURL = inputStreamProvider.getURL(appConfigFileName);
170         } catch (final IOException e) {
171             String msg = String.format("%s: Could not getURL()", logName);
172             LOG.error(msg, e);
173             throw new ConfigXMLReaderException(msg, e);
174         }
175         if (!optionalURL.isPresent()) {
176             return null;
177         }
178         URL url = optionalURL.orElseThrow();
179         try (InputStream is = url.openStream()) {
180             Document root = UntrustedXML.newDocumentBuilder().parse(is);
181             NormalizedNode dataNode = bindingContext.parseDataElement(root.getDocumentElement(),
182                 schemaStack.toSchemaTreeInference());
183
184             LOG.debug("{}: Parsed data node: {}", logName, dataNode);
185
186             return dataNode;
187         } catch (final IOException | SAXException | XMLStreamException | URISyntaxException e) {
188             String msg = String.format("%s: Could not read/parse app config %s", logName, url);
189             LOG.error(msg, e);
190             throw new ConfigXMLReaderException(msg, e);
191         }
192     }
193 }