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