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