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.getNamespace(), base.getRevision(), 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, localName);
285     }
286
287     public static QName create(final QNameModule module, final String prefix, final String localName) {
288         if (module == null) {
289             throw new NullPointerException("module may not be null");
290         }
291         return new QName(module, prefix, localName);
292     }
293
294     /**
295      * Creates new QName.
296      *
297      * @param qnameModule
298      *            Namespace and revision enclosed as a QNameModule
299      * @param localName
300      *            Local name part of QName. MUST NOT BE null.
301      * @return Instance of QName
302      */
303     public static QName create(final QNameModule qnameModule, final String localName) {
304         return new QName(qnameModule, null, localName);
305     }
306
307     /**
308      * Creates new QName.
309      *
310      * @param namespace
311      *            Namespace of QName or null if namespace is undefined.
312      * @param revision
313      *            Revision of namespace or null if revision is unspecified.
314      * @param localName
315      *            Local name part of QName. MUST NOT BE null.
316      * @return Instance of QName
317      */
318     public static QName create(final URI namespace, final Date revision, final String localName) {
319         return new QName(QNameModule.create(namespace, revision), null, localName);
320     }
321
322     /**
323      *
324      * Creates new QName.
325      *
326      * @param namespace
327      *            Namespace of QName, MUST NOT BE Null.
328      * @param revision
329      *            Revision of namespace / YANG module. MUST NOT BE null, MUST BE
330      *            in format <code>YYYY-mm-dd</code>.
331      * @param localName
332      *            Local name part of QName. MUST NOT BE null.
333      * @return
334      * @throws NullPointerException
335      *             If any of paramaters is null.
336      * @throws IllegalArgumentException
337      *             If <code>namespace</code> is not valid URI or
338      *             <code>revision</code> is not according to format
339      *             <code>YYYY-mm-dd</code>.
340      */
341     public static QName create(final String namespace, final String revision, final String localName)
342             throws IllegalArgumentException {
343         final URI namespaceUri;
344         try {
345             namespaceUri = new URI(namespace);
346         } catch (URISyntaxException ue) {
347             throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
348         }
349
350         Date revisionDate = parseRevision(revision);
351         return create(namespaceUri, revisionDate, localName);
352     }
353
354     @Override
355     public String toString() {
356         StringBuilder sb = new StringBuilder();
357         if (getNamespace() != null) {
358             sb.append(QNAME_LEFT_PARENTHESIS + getNamespace());
359
360             if (getFormattedRevision() != null) {
361                 sb.append(QNAME_REVISION_DELIMITER + getFormattedRevision());
362             }
363             sb.append(QNAME_RIGHT_PARENTHESIS);
364         }
365         sb.append(localName);
366         return sb.toString();
367     }
368
369     /**
370      * Return string representation of revision in format
371      * <code>YYYY-mm-dd</code>
372      *
373      * YANG Specification defines format for <code>revision</code> as
374      * YYYY-mm-dd. This format for revision is reused accross multiple places
375      * such as capabilities URI, YANG modules, etc.
376      *
377      * @return String representation of revision or null, if revision is not
378      *         set.
379      */
380     public String getFormattedRevision() {
381         return module.getFormattedRevision();
382     }
383
384     /**
385      * Creates copy of this with revision and prefix unset.
386      *
387      * @return copy of this QName with revision and prefix unset.
388      */
389     public QName withoutRevision() {
390         return QName.create(getNamespace(), null, localName);
391     }
392
393     public static Date parseRevision(final String formatedDate) {
394         try {
395             return getRevisionFormat().parse(formatedDate);
396         } catch (ParseException | RuntimeException e) {
397             throw new IllegalArgumentException(
398                     String.format("Revision '%s'is not in a supported format", formatedDate), e);
399         }
400     }
401
402     /**
403      * Formats {@link Date} representing revision to format
404      * <code>YYYY-mm-dd</code>
405      *
406      * YANG Specification defines format for <code>revision</code> as
407      * YYYY-mm-dd. This format for revision is reused accross multiple places
408      * such as capabilities URI, YANG modules, etc.
409      *
410      * @param revision
411      *            Date object to format or null
412      * @return String representation or null if the input was null.
413      */
414     public static String formattedRevision(final Date revision) {
415         if (revision == null) {
416             return null;
417         }
418         return getRevisionFormat().format(revision);
419     }
420
421     /**
422      *
423      * Compares this QName to other, without comparing revision.
424      *
425      * Compares instance of this to other instance of QName and returns true if
426      * both instances have equal <code>localName</code> ({@link #getLocalName()}
427      * ) and <code>namespace</code> ({@link #getNamespace()}).
428      *
429      * @param other
430      *            Other QName. Must not be null.
431      * @return true if this instance and other have equals localName and
432      *         namespace.
433      * @throws NullPointerException
434      *             if <code>other</code> is null.
435      */
436     public boolean isEqualWithoutRevision(final QName other) {
437         return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
438     }
439
440     @Override
441     public int compareTo(final QName other) {
442         // compare mandatory localName parameter
443         int result = localName.compareTo(other.localName);
444         if (result != 0) {
445             return result;
446         }
447
448         // compare nullable namespace parameter
449         if (getNamespace() == null) {
450             if (other.getNamespace() != null) {
451                 return -1;
452             }
453         } else {
454             if (other.getNamespace() == null) {
455                 return 1;
456             }
457             result = getNamespace().compareTo(other.getNamespace());
458             if (result != 0) {
459                 return result;
460             }
461         }
462
463         // compare nullable revision parameter
464         if (getRevision() == null) {
465             if (other.getRevision() != null) {
466                 return -1;
467             }
468         } else {
469             if (other.getRevision() == null) {
470                 return 1;
471             }
472             result = getRevision().compareTo(other.getRevision());
473             if (result != 0) {
474                 return result;
475             }
476         }
477
478         return result;
479     }
480
481 }