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