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