Revert "Revert "Bug 3874: Support of yang modeled AnyXML - API""
[yangtools.git] / yang / yang-common / src / main / java / org / opendaylight / yangtools / yang / common / QName.java
1 /*
2  * Copyright (c) 2013 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.common;
9
10 import static org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil.getRevisionFormat;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Interner;
13 import com.google.common.collect.Interners;
14 import java.io.Serializable;
15 import java.net.URI;
16 import java.net.URISyntaxException;
17 import java.text.ParseException;
18 import java.util.Date;
19 import java.util.Objects;
20 import java.util.regex.Matcher;
21 import java.util.regex.Pattern;
22 import org.opendaylight.yangtools.concepts.Immutable;
23 import org.opendaylight.yangtools.objcache.ObjectCache;
24 import org.opendaylight.yangtools.objcache.ObjectCacheFactory;
25
26 /**
27  * The QName from XML consists of local name of element and XML namespace, but
28  * for our use, we added module revision to it.
29  *
30  * In YANG context QName is full name of defined node, type, procedure or
31  * notification. QName consists of XML namespace, YANG model revision and local
32  * name of defined type. It is used to prevent name clashes between nodes with
33  * same local name, but from different schemas.
34  *
35  * <ul>
36  * <li><b>XMLNamespace</b> - {@link #getNamespace()} - the namespace assigned to the YANG module which
37  * defined element, type, procedure or notification.</li>
38  * <li><b>Revision</b> - {@link #getRevision()} - the revision of the YANG module which describes the
39  * element</li>
40  * <li><b>LocalName</b> - {@link #getLocalName()} - the YANG schema identifier which were defined for this
41  * node in the YANG module</li>
42  * </ul>
43  *
44  * QName may also have <code>prefix</code> assigned, but prefix does not
45  * affect equality and identity of two QNames and carry only information
46  * which may be useful for serializers / deserializers.
47  *
48  *
49  */
50 public final class QName implements Immutable, Serializable, Comparable<QName> {
51     private static final Interner<QName> INTERNER = Interners.newWeakInterner();
52     private static final ObjectCache CACHE = ObjectCacheFactory.getObjectCache(QName.class);
53     private static final long serialVersionUID = 5398411242927766414L;
54
55     static final String QNAME_REVISION_DELIMITER = "?revision=";
56     static final String QNAME_LEFT_PARENTHESIS = "(";
57     static final String QNAME_RIGHT_PARENTHESIS = ")";
58
59     private static final Pattern QNAME_PATTERN_FULL = Pattern.compile("^\\((.+)\\" + QNAME_REVISION_DELIMITER
60             + "(.+)\\)(.+)$");
61     private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile("^\\((.+)\\)(.+)$");
62     private static final Pattern QNAME_PATTERN_NO_NAMESPACE_NO_REVISION = Pattern.compile("^(.+)$");
63     private static final char[] ILLEGAL_CHARACTERS = new char[] { '?', '(', ')', '&' };
64
65     // Mandatory
66     private final QNameModule module;
67     // Mandatory
68     private final String localName;
69
70     private QName(final QNameModule module, final String localName) {
71         this.localName = checkLocalName(localName);
72         this.module = module;
73     }
74
75     /**
76      * Look up specified QName in the global cache and return a shared reference.
77      *
78      * @param qname QName instance
79      * @return Cached instance, according to {@link ObjectCache} policy.
80      *
81      * @deprecated Use {@link #intern()} instead.
82      */
83     @Deprecated
84     public static QName cachedReference(final QName qname) {
85         // We also want to make sure we keep the QNameModule cached
86         final QNameModule myMod = qname.getModule();
87         final QNameModule cacheMod = QNameModule.cachedReference(myMod);
88
89         final QName what;
90         // Identity comparison is here on purpose, as we are deciding whether to potentially store 'qname'
91         // into cache. It is important that it does not hold user-supplied reference (such a String instance from
92         // XML parser.
93         if (cacheMod == myMod) {
94             what = qname;
95         } else {
96             what = QName.create(cacheMod, qname.localName);
97         }
98
99         return CACHE.getReference(what);
100     }
101
102     /**
103      * QName Constructor.
104      *
105      * @param namespace
106      *            the namespace assigned to the YANG module
107      * @param localName
108      *            YANG schema identifier
109      */
110     public QName(final URI namespace, final String localName) {
111         this(QNameModule.create(namespace, null), localName);
112     }
113
114     private static String checkLocalName(final String localName) {
115         if (localName == null) {
116             throw new IllegalArgumentException("Parameter 'localName' may not be null.");
117         }
118         if (localName.length() == 0) {
119             throw new IllegalArgumentException("Parameter 'localName' must be a non-empty string.");
120         }
121
122         for (final char c : ILLEGAL_CHARACTERS) {
123             if (localName.indexOf(c) != -1) {
124                 throw new IllegalArgumentException(String.format(
125                         "Parameter 'localName':'%s' contains illegal character '%s'", localName, c));
126             }
127         }
128         return localName;
129     }
130
131     public static QName create(final String input) {
132         Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
133         if (matcher.matches()) {
134             final String namespace = matcher.group(1);
135             final String revision = matcher.group(2);
136             final String localName = matcher.group(3);
137             return create(namespace, revision, localName);
138         }
139         matcher = QNAME_PATTERN_NO_REVISION.matcher(input);
140         if (matcher.matches()) {
141             final URI namespace = URI.create(matcher.group(1));
142             final String localName = matcher.group(2);
143             return new QName(namespace, localName);
144         }
145         matcher = QNAME_PATTERN_NO_NAMESPACE_NO_REVISION.matcher(input);
146         if (matcher.matches()) {
147             final String localName = matcher.group(1);
148             return new QName((URI) null, localName);
149         }
150         throw new IllegalArgumentException("Invalid input:" + input);
151     }
152
153     /**
154      * Get the module component of the QName.
155      *
156      * @return Module component
157      */
158     public QNameModule getModule() {
159         return module;
160     }
161
162     /**
163      * Returns XMLNamespace assigned to the YANG module.
164      *
165      * @return XMLNamespace assigned to the YANG module.
166      */
167     public URI getNamespace() {
168         return module.getNamespace();
169     }
170
171     /**
172      * Returns YANG schema identifier which were defined for this node in the
173      * YANG module
174      *
175      * @return YANG schema identifier which were defined for this node in the
176      *         YANG module
177      */
178     public String getLocalName() {
179         return localName;
180     }
181
182     /**
183      * Returns revision of the YANG module if the module has defined revision,
184      * otherwise returns <code>null</code>
185      *
186      * @return revision of the YANG module if the module has defined revision,
187      *         otherwise returns <code>null</code>
188      */
189     public Date getRevision() {
190         return module.getRevision();
191     }
192
193     /**
194      * Return an interned reference to a equivalent QName.
195      *
196      * @return Interned reference, or this object if it was interned.
197      */
198     public QName intern() {
199         // We also want to make sure we keep the QNameModule cached
200         final QNameModule cacheMod = module.intern();
201
202         // Identity comparison is here on purpose, as we are deciding whether to potentially store 'qname' into the
203         // interner. It is important that it does not hold user-supplied reference (such a String instance from
204         // parsing of an XML document).
205         final QName template = cacheMod == module ? this : QName.create(cacheMod, localName);
206
207         return INTERNER.intern(template);
208     }
209
210     @Override
211     public int hashCode() {
212         final int prime = 31;
213         int result = 1;
214         result = prime * result + Objects.hashCode(localName);
215         result = prime * result + module.hashCode();
216         return result;
217     }
218
219     /**
220      *
221      * Compares the specified object with this list for equality.  Returns
222      * <tt>true</tt> if and only if the specified object is also instance of
223      * {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
224      * {@link #getRevision()} are equals to same properties of this instance.
225      *
226      * @param obj the object to be compared for equality with this QName
227      * @return <tt>true</tt> if the specified object is equal to this QName
228      *
229      */
230     @Override
231     public boolean equals(final Object obj) {
232         if (this == obj) {
233             return true;
234         }
235         if (!(obj instanceof QName)) {
236             return false;
237         }
238         final QName other = (QName) obj;
239         return Objects.equals(localName, other.localName) && module.equals(other.module);
240     }
241
242     public static QName create(final QName base, final String localName) {
243         return create(base.getModule(), localName);
244     }
245
246     /**
247      * Creates new QName.
248      *
249      * @param qnameModule
250      *            Namespace and revision enclosed as a QNameModule
251      * @param localName
252      *            Local name part of QName. MUST NOT BE null.
253      * @return Instance of QName
254      */
255     public static QName create(final QNameModule qnameModule, final String localName) {
256         return new QName(Preconditions.checkNotNull(qnameModule,"module may not be null"), localName);
257     }
258
259     /**
260      * Creates new QName.
261      *
262      * @param namespace
263      *            Namespace of QName or null if namespace is undefined.
264      * @param revision
265      *            Revision of namespace or null if revision is unspecified.
266      * @param localName
267      *            Local name part of QName. MUST NOT BE null.
268      * @return Instance of QName
269      */
270     public static QName create(final URI namespace, final Date revision, final String localName) {
271         return create(QNameModule.create(namespace, revision), localName);
272     }
273
274     /**
275      *
276      * Creates new QName.
277      *
278      * @param namespace
279      *            Namespace of QName, MUST NOT BE Null.
280      * @param revision
281      *            Revision of namespace / YANG module. MUST NOT BE null, MUST BE
282      *            in format <code>YYYY-mm-dd</code>.
283      * @param localName
284      *            Local name part of QName. MUST NOT BE null.
285      * @return
286      * @throws NullPointerException
287      *             If any of parameters is null.
288      * @throws IllegalArgumentException
289      *             If <code>namespace</code> is not valid URI or
290      *             <code>revision</code> is not according to format
291      *             <code>YYYY-mm-dd</code>.
292      */
293     public static QName create(final String namespace, final String revision, final String localName) {
294         final URI namespaceUri = parseNamespace(namespace);
295         final Date revisionDate = parseRevision(revision);
296         return create(namespaceUri, revisionDate, localName);
297     }
298
299     private static URI parseNamespace(final String namespace) {
300         try {
301             return new URI(namespace);
302         } catch (final URISyntaxException ue) {
303             throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
304         }
305     }
306
307     /**
308      * Creates new QName.
309      *
310      * @param namespace
311      *            Namespace of QName, MUST NOT BE Null.
312      * @param localName
313      *            Local name part of QName. MUST NOT BE null.
314      * @return
315      * @throws NullPointerException
316      *             If any of parameters is null.
317      * @throws IllegalArgumentException
318      *             If <code>namespace</code> is not valid URI.
319      */
320     public static QName create(final String namespace, final String localName) {
321         return create(parseNamespace(namespace), null, localName);
322     }
323
324     @Override
325     public String toString() {
326         final StringBuilder sb = new StringBuilder();
327         if (getNamespace() != null) {
328             sb.append(QNAME_LEFT_PARENTHESIS + getNamespace());
329
330             if (getFormattedRevision() != null) {
331                 sb.append(QNAME_REVISION_DELIMITER + getFormattedRevision());
332             }
333             sb.append(QNAME_RIGHT_PARENTHESIS);
334         }
335         sb.append(localName);
336         return sb.toString();
337     }
338
339     /**
340      * Return string representation of revision in format
341      * <code>YYYY-mm-dd</code>
342      *
343      * YANG Specification defines format for <code>revision</code> as
344      * YYYY-mm-dd. This format for revision is reused accross multiple places
345      * such as capabilities URI, YANG modules, etc.
346      *
347      * @return String representation of revision or null, if revision is not
348      *         set.
349      */
350     public String getFormattedRevision() {
351         return module.getFormattedRevision();
352     }
353
354     /**
355      * Creates copy of this with revision and prefix unset.
356      *
357      * @return copy of this QName with revision and prefix unset.
358      */
359     public QName withoutRevision() {
360         return create(getNamespace(), null, localName);
361     }
362
363     public static Date parseRevision(final String formatedDate) {
364         try {
365             return getRevisionFormat().parse(formatedDate);
366         } catch (ParseException | RuntimeException e) {
367             throw new IllegalArgumentException(
368                     String.format("Revision '%s'is not in a supported format", formatedDate), e);
369         }
370     }
371
372     /**
373      * Formats {@link Date} representing revision to format
374      * <code>YYYY-mm-dd</code>
375      *
376      * YANG Specification defines format for <code>revision</code> as
377      * YYYY-mm-dd. This format for revision is reused accross multiple places
378      * such as capabilities URI, YANG modules, etc.
379      *
380      * @param revision
381      *            Date object to format or null
382      * @return String representation or null if the input was null.
383      */
384     public static String formattedRevision(final Date revision) {
385         if (revision == null) {
386             return null;
387         }
388         return getRevisionFormat().format(revision);
389     }
390
391     /**
392      *
393      * Compares this QName to other, without comparing revision.
394      *
395      * Compares instance of this to other instance of QName and returns true if
396      * both instances have equal <code>localName</code> ({@link #getLocalName()}
397      * ) and <code>namespace</code> ({@link #getNamespace()}).
398      *
399      * @param other
400      *            Other QName. Must not be null.
401      * @return true if this instance and other have equals localName and
402      *         namespace.
403      * @throws NullPointerException
404      *             if <code>other</code> is null.
405      */
406     public boolean isEqualWithoutRevision(final QName other) {
407         return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
408     }
409
410     @Override
411     public int compareTo(final QName other) {
412         // compare mandatory localName parameter
413         int result = localName.compareTo(other.localName);
414         if (result != 0) {
415             return result;
416         }
417
418         // compare nullable namespace parameter
419         if (getNamespace() == null) {
420             if (other.getNamespace() != null) {
421                 return -1;
422             }
423         } else {
424             if (other.getNamespace() == null) {
425                 return 1;
426             }
427             result = getNamespace().compareTo(other.getNamespace());
428             if (result != 0) {
429                 return result;
430             }
431         }
432
433         // compare nullable revision parameter
434         if (getRevision() == null) {
435             if (other.getRevision() != null) {
436                 return -1;
437             }
438         } else {
439             if (other.getRevision() == null) {
440                 return 1;
441             }
442             result = getRevision().compareTo(other.getRevision());
443             if (result != 0) {
444                 return result;
445             }
446         }
447
448         return result;
449     }
450
451 }