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