bfcae8300eac96c1c94024fcf58767fc96300c91
[yangtools.git] / yang / yang-repo-api / src / main / java / org / opendaylight / yangtools / yang / model / repo / api / YinDomSchemaSource.java
1 /*
2  * Copyright (c) 2015 Cisco 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.yangtools.yang.model.repo.api;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.yangtools.yang.common.YangConstants.RFC6020_YIN_MODULE;
13 import static org.opendaylight.yangtools.yang.model.api.YangStmtMapping.MODULE;
14 import static org.opendaylight.yangtools.yang.model.api.YangStmtMapping.REVISION;
15 import static org.opendaylight.yangtools.yang.model.api.YangStmtMapping.SUBMODULE;
16
17 import com.google.common.base.MoreObjects;
18 import com.google.common.base.MoreObjects.ToStringHelper;
19 import java.util.Optional;
20 import javax.xml.transform.Source;
21 import javax.xml.transform.TransformerException;
22 import javax.xml.transform.TransformerFactory;
23 import javax.xml.transform.dom.DOMResult;
24 import javax.xml.transform.dom.DOMSource;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.common.Revision;
29 import org.opendaylight.yangtools.yang.common.YangConstants;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.w3c.dom.Attr;
33 import org.w3c.dom.Element;
34 import org.w3c.dom.Node;
35 import org.w3c.dom.NodeList;
36
37 /**
38  * Utility {@link YinXmlSchemaSource} exposing a W3C {@link DOMSource} representation of YIN model.
39  */
40 public abstract class YinDomSchemaSource implements YinXmlSchemaSource {
41     private static final Logger LOG = LoggerFactory.getLogger(YinDomSchemaSource.class);
42     private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
43     private static final QName REVISION_STMT = REVISION.getStatementName();
44     private static final String MODULE_ARG = MODULE.getArgumentDefinition().get().getArgumentName().getLocalName();
45     private static final String REVISION_ARG = REVISION.getArgumentDefinition().get().getArgumentName().getLocalName();
46
47     YinDomSchemaSource() {
48         // Prevent outside instantiation
49     }
50
51     /**
52      * Create a new {@link YinDomSchemaSource} using an identifier and a source.
53      *
54      * @param identifier Schema source identifier
55      * @param source W3C DOM source
56      * @param symbolicName Source symbolic name
57      * @return A new {@link YinDomSchemaSource} instance.
58      */
59     public static @NonNull YinDomSchemaSource create(final @NonNull SourceIdentifier identifier,
60             final @NonNull DOMSource source, final @Nullable String symbolicName) {
61
62         final Node root = source.getNode().getFirstChild();
63         final String rootNs = root.getNamespaceURI();
64         if (rootNs == null) {
65             // Let whoever is using this deal with this
66             return new Simple(identifier, source, symbolicName);
67         }
68
69         final QName qname = QName.create(rootNs, root.getLocalName());
70         checkArgument(RFC6020_YIN_MODULE.equals(qname.getModule()),
71             "Root node namepsace %s does not match %s", rootNs, YangConstants.RFC6020_YIN_NAMESPACE);
72         checkArgument(MODULE.getStatementName().equals(qname)
73             || SUBMODULE.getStatementName().equals(qname), "Root element %s is not a module nor a submodule", qname);
74
75         checkArgument(root instanceof Element, "Root node %s is not an element", root);
76         final Element element = (Element)root;
77
78         final Attr nameAttr = element.getAttributeNode(MODULE_ARG);
79         checkArgument(nameAttr != null, "No %s name argument found in %s", element.getLocalName());
80
81         final NodeList revisions = element.getElementsByTagNameNS(REVISION_STMT.getNamespace().toString(),
82             REVISION_STMT.getLocalName());
83         if (revisions.getLength() == 0) {
84             // FIXME: is module name important (as that may have changed)
85             return new Simple(identifier, source, symbolicName);
86         }
87
88         final Element revisionStmt = (Element) revisions.item(0);
89         final Attr dateAttr = revisionStmt.getAttributeNode(REVISION_ARG);
90         checkArgument(dateAttr != null, "No revision statement argument found in %s", revisionStmt);
91
92         final SourceIdentifier parsedId = RevisionSourceIdentifier.create(nameAttr.getValue(),
93             Revision.of(dateAttr.getValue()));
94         final SourceIdentifier id;
95         if (!parsedId.equals(identifier)) {
96             LOG.debug("Changed identifier from {} to {}", identifier, parsedId);
97             id = parsedId;
98         } else {
99             id = identifier;
100         }
101
102         return new Simple(id, source, symbolicName);
103     }
104
105     /**
106      * Create a {@link YinDomSchemaSource} from a {@link YinXmlSchemaSource}. If the argument is already a
107      * YinDomSchemaSource, this method returns the same instance. The source will be translated on first access,
108      * at which point an {@link IllegalStateException} may be raised.
109      *
110      * @param xmlSchemaSource Backing schema source
111      * @return A {@link YinDomSchemaSource} instance
112      */
113     public static @NonNull YinDomSchemaSource lazyTransform(final YinXmlSchemaSource xmlSchemaSource) {
114         final YinDomSchemaSource cast = castSchemaSource(xmlSchemaSource);
115         return cast != null ? cast : new Transforming(xmlSchemaSource);
116     }
117
118     /**
119      * Create a {@link YinDomSchemaSource} from a {@link YinXmlSchemaSource}. If the argument is already a
120      * YinDomSchemaSource, this method returns the same instance. The source will be translated immediately.
121      *
122      * @param xmlSchemaSource Backing schema source
123      * @return A {@link YinDomSchemaSource} instance
124      * @throws TransformerException when the provided source fails to transform
125      */
126     public static @NonNull YinDomSchemaSource transform(final YinXmlSchemaSource xmlSchemaSource)
127             throws TransformerException {
128         final YinDomSchemaSource cast = castSchemaSource(xmlSchemaSource);
129         return cast != null ? cast :
130             create(xmlSchemaSource.getIdentifier(), transformSource(xmlSchemaSource.getSource()),
131                 xmlSchemaSource.getSymbolicName().orElse(null));
132     }
133
134     @Override
135     public abstract DOMSource getSource();
136
137     @Override
138     public final Class<? extends YinXmlSchemaSource> getType() {
139         return YinDomSchemaSource.class;
140     }
141
142     @Override
143     public final String toString() {
144         return addToStringAttributes(MoreObjects.toStringHelper(this).add("identifier", getIdentifier())).toString();
145     }
146
147     /**
148      * Add subclass-specific attributes to the output {@link #toString()} output. Since
149      * subclasses are prevented from overriding {@link #toString()} for consistency
150      * reasons, they can add their specific attributes to the resulting string by attaching
151      * attributes to the supplied {@link ToStringHelper}.
152      *
153      * @param toStringHelper ToStringHelper onto the attributes can be added
154      * @return ToStringHelper supplied as input argument.
155      */
156     protected abstract ToStringHelper addToStringAttributes(ToStringHelper toStringHelper);
157
158     static @NonNull DOMSource transformSource(final Source source) throws TransformerException {
159         final DOMResult result = new DOMResult();
160         TRANSFORMER_FACTORY.newTransformer().transform(source, result);
161
162         return new DOMSource(result.getNode(), result.getSystemId());
163     }
164
165     private static @Nullable YinDomSchemaSource castSchemaSource(final YinXmlSchemaSource xmlSchemaSource) {
166         if (xmlSchemaSource instanceof YinDomSchemaSource) {
167             return (YinDomSchemaSource) xmlSchemaSource;
168         }
169
170         final Source source = xmlSchemaSource.getSource();
171         if (source instanceof DOMSource) {
172             return create(xmlSchemaSource.getIdentifier(), (DOMSource) source,
173                 xmlSchemaSource.getSymbolicName().orElse(null));
174         }
175
176         return null;
177     }
178
179     private static final class Simple extends YinDomSchemaSource {
180         private final @NonNull SourceIdentifier identifier;
181         private final @NonNull DOMSource source;
182         private final String symbolicName;
183
184         Simple(final @NonNull SourceIdentifier identifier, final @NonNull DOMSource source,
185                 final @Nullable String symbolicName) {
186             this.identifier = requireNonNull(identifier);
187             this.source = requireNonNull(source);
188             this.symbolicName = symbolicName;
189         }
190
191         @Override
192         public DOMSource getSource() {
193             return source;
194         }
195
196         @Override
197         public SourceIdentifier getIdentifier() {
198             return identifier;
199         }
200
201         @Override
202         public Optional<String> getSymbolicName() {
203             return Optional.ofNullable(symbolicName);
204         }
205
206         @Override
207         protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
208             return toStringHelper.add("source", source);
209         }
210     }
211
212     private static final class Transforming extends YinDomSchemaSource {
213         private final YinXmlSchemaSource xmlSchemaSource;
214         private volatile DOMSource source;
215
216         Transforming(final YinXmlSchemaSource xmlSchemaSource) {
217             this.xmlSchemaSource = requireNonNull(xmlSchemaSource);
218         }
219
220         @Override
221         public DOMSource getSource() {
222             DOMSource ret = source;
223             if (ret == null) {
224                 synchronized (this) {
225                     ret = source;
226                     if (ret == null) {
227                         try {
228                             ret = transformSource(xmlSchemaSource.getSource());
229                         } catch (TransformerException e) {
230                             throw new IllegalStateException("Failed to transform schema source " + xmlSchemaSource, e);
231                         }
232                         source = ret;
233                     }
234                 }
235             }
236
237             return ret;
238         }
239
240         @Override
241         public SourceIdentifier getIdentifier() {
242             return xmlSchemaSource.getIdentifier();
243         }
244
245         @Override
246         public Optional<String> getSymbolicName() {
247             return xmlSchemaSource.getSymbolicName();
248         }
249
250         @Override
251         protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
252             return toStringHelper.add("xmlSchemaSource", xmlSchemaSource);
253         }
254     }
255 }