771c008f47502bdf9a233ea2c65c83014632ee5f
[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 org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil.getRevisionFormat;
11
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Strings;
14 import com.google.common.collect.Interner;
15 import com.google.common.collect.Interners;
16 import java.io.Serializable;
17 import java.net.URI;
18 import java.net.URISyntaxException;
19 import java.text.ParseException;
20 import java.util.Date;
21 import java.util.Objects;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
24 import javax.annotation.Nonnull;
25 import javax.annotation.RegEx;
26 import org.opendaylight.yangtools.concepts.Immutable;
27
28 /**
29  * The QName from XML consists of local name of element and XML namespace, but
30  * for our use, we added module revision to it.
31  *
32  * In YANG context QName is full name of defined node, type, procedure or
33  * notification. QName consists of XML namespace, YANG model revision and local
34  * name of defined type. It is used to prevent name clashes between nodes with
35  * same local name, but from different schemas.
36  *
37  * <ul>
38  * <li><b>XMLNamespace</b> - {@link #getNamespace()} - the namespace assigned to the YANG module which
39  * defined element, type, procedure or notification.</li>
40  * <li><b>Revision</b> - {@link #getRevision()} - the revision of the YANG module which describes the
41  * element</li>
42  * <li><b>LocalName</b> - {@link #getLocalName()} - the YANG schema identifier which were defined for this
43  * node in the YANG module</li>
44  * </ul>
45  *
46  * QName may also have <code>prefix</code> assigned, but prefix does not
47  * affect equality and identity of two QNames and carry only information
48  * which may be useful for serializers / deserializers.
49  *
50  *
51  */
52 public final class QName implements Immutable, Serializable, Comparable<QName> {
53     private static final Interner<QName> INTERNER = Interners.newWeakInterner();
54     private static final long serialVersionUID = 5398411242927766414L;
55
56     static final String QNAME_REVISION_DELIMITER = "?revision=";
57     static final String QNAME_LEFT_PARENTHESIS = "(";
58     static final String QNAME_RIGHT_PARENTHESIS = ")";
59
60     @RegEx
61     private static final String QNAME_STRING_FULL = "^\\((.+)\\?revision=(.+)\\)(.+)$";
62     private static final Pattern QNAME_PATTERN_FULL = Pattern.compile(QNAME_STRING_FULL);
63
64     @RegEx
65     private static final String QNAME_STRING_NO_REVISION = "^\\((.+)\\)(.+)$";
66     private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile(QNAME_STRING_NO_REVISION);
67
68     @RegEx
69     private static final String QNAME_STRING_NO_NAMESPACE_NO_REVISION = "^(.+)$";
70     private static final Pattern QNAME_PATTERN_NO_NAMESPACE_NO_REVISION =
71         Pattern.compile(QNAME_STRING_NO_NAMESPACE_NO_REVISION);
72
73     private static final char[] ILLEGAL_CHARACTERS = new char[] { '?', '(', ')', '&', ':' };
74
75     // Non-null
76     private final QNameModule module;
77     // Non-null
78     private final String localName;
79     private transient int hash;
80
81     private QName(final QNameModule module, final String localName) {
82         this.localName = checkLocalName(localName);
83         this.module = module;
84     }
85
86     /**
87      * QName Constructor.
88      *
89      * @param namespace
90      *            the namespace assigned to the YANG module
91      * @param localName
92      *            YANG schema identifier
93      */
94     public QName(final URI namespace, final String localName) {
95         this(QNameModule.create(namespace, null), localName);
96     }
97
98     private static String checkLocalName(final String localName) {
99         Preconditions.checkArgument(localName != null, "Parameter 'localName' may not be null.");
100                 Preconditions.checkArgument(!Strings.isNullOrEmpty(localName), "Parameter 'localName' must be a non-empty string.");
101
102         for (final char c : ILLEGAL_CHARACTERS) {
103             if (localName.indexOf(c) != -1) {
104                 throw new IllegalArgumentException(String.format(
105                         "Parameter 'localName':'%s' contains illegal character '%s'", localName, c));
106             }
107         }
108         return localName;
109     }
110
111     public static QName create(final String input) {
112         Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
113         if (matcher.matches()) {
114             final String namespace = matcher.group(1);
115             final String revision = matcher.group(2);
116             final String localName = matcher.group(3);
117             return create(namespace, revision, localName);
118         }
119         matcher = QNAME_PATTERN_NO_REVISION.matcher(input);
120         if (matcher.matches()) {
121             final URI namespace = URI.create(matcher.group(1));
122             final String localName = matcher.group(2);
123             return new QName(namespace, localName);
124         }
125         matcher = QNAME_PATTERN_NO_NAMESPACE_NO_REVISION.matcher(input);
126         if (matcher.matches()) {
127             final String localName = matcher.group(1);
128             return new QName((URI) null, localName);
129         }
130         throw new IllegalArgumentException("Invalid input:" + input);
131     }
132
133     /**
134      * Get the module component of the QName.
135      *
136      * @return Module component
137      */
138     public QNameModule getModule() {
139         return module;
140     }
141
142     /**
143      * Returns XMLNamespace assigned to the YANG module.
144      *
145      * @return XMLNamespace assigned to the YANG module.
146      */
147     public URI getNamespace() {
148         return module.getNamespace();
149     }
150
151     /**
152      * Returns YANG schema identifier which were defined for this node in the
153      * YANG module
154      *
155      * @return YANG schema identifier which were defined for this node in the
156      *         YANG module
157      */
158     public String getLocalName() {
159         return localName;
160     }
161
162     /**
163      * Returns revision of the YANG module if the module has defined revision,
164      * otherwise returns <code>null</code>
165      *
166      * @return revision of the YANG module if the module has defined revision,
167      *         otherwise returns <code>null</code>
168      */
169     public Date getRevision() {
170         return module.getRevision();
171     }
172
173     /**
174      * Return an interned reference to a equivalent QName.
175      *
176      * @return Interned reference, or this object if it was interned.
177      */
178     public QName intern() {
179         // We also want to make sure we keep the QNameModule cached
180         final QNameModule cacheMod = module.intern();
181
182         // Identity comparison is here on purpose, as we are deciding whether to potentially store 'qname' into the
183         // interner. It is important that it does not hold user-supplied reference (such a String instance from
184         // parsing of an XML document).
185         final QName template = cacheMod == module ? this : QName.create(cacheMod, localName.intern());
186
187         return INTERNER.intern(template);
188     }
189
190     @Override
191     public int hashCode() {
192         if (hash == 0) {
193             hash = Objects.hash(module, localName);
194         }
195         return hash;
196     }
197
198     /**
199      *
200      * Compares the specified object with this list for equality.  Returns
201      * <tt>true</tt> if and only if the specified object is also instance of
202      * {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
203      * {@link #getRevision()} are equals to same properties of this instance.
204      *
205      * @param obj the object to be compared for equality with this QName
206      * @return <tt>true</tt> if the specified object is equal to this QName
207      *
208      */
209     @Override
210     public boolean equals(final Object obj) {
211         if (this == obj) {
212             return true;
213         }
214         if (!(obj instanceof QName)) {
215             return false;
216         }
217         final QName other = (QName) obj;
218         return Objects.equals(localName, other.localName) && module.equals(other.module);
219     }
220
221     public static QName create(final QName base, final String localName) {
222         return create(base.getModule(), localName);
223     }
224
225     /**
226      * Creates new QName.
227      *
228      * @param qnameModule
229      *            Namespace and revision enclosed as a QNameModule
230      * @param localName
231      *            Local name part of QName. MUST NOT BE null.
232      * @return Instance of QName
233      */
234     public static QName create(final QNameModule qnameModule, final String localName) {
235         return new QName(Preconditions.checkNotNull(qnameModule,"module may not be null"), localName);
236     }
237
238     /**
239      * Creates new QName.
240      *
241      * @param namespace
242      *            Namespace of QName or null if namespace is undefined.
243      * @param revision
244      *            Revision of namespace or null if revision is unspecified.
245      * @param localName
246      *            Local name part of QName. MUST NOT BE null.
247      * @return Instance of QName
248      */
249     public static QName create(final URI namespace, final Date revision, final String localName) {
250         return create(QNameModule.create(namespace, revision), localName);
251     }
252
253     /**
254      * Creates new QName.
255      *
256      * @param namespace
257      *            Namespace of QName or null if namespace is undefined.
258      * @param revision
259      *            Revision of namespace or null if revision is unspecified.
260      * @param localName
261      *            Local name part of QName. MUST NOT BE null.
262      * @return Instance of QName
263      */
264     public static QName create(final String namespace, final String localName, final Date revision) {
265         final URI namespaceUri = parseNamespace(namespace);
266         return create(QNameModule.create(namespaceUri, revision), localName);
267     }
268
269     /**
270      * Creates new QName.
271      *
272      * @param namespace
273      *            Namespace of QName, MUST NOT BE Null.
274      * @param revision
275      *            Revision of namespace / YANG module. MUST NOT BE null, MUST BE
276      *            in format <code>YYYY-mm-dd</code>.
277      * @param localName
278      *            Local name part of QName. MUST NOT BE null.
279      * @return A new QName
280      * @throws NullPointerException
281      *             If any of parameters is null.
282      * @throws IllegalArgumentException
283      *             If <code>namespace</code> is not valid URI or
284      *             <code>revision</code> is not according to format
285      *             <code>YYYY-mm-dd</code>.
286      */
287     public static QName create(final String namespace, final String revision, final String localName) {
288         final URI namespaceUri = parseNamespace(namespace);
289         final Date revisionDate = parseRevision(revision);
290         return create(namespaceUri, revisionDate, localName);
291     }
292
293     private static URI parseNamespace(final String namespace) {
294         try {
295             return new URI(namespace);
296         } catch (final URISyntaxException ue) {
297             throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
298         }
299     }
300
301     /**
302      * Creates new QName.
303      *
304      * @param namespace
305      *            Namespace of QName, MUST NOT BE Null.
306      * @param localName
307      *            Local name part of QName. MUST NOT BE null.
308      * @return A new QName
309      * @throws NullPointerException
310      *             If any of parameters is null.
311      * @throws IllegalArgumentException
312      *             If <code>namespace</code> is not valid URI.
313      */
314     public static QName create(final String namespace, final String localName) {
315         return create(parseNamespace(namespace), null, localName);
316     }
317
318     @Override
319     public String toString() {
320         final StringBuilder sb = new StringBuilder();
321         if (getNamespace() != null) {
322             sb.append(QNAME_LEFT_PARENTHESIS).append(getNamespace());
323
324             if (getFormattedRevision() != null) {
325                 sb.append(QNAME_REVISION_DELIMITER).append(getFormattedRevision());
326             }
327             sb.append(QNAME_RIGHT_PARENTHESIS);
328         }
329         sb.append(localName);
330         return sb.toString();
331     }
332
333     /**
334      * Return string representation of revision in format
335      * <code>YYYY-mm-dd</code>
336      *
337      * YANG Specification defines format for <code>revision</code> as
338      * YYYY-mm-dd. This format for revision is reused accross multiple places
339      * such as capabilities URI, YANG modules, etc.
340      *
341      * @return String representation of revision or null, if revision is not
342      *         set.
343      */
344     public String getFormattedRevision() {
345         return module.getFormattedRevision();
346     }
347
348     /**
349      * Creates copy of this with revision and prefix unset.
350      *
351      * @return copy of this QName with revision and prefix unset.
352      */
353     public QName withoutRevision() {
354         return create(getNamespace(), null, localName);
355     }
356
357     public static Date parseRevision(final String formatedDate) {
358         try {
359             return getRevisionFormat().parse(formatedDate);
360         } catch (ParseException | RuntimeException e) {
361             throw new IllegalArgumentException(
362                     String.format("Revision '%s'is not in a supported format", formatedDate), e);
363         }
364     }
365
366     /**
367      * Formats {@link Date} representing revision to format
368      * <code>YYYY-mm-dd</code>
369      *
370      * YANG Specification defines format for <code>revision</code> as
371      * YYYY-mm-dd. This format for revision is reused accross multiple places
372      * such as capabilities URI, YANG modules, etc.
373      *
374      * @param revision
375      *            Date object to format or null
376      * @return String representation or null if the input was null.
377      */
378     public static String formattedRevision(final Date revision) {
379         if (revision == null) {
380             return null;
381         }
382         return getRevisionFormat().format(revision);
383     }
384
385     /**
386      *
387      * Compares this QName to other, without comparing revision.
388      *
389      * Compares instance of this to other instance of QName and returns true if
390      * both instances have equal <code>localName</code> ({@link #getLocalName()}
391      * ) and <code>namespace</code> ({@link #getNamespace()}).
392      *
393      * @param other
394      *            Other QName. Must not be null.
395      * @return true if this instance and other have equals localName and
396      *         namespace.
397      * @throws NullPointerException
398      *             if <code>other</code> is null.
399      */
400     public boolean isEqualWithoutRevision(final QName other) {
401         return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
402     }
403
404     @Override
405     public int compareTo(@Nonnull final QName other) {
406         // compare mandatory localName parameter
407         int result = localName.compareTo(other.localName);
408         if (result != 0) {
409             return result;
410         }
411
412         // compare nullable namespace parameter
413         if (getNamespace() == null) {
414             if (other.getNamespace() != null) {
415                 return -1;
416             }
417         } else {
418             if (other.getNamespace() == null) {
419                 return 1;
420             }
421             result = getNamespace().compareTo(other.getNamespace());
422             if (result != 0) {
423                 return result;
424             }
425         }
426
427         // compare nullable revision parameter
428         if (getRevision() == null) {
429             if (other.getRevision() != null) {
430                 return -1;
431             }
432         } else {
433             if (other.getRevision() == null) {
434                 return 1;
435             }
436             result = getRevision().compareTo(other.getRevision());
437             if (result != 0) {
438                 return result;
439             }
440         }
441
442         return result;
443     }
444
445 }