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