Use Objects.hashCode()
[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 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 import org.opendaylight.yangtools.concepts.Immutable;
21 import org.opendaylight.yangtools.objcache.ObjectCache;
22 import org.opendaylight.yangtools.objcache.ObjectCacheFactory;
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 ObjectCache CACHE = ObjectCacheFactory.getObjectCache(QName.class);
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 ObjectCache} policy.
77      */
78     public static QName cachedReference(final QName qname) {
79         // We also want to make sure we keep the QNameModule cached
80         final QNameModule myMod = qname.getModule();
81         final QNameModule cacheMod = QNameModule.cachedReference(myMod);
82
83         final QName what;
84         if (cacheMod.equals(myMod)) {
85             what = qname;
86         } else {
87             what = QName.create(cacheMod, qname.localName);
88         }
89
90         return CACHE.getReference(what);
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(QNameModule.create(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 (final 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             final String namespace = matcher.group(1);
126             final String revision = matcher.group(2);
127             final 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             final URI namespace = URI.create(matcher.group(1));
133             final 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             final 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     @Override
185     public int hashCode() {
186         final int prime = 31;
187         int result = 1;
188         result = prime * result + Objects.hashCode(localName);
189         result = prime * result + module.hashCode();
190         return result;
191     }
192
193     /**
194      *
195      * Compares the specified object with this list for equality.  Returns
196      * <tt>true</tt> if and only if the specified object is also instance of
197      * {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
198      * {@link #getRevision()} are equals to same properties of this instance.
199      *
200      * @param obj the object to be compared for equality with this QName
201      * @return <tt>true</tt> if the specified object is equal to this QName
202      *
203      */
204     @Override
205     public boolean equals(final Object obj) {
206         if (this == obj) {
207             return true;
208         }
209         if (!(obj instanceof QName)) {
210             return false;
211         }
212         final QName other = (QName) obj;
213         if (localName == null) {
214             if (other.localName != null) {
215                 return false;
216             }
217         } else if (!localName.equals(other.localName)) {
218             return false;
219         }
220         return module.equals(other.module);
221     }
222
223     public static QName create(final QName base, final String localName) {
224         return create(base.getModule(), localName);
225     }
226
227     /**
228      * Creates new QName.
229      *
230      * @param qnameModule
231      *            Namespace and revision enclosed as a QNameModule
232      * @param localName
233      *            Local name part of QName. MUST NOT BE null.
234      * @return Instance of QName
235      */
236     public static QName create(final QNameModule qnameModule, final String localName) {
237         return new QName(Preconditions.checkNotNull(qnameModule,"module may not be null"), localName);
238     }
239
240     /**
241      * Creates new QName.
242      *
243      * @param namespace
244      *            Namespace of QName or null if namespace is undefined.
245      * @param revision
246      *            Revision of namespace or null if revision is unspecified.
247      * @param localName
248      *            Local name part of QName. MUST NOT BE null.
249      * @return Instance of QName
250      */
251     public static QName create(final URI namespace, final Date revision, final String localName) {
252         return create(QNameModule.create(namespace, revision), localName);
253     }
254
255     /**
256      *
257      * Creates new QName.
258      *
259      * @param namespace
260      *            Namespace of QName, MUST NOT BE Null.
261      * @param revision
262      *            Revision of namespace / YANG module. MUST NOT BE null, MUST BE
263      *            in format <code>YYYY-mm-dd</code>.
264      * @param localName
265      *            Local name part of QName. MUST NOT BE null.
266      * @return
267      * @throws NullPointerException
268      *             If any of parameters is null.
269      * @throws IllegalArgumentException
270      *             If <code>namespace</code> is not valid URI or
271      *             <code>revision</code> is not according to format
272      *             <code>YYYY-mm-dd</code>.
273      */
274     public static QName create(final String namespace, final String revision, final String localName) {
275         final URI namespaceUri = parseNamespace(namespace);
276         final Date revisionDate = parseRevision(revision);
277         return create(namespaceUri, revisionDate, localName);
278     }
279
280     private static URI parseNamespace(final String namespace) {
281         try {
282             return new URI(namespace);
283         } catch (final URISyntaxException ue) {
284             throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
285         }
286     }
287
288     /**
289      * Creates new QName.
290      *
291      * @param namespace
292      *            Namespace of QName, MUST NOT BE Null.
293      * @param localName
294      *            Local name part of QName. MUST NOT BE null.
295      * @return
296      * @throws NullPointerException
297      *             If any of parameters is null.
298      * @throws IllegalArgumentException
299      *             If <code>namespace</code> is not valid URI.
300      */
301     public static QName create(final String namespace, final String localName) {
302         return create(parseNamespace(namespace), null, localName);
303     }
304
305     @Override
306     public String toString() {
307         final StringBuilder sb = new StringBuilder();
308         if (getNamespace() != null) {
309             sb.append(QNAME_LEFT_PARENTHESIS + getNamespace());
310
311             if (getFormattedRevision() != null) {
312                 sb.append(QNAME_REVISION_DELIMITER + getFormattedRevision());
313             }
314             sb.append(QNAME_RIGHT_PARENTHESIS);
315         }
316         sb.append(localName);
317         return sb.toString();
318     }
319
320     /**
321      * Return string representation of revision in format
322      * <code>YYYY-mm-dd</code>
323      *
324      * YANG Specification defines format for <code>revision</code> as
325      * YYYY-mm-dd. This format for revision is reused accross multiple places
326      * such as capabilities URI, YANG modules, etc.
327      *
328      * @return String representation of revision or null, if revision is not
329      *         set.
330      */
331     public String getFormattedRevision() {
332         return module.getFormattedRevision();
333     }
334
335     /**
336      * Creates copy of this with revision and prefix unset.
337      *
338      * @return copy of this QName with revision and prefix unset.
339      */
340     public QName withoutRevision() {
341         return create(getNamespace(), null, localName);
342     }
343
344     public static Date parseRevision(final String formatedDate) {
345         try {
346             return getRevisionFormat().parse(formatedDate);
347         } catch (ParseException | RuntimeException e) {
348             throw new IllegalArgumentException(
349                     String.format("Revision '%s'is not in a supported format", formatedDate), e);
350         }
351     }
352
353     /**
354      * Formats {@link Date} representing revision to 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      * @param revision
362      *            Date object to format or null
363      * @return String representation or null if the input was null.
364      */
365     public static String formattedRevision(final Date revision) {
366         if (revision == null) {
367             return null;
368         }
369         return getRevisionFormat().format(revision);
370     }
371
372     /**
373      *
374      * Compares this QName to other, without comparing revision.
375      *
376      * Compares instance of this to other instance of QName and returns true if
377      * both instances have equal <code>localName</code> ({@link #getLocalName()}
378      * ) and <code>namespace</code> ({@link #getNamespace()}).
379      *
380      * @param other
381      *            Other QName. Must not be null.
382      * @return true if this instance and other have equals localName and
383      *         namespace.
384      * @throws NullPointerException
385      *             if <code>other</code> is null.
386      */
387     public boolean isEqualWithoutRevision(final QName other) {
388         return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
389     }
390
391     @Override
392     public int compareTo(final QName other) {
393         // compare mandatory localName parameter
394         int result = localName.compareTo(other.localName);
395         if (result != 0) {
396             return result;
397         }
398
399         // compare nullable namespace parameter
400         if (getNamespace() == null) {
401             if (other.getNamespace() != null) {
402                 return -1;
403             }
404         } else {
405             if (other.getNamespace() == null) {
406                 return 1;
407             }
408             result = getNamespace().compareTo(other.getNamespace());
409             if (result != 0) {
410                 return result;
411             }
412         }
413
414         // compare nullable revision parameter
415         if (getRevision() == null) {
416             if (other.getRevision() != null) {
417                 return -1;
418             }
419         } else {
420             if (other.getRevision() == null) {
421                 return 1;
422             }
423             result = getRevision().compareTo(other.getRevision());
424             if (result != 0) {
425                 return result;
426             }
427         }
428
429         return result;
430     }
431
432 }