Fix noRev map efficiency
[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 @NonNull 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 @NonNull 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 @NonNull 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 @NonNull 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 @NonNull 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 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 URI namespace, final @Nullable Revision revision,
151             final String localName) {
152         return create(QNameModule.create(namespace, revision), localName);
153     }
154
155     /**
156      * Creates new QName.
157      *
158      * @param namespace Namespace of QName or null if namespace is undefined.
159      * @param revision Revision of namespace.
160      * @param localName Local name part of QName. MUST NOT BE null.
161      * @return Instance of QName
162      */
163     public static @NonNull QName create(final URI namespace, final Optional<Revision> revision,
164             final String localName) {
165         return create(QNameModule.create(namespace, revision), localName);
166     }
167
168     /**
169      * Creates new QName.
170      *
171      * @param namespace Namespace of QName or null if namespace is undefined.
172      * @param revision Revision of namespace or null if revision is unspecified.
173      * @param localName Local name part of QName. MUST NOT BE null.
174      * @return Instance of QName
175      */
176     public static @NonNull QName create(final String namespace, final String localName, final Revision revision) {
177         return create(QNameModule.create(parseNamespace(namespace), revision), localName);
178     }
179
180     /**
181      * Creates new QName.
182      *
183      * @param namespace Namespace of QName, MUST NOT BE Null.
184      * @param revision Revision of namespace / YANG module. MUST NOT BE null, MUST BE in format {@code YYYY-mm-dd}.
185      * @param localName Local name part of QName. MUST NOT BE null.
186      * @return A new QName
187      * @throws NullPointerException If any of parameters is null.
188      * @throws IllegalArgumentException If {@code namespace} is not valid URI or {@code revision} does not conform
189      *         to {@code YYYY-mm-dd}.
190      */
191     public static @NonNull QName create(final String namespace, final String revision, final String localName) {
192         return create(parseNamespace(namespace), Revision.of(revision), localName);
193     }
194
195     /**
196      * Creates new QName.
197      *
198      * @param namespace Namespace of QName, MUST NOT BE Null.
199      * @param localName Local name part of QName. MUST NOT BE null.
200      * @return A new QName
201      * @throws NullPointerException If any of parameters is null.
202      * @throws IllegalArgumentException If {@code namespace} is not valid URI.
203      */
204     public static @NonNull QName create(final String namespace, final String localName) {
205         return create(parseNamespace(namespace), localName);
206     }
207
208     /**
209      * Creates new QName.
210      *
211      * @param namespace Namespace of QName, MUST NOT BE null.
212      * @param localName Local name part of QName. MUST NOT BE null.
213      * @return A new QName
214      * @throws NullPointerException If any of parameters is null.
215      * @throws IllegalArgumentException If <code>namespace</code> is not valid URI.
216      */
217     public static @NonNull QName create(final URI namespace, final String localName) {
218         return new QName(namespace, localName);
219     }
220
221     /**
222      * Read a QName from a DataInput. The format is expected to match the output format of {@link #writeTo(DataOutput)}.
223      *
224      * @param in DataInput to read
225      * @return A QName instance
226      * @throws IOException if I/O error occurs
227      */
228     public static QName readFrom(final DataInput in) throws IOException {
229         final QNameModule module = QNameModule.readFrom(in);
230         return new QName(module, checkLocalName(in.readUTF()));
231     }
232
233     /**
234      * Get the module component of the QName.
235      *
236      * @return Module component
237      */
238     public @NonNull QNameModule getModule() {
239         return module;
240     }
241
242     /**
243      * Returns XMLNamespace assigned to the YANG module.
244      *
245      * @return XMLNamespace assigned to the YANG module.
246      */
247     public @NonNull URI getNamespace() {
248         return module.getNamespace();
249     }
250
251     /**
252      * Returns YANG schema identifier which were defined for this node in the
253      * YANG module.
254      *
255      * @return YANG schema identifier which were defined for this node in the
256      *         YANG module
257      */
258     public @NonNull String getLocalName() {
259         return localName;
260     }
261
262     /**
263      * Returns revision of the YANG module if the module has defined revision.
264      *
265      * @return revision of the YANG module if the module has defined revision.
266      */
267     public @NonNull Optional<Revision> getRevision() {
268         return module.getRevision();
269     }
270
271     /**
272      * Return an interned reference to a equivalent QName.
273      *
274      * @return Interned reference, or this object if it was interned.
275      */
276     public @NonNull QName intern() {
277         // We also want to make sure we keep the QNameModule cached
278         final QNameModule cacheMod = module.intern();
279
280         // Identity comparison is here on purpose, as we are deciding whether to potentially store 'qname' into the
281         // interner. It is important that it does not hold user-supplied reference (such a String instance from
282         // parsing of an XML document).
283         final QName template = cacheMod == module ? this : QName.create(cacheMod, localName.intern());
284
285         return INTERNER.intern(template);
286     }
287
288     @Override
289     public int hashCode() {
290         if (hash == 0) {
291             hash = Objects.hash(module, localName);
292         }
293         return hash;
294     }
295
296     /**
297      * Compares the specified object with this list for equality.  Returns <tt>true</tt> if and only if the specified
298      * object is also instance of {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
299      * {@link #getRevision()} are equals to same properties of this instance.
300      *
301      * @param obj the object to be compared for equality with this QName
302      * @return <tt>true</tt> if the specified object is equal to this QName
303      */
304     @Override
305     public boolean equals(final Object obj) {
306         if (this == obj) {
307             return true;
308         }
309         if (!(obj instanceof QName)) {
310             return false;
311         }
312         final QName other = (QName) obj;
313         return Objects.equals(localName, other.localName) && module.equals(other.module);
314     }
315
316     private static @NonNull URI parseNamespace(final String namespace) {
317         try {
318             return new URI(namespace);
319         } catch (final URISyntaxException ue) {
320             throw new IllegalArgumentException("Namespace '" + namespace + "' is not a valid URI", ue);
321         }
322     }
323
324     @Override
325     public @NonNull String toString() {
326         final StringBuilder sb = new StringBuilder();
327         if (getNamespace() != null) {
328             sb.append(QNAME_LEFT_PARENTHESIS).append(getNamespace());
329
330             final Optional<Revision> rev = getRevision();
331             if (rev.isPresent()) {
332                 sb.append(QNAME_REVISION_DELIMITER).append(rev.get());
333             }
334             sb.append(QNAME_RIGHT_PARENTHESIS);
335         }
336         sb.append(localName);
337         return sb.toString();
338     }
339
340     /**
341      * Returns a QName with the specified QNameModule and the same localname as this one.
342      *
343      * @param newModule New QNameModule to use
344      * @return a QName with specified QNameModule and same local name as this one
345      */
346     public @NonNull QName withModule(final QNameModule newModule) {
347         return new QName(newModule, localName);
348     }
349
350     /**
351      * Returns a QName with the same namespace and local name, but with no revision. If this QName does not have
352      * a Revision, this object is returned.
353      *
354      * @return a QName with the same namespace and local name, but with no revision.
355      */
356     public @NonNull QName withoutRevision() {
357         final QNameModule newModule;
358         return (newModule = module.withoutRevision()) == module ? this : new QName(newModule, localName);
359     }
360
361     /**
362      * Formats {@link Revision} representing revision to format {@code YYYY-mm-dd}
363      *
364      * <p>
365      * YANG Specification defines format for {@code revision<} as YYYY-mm-dd. This format for revision is reused across
366      * multiple places such as capabilities URI, YANG modules, etc.
367      *
368      * @param revision Date object to format
369      * @return String representation or null if the input was null.
370      */
371     public static @Nullable String formattedRevision(final Optional<Revision> revision) {
372         return revision.map(Revision::toString).orElse(null);
373     }
374
375     /**
376      * Compares this QName to other, without comparing revision.
377      *
378      * <p>
379      * Compares instance of this to other instance of QName and returns true if both instances have equal
380      * {@code localName} ({@link #getLocalName()}) and @{code namespace} ({@link #getNamespace()}).
381      *
382      * @param other Other QName. Must not be null.
383      * @return true if this instance and other have equals localName and namespace.
384      * @throws NullPointerException if {@code other} is null.
385      */
386     public boolean isEqualWithoutRevision(final QName other) {
387         return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
388     }
389
390     // FIXME: this comparison function looks odd. We are sorting first by local name and then by module? What is
391     //        the impact on iteration order of SortedMap<QName, ?>?
392     @Override
393     @SuppressWarnings("checkstyle:parameterName")
394     public int compareTo(final QName o) {
395         // compare mandatory localName parameter
396         int result = localName.compareTo(o.localName);
397         if (result != 0) {
398             return result;
399         }
400         return module.compareTo(o.module);
401     }
402
403     @Override
404     public void writeTo(final DataOutput out) throws IOException {
405         module.writeTo(out);
406         out.writeUTF(localName);
407     }
408 }