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