Use RevisionUnion in QNameModule
[yangtools.git] / common / 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.annotations.Beta;
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.Serial;
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://www.rfc-editor.org/rfc/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     @Serial
52     private static final long serialVersionUID = 1L;
53
54     @Regex
55     private static final String QNAME_STRING_FULL = "^\\((.+)\\?revision=(.+)\\)(.+)$";
56     private static final Pattern QNAME_PATTERN_FULL = Pattern.compile(QNAME_STRING_FULL);
57
58     @Regex
59     private static final String QNAME_STRING_NO_REVISION = "^\\((.+)\\)(.+)$";
60     private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile(QNAME_STRING_NO_REVISION);
61
62     private final @NonNull QNameModule module;
63     private transient int hash = 0;
64
65     QName(final QNameModule module, final @NonNull String localName) {
66         super(localName);
67         this.module = requireNonNull(module);
68     }
69
70     /**
71      * QName Constructor.
72      *
73      * @param namespace
74      *            the namespace assigned to the YANG module
75      * @param localName
76      *            YANG schema identifier
77      */
78     private QName(final XMLNamespace namespace, final String localName) {
79         this(QNameModule.of(namespace), checkLocalName(localName));
80     }
81
82     public static @NonNull QName create(final String input) {
83         Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
84         if (matcher.matches()) {
85             final String namespace = matcher.group(1);
86             final String revision = matcher.group(2);
87             final String localName = matcher.group(3);
88             return create(namespace, revision, localName);
89         }
90         matcher = QNAME_PATTERN_NO_REVISION.matcher(input);
91         if (matcher.matches()) {
92             final XMLNamespace namespace = XMLNamespace.of(matcher.group(1));
93             final String localName = matcher.group(2);
94             return new QName(namespace, localName);
95         }
96         throw new IllegalArgumentException("Invalid input: " + input);
97     }
98
99     public static @NonNull QName create(final QName base, final String localName) {
100         return create(base.getModule(), localName);
101     }
102
103     /**
104      * Creates new QName.
105      *
106      * @param qnameModule Namespace and revision enclosed as a QNameModule
107      * @param localName Local name part of QName. MUST NOT BE null.
108      * @return Instance of QName
109      * @throws NullPointerException if any argument is null
110      * @throws IllegalArgumentException if localName is not a valid YANG identifier
111      */
112     public static @NonNull QName create(final QNameModule qnameModule, final String localName) {
113         return new QName(requireNonNull(qnameModule, "module may not be null"), checkLocalName(localName));
114     }
115
116     /**
117      * Creates new QName.
118      *
119      * @param namespace Namespace of QName or null if namespace is undefined.
120      * @param revision Revision of namespace or null if revision is unspecified.
121      * @param localName Local name part of QName. MUST NOT BE null.
122      * @return Instance of QName
123      */
124     public static @NonNull QName create(final XMLNamespace namespace, final @Nullable Revision revision,
125             final String localName) {
126         return create(QNameModule.ofRevision(namespace, revision), localName);
127     }
128
129     /**
130      * Creates new QName.
131      *
132      * @param namespace Namespace of QName or null if namespace is undefined.
133      * @param revision Revision of namespace.
134      * @param localName Local name part of QName. MUST NOT BE null.
135      * @return Instance of QName
136      */
137     public static @NonNull QName create(final XMLNamespace namespace, final Optional<Revision> revision,
138             final String localName) {
139         return create(QNameModule.ofRevision(namespace, revision.orElse(null)), localName);
140     }
141
142     /**
143      * Creates new QName.
144      *
145      * @param namespace Namespace of QName or null if namespace is undefined.
146      * @param revision Revision of namespace or null if revision is unspecified.
147      * @param localName Local name part of QName. MUST NOT BE null.
148      * @return Instance of QName
149      */
150     public static @NonNull QName create(final String namespace, final String localName, final Revision revision) {
151         return create(QNameModule.of(XMLNamespace.of(namespace), revision), localName);
152     }
153
154     /**
155      * Creates new QName.
156      *
157      * @param namespace Namespace of QName, MUST NOT BE Null.
158      * @param revision Revision of namespace / YANG module. MUST NOT BE null, MUST BE in format {@code YYYY-mm-dd}.
159      * @param localName Local name part of QName. MUST NOT BE null.
160      * @return A new QName
161      * @throws NullPointerException If any of parameters is null.
162      * @throws IllegalArgumentException If {@code namespace} is not valid URI or {@code revision} does not conform
163      *         to {@code YYYY-mm-dd}.
164      */
165     public static @NonNull QName create(final String namespace, final String revision, final String localName) {
166         return create(QNameModule.ofRevision(namespace, revision), localName);
167     }
168
169     /**
170      * Creates new QName.
171      *
172      * @param namespace Namespace of QName, MUST NOT BE Null.
173      * @param localName Local name part of QName. MUST NOT BE null.
174      * @return A new QName
175      * @throws NullPointerException If any of parameters is null.
176      * @throws IllegalArgumentException If {@code namespace} is not valid URI.
177      */
178     public static @NonNull QName create(final String namespace, final String localName) {
179         return create(XMLNamespace.of(namespace), localName);
180     }
181
182     /**
183      * Creates new QName.
184      *
185      * @param namespace Namespace of QName, MUST NOT BE null.
186      * @param localName Local name part of QName. MUST NOT BE null.
187      * @return A new QName
188      * @throws NullPointerException If any of parameters is null.
189      * @throws IllegalArgumentException If <code>namespace</code> is not valid URI.
190      */
191     public static @NonNull QName create(final XMLNamespace namespace, final String localName) {
192         return new QName(namespace, localName);
193     }
194
195     /**
196      * Read a QName from a DataInput. The format is expected to match the output format of {@link #writeTo(DataOutput)}.
197      *
198      * @param in DataInput to read
199      * @return A QName instance
200      * @throws IOException if I/O error occurs
201      */
202     public static @NonNull QName readFrom(final DataInput in) throws IOException {
203         if (in instanceof QNameAwareDataInput aware) {
204             return aware.readQName();
205         }
206
207         final var module = QNameModule.readFrom(in);
208         return new QName(module, checkLocalName(in.readUTF()));
209     }
210
211     /**
212      * Creates new QName composed of specified module and local name. This method does not perform lexical checking of
213      * localName, and it is the caller's responsibility to performs these checks.
214      *
215      * <p>
216      * When in doubt, use {@link #create(QNameModule, String)} instead.
217      *
218      * @param qnameModule Namespace and revision enclosed as a QNameModule
219      * @param localName Local name part of QName, required to have been validated
220      * @return Instance of QName
221      * @throws NullPointerException if any of the arguments is null
222      */
223     @Beta
224     public static @NonNull QName unsafeOf(final @NonNull QNameModule qnameModule, final @NonNull String localName) {
225         return new QName(qnameModule, localName);
226     }
227
228     /**
229      * Get the module component of the QName.
230      *
231      * @return Module component
232      */
233     public @NonNull QNameModule getModule() {
234         return module;
235     }
236
237     /**
238      * Returns XMLNamespace assigned to the YANG module.
239      *
240      * @return XMLNamespace assigned to the YANG module.
241      */
242     public @NonNull XMLNamespace getNamespace() {
243         return module.namespace();
244     }
245
246     /**
247      * Returns revision of the YANG module if the module has defined revision.
248      *
249      * @return revision of the YANG module if the module has defined revision.
250      */
251     public @NonNull Optional<Revision> getRevision() {
252         return module.findRevision();
253     }
254
255     @Override
256     public @NonNull QName intern() {
257         // We also want to make sure we keep the QNameModule cached
258         final QNameModule cacheMod = module.intern();
259
260         // Identity comparison is here on purpose, as we are deciding whether to potentially store 'qname' into the
261         // interner. It is important that it does not hold user-supplied reference (such a String instance from
262         // parsing of an XML document).
263         final QName template = cacheMod == module ? this : new QName(cacheMod, getLocalName().intern());
264
265         return INTERNER.intern(template);
266     }
267
268     @Override
269     public int hashCode() {
270         if (hash == 0) {
271             hash = Objects.hash(module, getLocalName());
272         }
273         return hash;
274     }
275
276     /**
277      * Compares the specified object with this list for equality.  Returns {@code true} if and only if the specified
278      * object is also instance of {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
279      * {@link #getRevision()} are equals to same properties of this instance.
280      *
281      * @param obj the object to be compared for equality with this QName
282      * @return {@code true} if the specified object is equal to this QName
283      */
284     @Override
285     public boolean equals(final Object obj) {
286         return this == obj || obj instanceof QName other && getLocalName().equals(other.getLocalName())
287             && module.equals(other.module);
288     }
289
290     @Override
291     public @NonNull String toString() {
292         final StringBuilder sb = new StringBuilder().append('(').append(getNamespace());
293         final Optional<Revision> rev = getRevision();
294         if (rev.isPresent()) {
295             sb.append("?revision=").append(rev.orElseThrow());
296         }
297         return sb.append(')').append(getLocalName()).toString();
298     }
299
300     @Override
301     public @NonNull QName bindTo(final QNameModule namespace) {
302         return module.equals(namespace) ? this : super.bindTo(namespace);
303     }
304
305     /**
306      * Returns a QName with the same namespace and local name, but with no revision. If this QName does not have
307      * a Revision, this object is returned.
308      *
309      * @return a QName with the same namespace and local name, but with no revision.
310      */
311     public @NonNull QName withoutRevision() {
312         final QNameModule newModule;
313         return (newModule = module.withoutRevision()) == module ? this : new QName(newModule, getLocalName());
314     }
315
316     /**
317      * Formats {@link Revision} representing revision to format {@code YYYY-mm-dd}
318      *
319      * <p>
320      * YANG Specification defines format for {@code revision<} as YYYY-mm-dd. This format for revision is reused across
321      * multiple places such as capabilities URI, YANG modules, etc.
322      *
323      * @param revision Date object to format
324      * @return String representation or null if the input was null.
325      */
326     public static @Nullable String formattedRevision(final Optional<Revision> revision) {
327         return revision.map(Revision::toString).orElse(null);
328     }
329
330     /**
331      * Compares this QName to other, without comparing revision.
332      *
333      * <p>
334      * Compares instance of this to other instance of QName and returns true if both instances have equal
335      * {@code localName} ({@link #getLocalName()}) and @{code namespace} ({@link #getNamespace()}).
336      *
337      * @param other Other QName. Must not be null.
338      * @return true if this instance and other have equals localName and namespace.
339      * @throws NullPointerException if {@code other} is null.
340      */
341     public boolean isEqualWithoutRevision(final QName other) {
342         return getLocalName().equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
343     }
344
345     @Override
346     @SuppressWarnings("checkstyle:parameterName")
347     public int compareTo(final QName o) {
348         final int result = module.compareTo(o.module);
349         return result != 0 ? result : getLocalName().compareTo(o.getLocalName());
350     }
351
352     @Override
353     public void writeTo(final DataOutput out) throws IOException {
354         if (out instanceof QNameAwareDataOutput aware) {
355             aware.writeQName(this);
356         } else {
357             module.writeTo(out);
358             out.writeUTF(getLocalName());
359         }
360     }
361
362     @Override
363     Object writeReplace() {
364         return new QNv1(this);
365     }
366 }