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