BUG-1382: deprecate QName.getPrefix()
[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      * @deprecated Prefix storage in QNames is deprecated.
87      */
88     @Deprecated
89     public QName(final URI namespace, final Date revision, final String prefix, final String localName) {
90         this(QNameModule.create(namespace, revision), prefix, localName);
91     }
92
93     /**
94      * QName Constructor.
95      *
96      * @param namespace
97      *            the namespace assigned to the YANG module
98      * @param localName
99      *            YANG schema identifier
100      */
101     public QName(final URI namespace, final String localName) {
102         this(namespace, null, "", localName);
103     }
104
105     private static String checkLocalName(final String localName) {
106         if (localName == null) {
107             throw new IllegalArgumentException("Parameter 'localName' may not be null.");
108         }
109         if (localName.length() == 0) {
110             throw new IllegalArgumentException("Parameter 'localName' must be a non-empty string.");
111         }
112
113         for (char c : ILLEGAL_CHARACTERS) {
114             if (localName.indexOf(c) != -1) {
115                 throw new IllegalArgumentException(String.format(
116                         "Parameter 'localName':'%s' contains illegal character '%s'", localName, c));
117             }
118         }
119         return localName;
120     }
121
122     public static QName create(final String input) {
123         Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
124         if (matcher.matches()) {
125             String namespace = matcher.group(1);
126             String revision = matcher.group(2);
127             String localName = matcher.group(3);
128             return create(namespace, revision, localName);
129         }
130         matcher = QNAME_PATTERN_NO_REVISION.matcher(input);
131         if (matcher.matches()) {
132             URI namespace = URI.create(matcher.group(1));
133             String localName = matcher.group(2);
134             return new QName(namespace, localName);
135         }
136         matcher = QNAME_PATTERN_NO_NAMESPACE_NO_REVISION.matcher(input);
137         if (matcher.matches()) {
138             String localName = matcher.group(1);
139             return new QName((URI) null, localName);
140         }
141         throw new IllegalArgumentException("Invalid input:" + input);
142     }
143
144     /**
145      * Get the module component of the QName.
146      *
147      * @return Module component
148      */
149     public QNameModule getModule() {
150         return module;
151     }
152
153     /**
154      * Returns XMLNamespace assigned to the YANG module.
155      *
156      * @return XMLNamespace assigned to the YANG module.
157      */
158     public URI getNamespace() {
159         return module.getNamespace();
160     }
161
162     /**
163      * Returns YANG schema identifier which were defined for this node in the
164      * YANG module
165      *
166      * @return YANG schema identifier which were defined for this node in the
167      *         YANG module
168      */
169     public String getLocalName() {
170         return localName;
171     }
172
173     /**
174      * Returns revision of the YANG module if the module has defined revision,
175      * otherwise returns <code>null</code>
176      *
177      * @return revision of the YANG module if the module has defined revision,
178      *         otherwise returns <code>null</code>
179      */
180     public Date getRevision() {
181         return module.getRevision();
182     }
183
184     /**
185      * Returns locally defined prefix assigned to local name
186      *
187      * @return locally defined prefix assigned to local name
188      *
189      * @deprecated Prefix storage in QNames is deprecated.
190      */
191     @Deprecated
192     public String getPrefix() {
193         return prefix;
194     }
195
196     @Override
197     public int hashCode() {
198         final int prime = 31;
199         int result = 1;
200         result = prime * result + ((localName == null) ? 0 : localName.hashCode());
201         result = prime * result + module.hashCode();
202         return result;
203     }
204
205     /**
206      *
207      * Compares the specified object with this list for equality.  Returns
208      * <tt>true</tt> if and only if the specified object is also instance of
209      * {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
210      * {@link #getRevision()} are equals to same properties of this instance.
211      *
212      * @param o the object to be compared for equality with this QName
213      * @return <tt>true</tt> if the specified object is equal to this QName
214      *
215      */
216     @Override
217     public boolean equals(final Object obj) {
218         if (this == obj) {
219             return true;
220         }
221         if (!(obj instanceof QName)) {
222             return false;
223         }
224         final QName other = (QName) obj;
225         if (localName == null) {
226             if (other.localName != null) {
227                 return false;
228             }
229         } else if (!localName.equals(other.localName)) {
230             return false;
231         }
232         return module.equals(other.module);
233     }
234
235     public static QName create(final QName base, final String localName) {
236         return new QName(base.getModule(), base.getPrefix(), localName);
237     }
238
239     /**
240      * Creates new QName.
241      *
242      * @param qnameModule
243      *            Namespace and revision enclosed as a QNameModule
244      * @param prefix
245      *            Namespace prefix
246      * @param localName
247      *            Local name part of QName. MUST NOT BE null.
248      * @return Instance of QName
249      *
250      * @deprecated Prefix storage in QNames is deprecated.
251      */
252     @Deprecated
253     public static QName create(final QNameModule module, final String prefix, final String localName) {
254         if (module == null) {
255             throw new NullPointerException("module may not be null");
256         }
257         return new QName(module, prefix, localName);
258     }
259
260     /**
261      * Creates new QName.
262      *
263      * @param qnameModule
264      *            Namespace and revision enclosed as a QNameModule
265      * @param localName
266      *            Local name part of QName. MUST NOT BE null.
267      * @return Instance of QName
268      */
269     public static QName create(final QNameModule qnameModule, final String localName) {
270         return new QName(qnameModule, null, localName);
271     }
272
273     /**
274      * Creates new QName.
275      *
276      * @param namespace
277      *            Namespace of QName or null if namespace is undefined.
278      * @param revision
279      *            Revision of namespace or null if revision is unspecified.
280      * @param localName
281      *            Local name part of QName. MUST NOT BE null.
282      * @return Instance of QName
283      */
284     public static QName create(final URI namespace, final Date revision, final String localName) {
285         return new QName(QNameModule.create(namespace, revision), null, localName);
286     }
287
288     /**
289      *
290      * Creates new QName.
291      *
292      * @param namespace
293      *            Namespace of QName, MUST NOT BE Null.
294      * @param revision
295      *            Revision of namespace / YANG module. MUST NOT BE null, MUST BE
296      *            in format <code>YYYY-mm-dd</code>.
297      * @param localName
298      *            Local name part of QName. MUST NOT BE null.
299      * @return
300      * @throws NullPointerException
301      *             If any of paramaters is null.
302      * @throws IllegalArgumentException
303      *             If <code>namespace</code> is not valid URI or
304      *             <code>revision</code> is not according to format
305      *             <code>YYYY-mm-dd</code>.
306      */
307     public static QName create(final String namespace, final String revision, final String localName)
308             throws IllegalArgumentException {
309         final URI namespaceUri;
310         try {
311             namespaceUri = new URI(namespace);
312         } catch (URISyntaxException ue) {
313             throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
314         }
315
316         Date revisionDate = parseRevision(revision);
317         return create(namespaceUri, revisionDate, localName);
318     }
319
320     @Override
321     public String toString() {
322         StringBuilder sb = new StringBuilder();
323         if (getNamespace() != null) {
324             sb.append(QNAME_LEFT_PARENTHESIS + getNamespace());
325
326             if (getFormattedRevision() != null) {
327                 sb.append(QNAME_REVISION_DELIMITER + getFormattedRevision());
328             }
329             sb.append(QNAME_RIGHT_PARENTHESIS);
330         }
331         sb.append(localName);
332         return sb.toString();
333     }
334
335     /**
336      * Return string representation of revision in format
337      * <code>YYYY-mm-dd</code>
338      *
339      * YANG Specification defines format for <code>revision</code> as
340      * YYYY-mm-dd. This format for revision is reused accross multiple places
341      * such as capabilities URI, YANG modules, etc.
342      *
343      * @return String representation of revision or null, if revision is not
344      *         set.
345      */
346     public String getFormattedRevision() {
347         return module.getFormattedRevision();
348     }
349
350     /**
351      * Creates copy of this with revision and prefix unset.
352      *
353      * @return copy of this QName with revision and prefix unset.
354      */
355     public QName withoutRevision() {
356         return QName.create(getNamespace(), null, localName);
357     }
358
359     public static Date parseRevision(final String formatedDate) {
360         try {
361             return getRevisionFormat().parse(formatedDate);
362         } catch (ParseException | RuntimeException e) {
363             throw new IllegalArgumentException(
364                     String.format("Revision '%s'is not in a supported format", formatedDate), e);
365         }
366     }
367
368     /**
369      * Formats {@link Date} representing revision to format
370      * <code>YYYY-mm-dd</code>
371      *
372      * YANG Specification defines format for <code>revision</code> as
373      * YYYY-mm-dd. This format for revision is reused accross multiple places
374      * such as capabilities URI, YANG modules, etc.
375      *
376      * @param revision
377      *            Date object to format or null
378      * @return String representation or null if the input was null.
379      */
380     public static String formattedRevision(final Date revision) {
381         if (revision == null) {
382             return null;
383         }
384         return getRevisionFormat().format(revision);
385     }
386
387     /**
388      *
389      * Compares this QName to other, without comparing revision.
390      *
391      * Compares instance of this to other instance of QName and returns true if
392      * both instances have equal <code>localName</code> ({@link #getLocalName()}
393      * ) and <code>namespace</code> ({@link #getNamespace()}).
394      *
395      * @param other
396      *            Other QName. Must not be null.
397      * @return true if this instance and other have equals localName and
398      *         namespace.
399      * @throws NullPointerException
400      *             if <code>other</code> is null.
401      */
402     public boolean isEqualWithoutRevision(final QName other) {
403         return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
404     }
405
406     @Override
407     public int compareTo(final QName other) {
408         // compare mandatory localName parameter
409         int result = localName.compareTo(other.localName);
410         if (result != 0) {
411             return result;
412         }
413
414         // compare nullable namespace parameter
415         if (getNamespace() == null) {
416             if (other.getNamespace() != null) {
417                 return -1;
418             }
419         } else {
420             if (other.getNamespace() == null) {
421                 return 1;
422             }
423             result = getNamespace().compareTo(other.getNamespace());
424             if (result != 0) {
425                 return result;
426             }
427         }
428
429         // compare nullable revision parameter
430         if (getRevision() == null) {
431             if (other.getRevision() != null) {
432                 return -1;
433             }
434         } else {
435             if (other.getRevision() == null) {
436                 return 1;
437             }
438             result = getRevision().compareTo(other.getRevision());
439             if (result != 0) {
440                 return result;
441             }
442         }
443
444         return result;
445     }
446
447 }