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