Merge "Improved sorting of augmentations before code generation."
[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      * Returns XMLNamespace assigned to the YANG module.
197      *
198      * @return XMLNamespace assigned to the YANG module.
199      */
200     public URI getNamespace() {
201         return module.getNamespace();
202     }
203
204     /**
205      * Returns YANG schema identifier which were defined for this node in the
206      * YANG module
207      *
208      * @return YANG schema identifier which were defined for this node in the
209      *         YANG module
210      */
211     public String getLocalName() {
212         return localName;
213     }
214
215     /**
216      * Returns revision of the YANG module if the module has defined revision,
217      * otherwise returns <code>null</code>
218      *
219      * @return revision of the YANG module if the module has defined revision,
220      *         otherwise returns <code>null</code>
221      */
222     public Date getRevision() {
223         return module.getRevision();
224     }
225
226     /**
227      * Returns locally defined prefix assigned to local name
228      *
229      * @return locally defined prefix assigned to local name
230      */
231     public String getPrefix() {
232         return prefix;
233     }
234
235     @Override
236     public int hashCode() {
237         final int prime = 31;
238         int result = 1;
239         result = prime * result + ((localName == null) ? 0 : localName.hashCode());
240         result = prime * result + ((getNamespace() == null) ? 0 : getNamespace().hashCode());
241         result = prime * result + ((getFormattedRevision() == null) ? 0 : getFormattedRevision().hashCode());
242         return result;
243     }
244
245     /**
246      *
247      * Compares the specified object with this list for equality.  Returns
248      * <tt>true</tt> if and only if the specified object is also instance of
249      * {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
250      * {@link #getRevision()} are equals to same properties of this instance.
251      *
252      * @param o the object to be compared for equality with this QName
253      * @return <tt>true</tt> if the specified object is equal to this QName
254      *
255      */
256     @Override
257     public boolean equals(final Object obj) {
258         if (this == obj) {
259             return true;
260         }
261         if (!(obj instanceof QName)) {
262             return false;
263         }
264         final QName other = (QName) obj;
265         if (localName == null) {
266             if (other.localName != null) {
267                 return false;
268             }
269         } else if (!localName.equals(other.localName)) {
270             return false;
271         }
272         if (getNamespace() == null) {
273             if (other.getNamespace() != null) {
274                 return false;
275             }
276         } else if (!getNamespace().equals(other.getNamespace())) {
277             return false;
278         }
279         if (getFormattedRevision() == null) {
280             if (other.getFormattedRevision() != null) {
281                 return false;
282             }
283         } else if (!getRevision().equals(other.getRevision())) {
284             return false;
285         }
286         return true;
287     }
288
289     public static QName create(final QName base, final String localName) {
290         return new QName(base, localName);
291     }
292
293     /**
294      *
295      * Creates new QName.
296      *
297      * @param namespace Namespace of QName or null if namespace is undefined.
298      * @param revision Revision of namespace or null if revision is unspecified.
299      * @param localName Local name part of QName. MUST NOT BE null.
300      * @return Instance of QName
301      */
302     public static QName create(final URI namespace, final Date revision, final String localName) {
303         return new QName(QNameModule.create(namespace, revision), null,localName);
304     }
305
306     /**
307      *
308      * Creates new QName.
309      *
310      * @param namespace
311      *            Namespace of QName, MUST NOT BE Null.
312      * @param revision
313      *            Revision of namespace / YANG module. MUST NOT BE null, MUST BE
314      *            in format <code>YYYY-mm-dd</code>.
315      * @param localName
316      *            Local name part of QName. MUST NOT BE null.
317      * @return
318      * @throws NullPointerException
319      *             If any of paramaters is null.
320      * @throws IllegalArgumentException
321      *             If <code>namespace</code> is not valid URI or
322      *             <code>revision</code> is not according to format
323      *             <code>YYYY-mm-dd</code>.
324      */
325     public static QName create(final String namespace, final String revision, final String localName)
326             throws IllegalArgumentException {
327         final URI namespaceUri;
328         try {
329             namespaceUri = new URI(namespace);
330         } catch (URISyntaxException ue) {
331             throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
332         }
333
334         Date revisionDate = parseRevision(revision);
335         return create(namespaceUri, revisionDate, localName);
336     }
337
338     @Override
339     public String toString() {
340         StringBuilder sb = new StringBuilder();
341         if (getNamespace() != null) {
342             sb.append(QNAME_LEFT_PARENTHESIS + getNamespace());
343
344             if (getFormattedRevision() != null) {
345                 sb.append(QNAME_REVISION_DELIMITER + getFormattedRevision());
346             }
347             sb.append(QNAME_RIGHT_PARENTHESIS);
348         }
349         sb.append(localName);
350         return sb.toString();
351     }
352
353     /**
354      * Return string representation of revision in format
355      * <code>YYYY-mm-dd</code>
356      *
357      * YANG Specification defines format for <code>revision</code> as
358      * YYYY-mm-dd. This format for revision is reused accross multiple places
359      * such as capabilities URI, YANG modules, etc.
360      *
361      * @return String representation of revision or null, if revision is not
362      *         set.
363      */
364     public String getFormattedRevision() {
365         return module.getFormattedRevision();
366     }
367
368     /**
369      * Creates copy of this with revision and prefix unset.
370      *
371      * @return copy of this QName with revision and prefix unset.
372      */
373     public QName withoutRevision() {
374         return QName.create(getNamespace(), null, localName);
375     }
376
377     public static Date parseRevision(final String formatedDate) {
378         try {
379             return getRevisionFormat().parse(formatedDate);
380         } catch (ParseException | RuntimeException e) {
381             throw new IllegalArgumentException(
382                     String.format("Revision '%s'is not in a supported format", formatedDate), e);
383         }
384     }
385
386     /**
387      * Formats {@link Date} representing revision to format
388      * <code>YYYY-mm-dd</code>
389      *
390      * YANG Specification defines format for <code>revision</code> as
391      * YYYY-mm-dd. This format for revision is reused accross multiple places
392      * such as capabilities URI, YANG modules, etc.
393      *
394      * @param revision
395      *            Date object to format or null
396      * @return String representation or null if the input was null.
397      */
398     public static String formattedRevision(final Date revision) {
399         if (revision == null) {
400             return null;
401         }
402         return getRevisionFormat().format(revision);
403     }
404
405     /**
406      *
407      * Compares this QName to other, without comparing revision.
408      *
409      * Compares instance of this to other instance of QName and returns true if
410      * both instances have equal <code>localName</code> ({@link #getLocalName()}
411      * ) and <code>namespace</code> ({@link #getNamespace()}).
412      *
413      * @param other
414      *            Other QName. Must not be null.
415      * @return true if this instance and other have equals localName and
416      *         namespace.
417      * @throws NullPointerException
418      *             if <code>other</code> is null.
419      */
420     public boolean isEqualWithoutRevision(final QName other) {
421         return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
422     }
423
424     @Override
425     public int compareTo(final QName other) {
426         // compare mandatory localName parameter
427         int result = localName.compareTo(other.localName);
428         if (result != 0) {
429             return result;
430         }
431
432         // compare nullable namespace parameter
433         if (getNamespace() == null) {
434             if (other.getNamespace() != null) {
435                 return -1;
436             }
437         } else {
438             if (other.getNamespace() == null) {
439                 return 1;
440             }
441             result = getNamespace().compareTo(other.getNamespace());
442             if (result != 0) {
443                 return result;
444             }
445         }
446
447         // compare nullable revision parameter
448         if (getRevision() == null) {
449             if (other.getRevision() != null) {
450                 return -1;
451             }
452         } else {
453             if (other.getRevision() == null) {
454                 return 1;
455             }
456             result = getRevision().compareTo(other.getRevision());
457             if (result != 0) {
458                 return result;
459             }
460         }
461
462         return result;
463     }
464
465 }