2 * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.blueprint.ext;
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;
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;
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.
40 * @author Thomas Pantelis (originally; re-factored by Michael Vorburger.ch)
42 public class DataStoreAppConfigDefaultXMLReader<T extends DataObject> {
44 private static final Logger LOG = LoggerFactory.getLogger(DataStoreAppConfigDefaultXMLReader.class);
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;
54 public interface FallbackConfigProvider {
55 NormalizedNode get(SchemaTreeInference dataSchema)
56 throws IOException, XMLStreamException, SAXException, URISyntaxException;
60 public interface ConfigURLProvider {
61 Optional<URL> getURL(String appConfigFileName) throws IOException;
64 public DataStoreAppConfigDefaultXMLReader(
66 final String defaultAppConfigFileName,
67 final DOMSchemaService schemaService,
68 final BindingNormalizedNodeSerializer bindingSerializer,
69 final BindingContext bindingContext,
70 final ConfigURLProvider inputStreamProvider) {
72 this.logName = logName;
73 this.defaultAppConfigFileName = defaultAppConfigFileName;
74 this.schemaService = schemaService;
75 this.bindingSerializer = bindingSerializer;
76 this.bindingContext = bindingContext;
77 this.inputStreamProvider = inputStreamProvider;
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)));
91 private static URL getURL(final Class<?> testClass, final String defaultAppConfigFileName) {
92 return Resources.getResource(testClass, defaultAppConfigFileName);
95 public T createDefaultInstance() throws ConfigXMLReaderException, XMLStreamException, IOException, SAXException,
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)");
103 @SuppressWarnings("unchecked")
104 public T createDefaultInstance(final FallbackConfigProvider fallback) throws ConfigXMLReaderException,
105 URISyntaxException, XMLStreamException, SAXException, IOException {
106 YangInstanceIdentifier yangPath = bindingSerializer.toYangInstanceIdentifier(bindingContext.appConfigPath);
108 LOG.debug("{}: Creating app config instance from path {}, Qname: {}", logName, yangPath,
109 bindingContext.bindingQName);
111 checkNotNull(schemaService, "%s: Could not obtain the SchemaService OSGi service", logName);
113 EffectiveModelContext schemaContext = schemaService.getGlobalContext();
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());
119 final SchemaInferenceStack schemaStack = SchemaInferenceStack.of(schemaContext);
120 final SchemaTreeEffectiveStatement<?> dataSchema;
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);
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());
132 NormalizedNode dataNode = parsePossibleDefaultAppConfigXMLFile(schemaStack);
133 if (dataNode == null) {
134 dataNode = fallback.get(schemaStack.toSchemaTreeInference());
137 DataObject appConfig = bindingSerializer.fromNormalizedNode(yangPath, dataNode).getValue();
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);
143 return (T) appConfig;
146 private static void checkNotNull(final Object reference, final String errorMessageFormat,
147 final Object... formatArgs) throws ConfigXMLReaderException {
148 checkCondition(reference != null, errorMessageFormat, formatArgs);
151 private static void checkCondition(final boolean expression, final String errorMessageFormat,
152 final Object... formatArgs) throws ConfigXMLReaderException {
154 throw new ConfigXMLReaderException(String.format(errorMessageFormat, formatArgs));
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();
164 appConfigFileName = moduleName + "_" + bindingContext.bindingQName.getLocalName() + ".xml";
167 Optional<URL> optionalURL;
169 optionalURL = inputStreamProvider.getURL(appConfigFileName);
170 } catch (final IOException e) {
171 String msg = String.format("%s: Could not getURL()", logName);
173 throw new ConfigXMLReaderException(msg, e);
175 if (!optionalURL.isPresent()) {
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());
184 LOG.debug("{}: Parsed data node: {}", logName, dataNode);
187 } catch (final IOException | SAXException | XMLStreamException | URISyntaxException e) {
188 String msg = String.format("%s: Could not read/parse app config %s", logName, url);
190 throw new ConfigXMLReaderException(msg, e);