QName namespace is always non-null
[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 java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.Interner;
13 import com.google.common.collect.Interners;
14 import java.io.DataInput;
15 import java.io.DataOutput;
16 import java.io.IOException;
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 org.checkerframework.checker.regex.qual.Regex;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.eclipse.jdt.annotation.Nullable;
26
27 /**
28  * The QName from XML consists of local name of element and XML namespace, but for our use, we added module revision to
29  * it.
30  *
31  * <p>
32  * In YANG context QName is full name of defined node, type, procedure or notification. QName consists of XML namespace,
33  * YANG model revision and local name of defined type. It is used to prevent name clashes between nodes with same local
34  * name, but from different schemas.
35  *
36  * <p>
37  * The local name must conform to <a href="https://tools.ietf.org/html/rfc7950#section-6.2">RFC7950 Section 6.2</a>.
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 public final class QName extends AbstractQName implements Comparable<QName> {
49     private static final Interner<QName> INTERNER = Interners.newWeakInterner();
50     // Note: 5398411242927766414L is used for versions < 3.0.0 without writeReplace
51     private static final long serialVersionUID = 1L;
52
53     static final String QNAME_REVISION_DELIMITER = "?revision=";
54     static final String QNAME_LEFT_PARENTHESIS = "(";
55     static final String QNAME_RIGHT_PARENTHESIS = ")";
56
57     @Regex
58     private static final String QNAME_STRING_FULL = "^\\((.+)\\?revision=(.+)\\)(.+)$";
59     private static final Pattern QNAME_PATTERN_FULL = Pattern.compile(QNAME_STRING_FULL);
60
61     @Regex
62     private static final String QNAME_STRING_NO_REVISION = "^\\((.+)\\)(.+)$";
63     private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile(QNAME_STRING_NO_REVISION);
64
65     private final @NonNull QNameModule module;
66     private transient int hash = 0;
67
68     QName(final QNameModule module, final @NonNull String localName) {
69         super(localName);
70         this.module = requireNonNull(module);
71     }
72
73     /**
74      * QName Constructor.
75      *
76      * @param namespace
77      *            the namespace assigned to the YANG module
78      * @param localName
79      *            YANG schema identifier
80      */
81     private QName(final URI namespace, final String localName) {
82         this(QNameModule.create(namespace), checkLocalName(localName));
83     }
84
85     public static @NonNull QName create(final String input) {
86         Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
87         if (matcher.matches()) {
88             final String namespace = matcher.group(1);
89             final String revision = matcher.group(2);
90             final String localName = matcher.group(3);
91             return create(namespace, revision, localName);
92         }
93         matcher = QNAME_PATTERN_NO_REVISION.matcher(input);
94         if (matcher.matches()) {
95             final URI namespace = URI.create(matcher.group(1));
96             final String localName = matcher.group(2);
97             return new QName(namespace, localName);
98         }
99         throw new IllegalArgumentException("Invalid input: " + input);
100     }
101
102     public static @NonNull QName create(final QName base, final String localName) {
103         return create(base.getModule(), localName);
104     }
105
106     /**
107      * Creates new QName.
108      *
109      * @param qnameModule
110      *            Namespace and revision enclosed as a QNameModule
111      * @param localName
112      *            Local name part of QName. MUST NOT BE null.
113      * @return Instance of QName
114      */
115     public static @NonNull QName create(final QNameModule qnameModule, final String localName) {
116         return new QName(requireNonNull(qnameModule, "module may not be null"), checkLocalName(localName));
117     }
118
119     /**
120      * Creates new QName.
121      *
122      * @param namespace Namespace of QName or null if namespace is undefined.
123      * @param revision Revision of namespace or null if revision is unspecified.
124      * @param localName Local name part of QName. MUST NOT BE null.
125      * @return Instance of QName
126      */
127     public static @NonNull QName create(final URI namespace, final @Nullable Revision revision,
128             final String localName) {
129         return create(QNameModule.create(namespace, revision), localName);
130     }
131
132     /**
133      * Creates new QName.
134      *
135      * @param namespace Namespace of QName or null if namespace is undefined.
136      * @param revision Revision of namespace.
137      * @param localName Local name part of QName. MUST NOT BE null.
138      * @return Instance of QName
139      */
140     public static @NonNull QName create(final URI namespace, final Optional<Revision> revision,
141             final String localName) {
142         return create(QNameModule.create(namespace, revision), localName);
143     }
144
145     /**
146      * Creates new QName.
147      *
148      * @param namespace Namespace of QName or null if namespace is undefined.
149      * @param revision Revision of namespace or null if revision is unspecified.
150      * @param localName Local name part of QName. MUST NOT BE null.
151      * @return Instance of QName
152      */
153     public static @NonNull QName create(final String namespace, final String localName, final Revision revision) {
154         return create(QNameModule.create(parseNamespace(namespace), revision), localName);
155     }
156
157     /**
158      * Creates new QName.
159      *
160      * @param namespace Namespace of QName, MUST NOT BE Null.
161      * @param revision Revision of namespace / YANG module. MUST NOT BE null, MUST BE in format {@code YYYY-mm-dd}.
162      * @param localName Local name part of QName. MUST NOT BE null.
163      * @return A new QName
164      * @throws NullPointerException If any of parameters is null.
165      * @throws IllegalArgumentException If {@code namespace} is not valid URI or {@code revision} does not conform
166      *         to {@code YYYY-mm-dd}.
167      */
168     public static @NonNull QName create(final String namespace, final String revision, final String localName) {
169         return create(parseNamespace(namespace), Revision.of(revision), localName);
170     }
171
172     /**
173      * Creates new QName.
174      *
175      * @param namespace Namespace of QName, MUST NOT BE Null.
176      * @param localName Local name part of QName. MUST NOT BE null.
177      * @return A new QName
178      * @throws NullPointerException If any of parameters is null.
179      * @throws IllegalArgumentException If {@code namespace} is not valid URI.
180      */
181     public static @NonNull QName create(final String namespace, final String localName) {
182         return create(parseNamespace(namespace), localName);
183     }
184
185     /**
186      * Creates new QName.
187      *
188      * @param namespace Namespace of QName, MUST NOT BE null.
189      * @param localName Local name part of QName. MUST NOT BE null.
190      * @return A new QName
191      * @throws NullPointerException If any of parameters is null.
192      * @throws IllegalArgumentException If <code>namespace</code> is not valid URI.
193      */
194     public static @NonNull QName create(final URI namespace, final String localName) {
195         return new QName(namespace, localName);
196     }
197
198     /**
199      * Read a QName from a DataInput. The format is expected to match the output format of {@link #writeTo(DataOutput)}.
200      *
201      * @param in DataInput to read
202      * @return A QName instance
203      * @throws IOException if I/O error occurs
204      */
205     public static @NonNull QName readFrom(final DataInput in) throws IOException {
206         final QNameModule module = QNameModule.readFrom(in);
207         return new QName(module, checkLocalName(in.readUTF()));
208     }
209
210     /**
211      * Get the module component of the QName.
212      *
213      * @return Module component
214      */
215     public @NonNull QNameModule getModule() {
216         return module;
217     }
218
219     /**
220      * Returns XMLNamespace assigned to the YANG module.
221      *
222      * @return XMLNamespace assigned to the YANG module.
223      */
224     public @NonNull URI getNamespace() {
225         return module.getNamespace();
226     }
227
228     /**
229      * Returns revision of the YANG module if the module has defined revision.
230      *
231      * @return revision of the YANG module if the module has defined revision.
232      */
233     public @NonNull Optional<Revision> getRevision() {
234         return module.getRevision();
235     }
236
237     @Override
238     public @NonNull QName intern() {
239         // We also want to make sure we keep the QNameModule cached
240         final QNameModule cacheMod = module.intern();
241
242         // Identity comparison is here on purpose, as we are deciding whether to potentially store 'qname' into the
243         // interner. It is important that it does not hold user-supplied reference (such a String instance from
244         // parsing of an XML document).
245         final QName template = cacheMod == module ? this : new QName(cacheMod, getLocalName().intern());
246
247         return INTERNER.intern(template);
248     }
249
250     @Override
251     public int hashCode() {
252         if (hash == 0) {
253             hash = Objects.hash(module, getLocalName());
254         }
255         return hash;
256     }
257
258     /**
259      * Compares the specified object with this list for equality.  Returns {@code true} if and only if the specified
260      * object is also instance of {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
261      * {@link #getRevision()} are equals to same properties of this instance.
262      *
263      * @param obj the object to be compared for equality with this QName
264      * @return {@code true} if the specified object is equal to this QName
265      */
266     @Override
267     public boolean equals(final Object obj) {
268         if (this == obj) {
269             return true;
270         }
271         if (!(obj instanceof QName)) {
272             return false;
273         }
274         final QName other = (QName) obj;
275         return Objects.equals(getLocalName(), other.getLocalName()) && module.equals(other.module);
276     }
277
278     private static @NonNull URI parseNamespace(final String namespace) {
279         try {
280             return new URI(namespace);
281         } catch (final URISyntaxException ue) {
282             throw new IllegalArgumentException("Namespace '" + namespace + "' is not a valid URI", ue);
283         }
284     }
285
286     @Override
287     public @NonNull String toString() {
288         final StringBuilder sb = new StringBuilder().append(QNAME_LEFT_PARENTHESIS).append(getNamespace());
289         final Optional<Revision> rev = getRevision();
290         if (rev.isPresent()) {
291             sb.append(QNAME_REVISION_DELIMITER).append(rev.get());
292         }
293         return sb.append(QNAME_RIGHT_PARENTHESIS).append(getLocalName()).toString();
294     }
295
296     /**
297      * Returns a QName with the specified QNameModule and the same localname as this one.
298      *
299      * @param newModule New QNameModule to use
300      * @return a QName with specified QNameModule and same local name as this one
301      */
302     public @NonNull QName withModule(final QNameModule newModule) {
303         return new QName(newModule, getLocalName());
304     }
305
306     /**
307      * Returns a QName with the same namespace and local name, but with no revision. If this QName does not have
308      * a Revision, this object is returned.
309      *
310      * @return a QName with the same namespace and local name, but with no revision.
311      */
312     public @NonNull QName withoutRevision() {
313         final QNameModule newModule;
314         return (newModule = module.withoutRevision()) == module ? this : new QName(newModule, getLocalName());
315     }
316
317     /**
318      * Formats {@link Revision} representing revision to format {@code YYYY-mm-dd}
319      *
320      * <p>
321      * YANG Specification defines format for {@code revision<} as YYYY-mm-dd. This format for revision is reused across
322      * multiple places such as capabilities URI, YANG modules, etc.
323      *
324      * @param revision Date object to format
325      * @return String representation or null if the input was null.
326      */
327     public static @Nullable String formattedRevision(final Optional<Revision> revision) {
328         return revision.map(Revision::toString).orElse(null);
329     }
330
331     /**
332      * Compares this QName to other, without comparing revision.
333      *
334      * <p>
335      * Compares instance of this to other instance of QName and returns true if both instances have equal
336      * {@code localName} ({@link #getLocalName()}) and @{code namespace} ({@link #getNamespace()}).
337      *
338      * @param other Other QName. Must not be null.
339      * @return true if this instance and other have equals localName and namespace.
340      * @throws NullPointerException if {@code other} is null.
341      */
342     public boolean isEqualWithoutRevision(final QName other) {
343         return getLocalName().equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
344     }
345
346     // FIXME: this comparison function looks odd. We are sorting first by local name and then by module? What is
347     //        the impact on iteration order of SortedMap<QName, ?>?
348     @Override
349     @SuppressWarnings("checkstyle:parameterName")
350     public int compareTo(final QName o) {
351         // compare mandatory localName parameter
352         int result = getLocalName().compareTo(o.getLocalName());
353         if (result != 0) {
354             return result;
355         }
356         return module.compareTo(o.module);
357     }
358
359     @Override
360     public void writeTo(final DataOutput out) throws IOException {
361         module.writeTo(out);
362         out.writeUTF(getLocalName());
363     }
364
365     @Override
366     Object writeReplace() {
367         return new QNv1(this);
368     }
369 }