Use Objects.equals() in QName.equals()
[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         return Objects.equals(localName, other.localName) && module.equals(other.module);
214     }
215
216     public static QName create(final QName base, final String localName) {
217         return create(base.getModule(), localName);
218     }
219
220     /**
221      * Creates new QName.
222      *
223      * @param qnameModule
224      *            Namespace and revision enclosed as a QNameModule
225      * @param localName
226      *            Local name part of QName. MUST NOT BE null.
227      * @return Instance of QName
228      */
229     public static QName create(final QNameModule qnameModule, final String localName) {
230         return new QName(Preconditions.checkNotNull(qnameModule,"module may not be null"), localName);
231     }
232
233     /**
234      * Creates new QName.
235      *
236      * @param namespace
237      *            Namespace of QName or null if namespace is undefined.
238      * @param revision
239      *            Revision of namespace or null if revision is unspecified.
240      * @param localName
241      *            Local name part of QName. MUST NOT BE null.
242      * @return Instance of QName
243      */
244     public static QName create(final URI namespace, final Date revision, final String localName) {
245         return create(QNameModule.create(namespace, revision), localName);
246     }
247
248     /**
249      *
250      * Creates new QName.
251      *
252      * @param namespace
253      *            Namespace of QName, MUST NOT BE Null.
254      * @param revision
255      *            Revision of namespace / YANG module. MUST NOT BE null, MUST BE
256      *            in format <code>YYYY-mm-dd</code>.
257      * @param localName
258      *            Local name part of QName. MUST NOT BE null.
259      * @return
260      * @throws NullPointerException
261      *             If any of parameters is null.
262      * @throws IllegalArgumentException
263      *             If <code>namespace</code> is not valid URI or
264      *             <code>revision</code> is not according to format
265      *             <code>YYYY-mm-dd</code>.
266      */
267     public static QName create(final String namespace, final String revision, final String localName) {
268         final URI namespaceUri = parseNamespace(namespace);
269         final Date revisionDate = parseRevision(revision);
270         return create(namespaceUri, revisionDate, localName);
271     }
272
273     private static URI parseNamespace(final String namespace) {
274         try {
275             return new URI(namespace);
276         } catch (final URISyntaxException ue) {
277             throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
278         }
279     }
280
281     /**
282      * Creates new QName.
283      *
284      * @param namespace
285      *            Namespace of QName, MUST NOT BE Null.
286      * @param localName
287      *            Local name part of QName. MUST NOT BE null.
288      * @return
289      * @throws NullPointerException
290      *             If any of parameters is null.
291      * @throws IllegalArgumentException
292      *             If <code>namespace</code> is not valid URI.
293      */
294     public static QName create(final String namespace, final String localName) {
295         return create(parseNamespace(namespace), null, localName);
296     }
297
298     @Override
299     public String toString() {
300         final StringBuilder sb = new StringBuilder();
301         if (getNamespace() != null) {
302             sb.append(QNAME_LEFT_PARENTHESIS + getNamespace());
303
304             if (getFormattedRevision() != null) {
305                 sb.append(QNAME_REVISION_DELIMITER + getFormattedRevision());
306             }
307             sb.append(QNAME_RIGHT_PARENTHESIS);
308         }
309         sb.append(localName);
310         return sb.toString();
311     }
312
313     /**
314      * Return string representation of revision in format
315      * <code>YYYY-mm-dd</code>
316      *
317      * YANG Specification defines format for <code>revision</code> as
318      * YYYY-mm-dd. This format for revision is reused accross multiple places
319      * such as capabilities URI, YANG modules, etc.
320      *
321      * @return String representation of revision or null, if revision is not
322      *         set.
323      */
324     public String getFormattedRevision() {
325         return module.getFormattedRevision();
326     }
327
328     /**
329      * Creates copy of this with revision and prefix unset.
330      *
331      * @return copy of this QName with revision and prefix unset.
332      */
333     public QName withoutRevision() {
334         return create(getNamespace(), null, localName);
335     }
336
337     public static Date parseRevision(final String formatedDate) {
338         try {
339             return getRevisionFormat().parse(formatedDate);
340         } catch (ParseException | RuntimeException e) {
341             throw new IllegalArgumentException(
342                     String.format("Revision '%s'is not in a supported format", formatedDate), e);
343         }
344     }
345
346     /**
347      * Formats {@link Date} representing revision to format
348      * <code>YYYY-mm-dd</code>
349      *
350      * YANG Specification defines format for <code>revision</code> as
351      * YYYY-mm-dd. This format for revision is reused accross multiple places
352      * such as capabilities URI, YANG modules, etc.
353      *
354      * @param revision
355      *            Date object to format or null
356      * @return String representation or null if the input was null.
357      */
358     public static String formattedRevision(final Date revision) {
359         if (revision == null) {
360             return null;
361         }
362         return getRevisionFormat().format(revision);
363     }
364
365     /**
366      *
367      * Compares this QName to other, without comparing revision.
368      *
369      * Compares instance of this to other instance of QName and returns true if
370      * both instances have equal <code>localName</code> ({@link #getLocalName()}
371      * ) and <code>namespace</code> ({@link #getNamespace()}).
372      *
373      * @param other
374      *            Other QName. Must not be null.
375      * @return true if this instance and other have equals localName and
376      *         namespace.
377      * @throws NullPointerException
378      *             if <code>other</code> is null.
379      */
380     public boolean isEqualWithoutRevision(final QName other) {
381         return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
382     }
383
384     @Override
385     public int compareTo(final QName other) {
386         // compare mandatory localName parameter
387         int result = localName.compareTo(other.localName);
388         if (result != 0) {
389             return result;
390         }
391
392         // compare nullable namespace parameter
393         if (getNamespace() == null) {
394             if (other.getNamespace() != null) {
395                 return -1;
396             }
397         } else {
398             if (other.getNamespace() == null) {
399                 return 1;
400             }
401             result = getNamespace().compareTo(other.getNamespace());
402             if (result != 0) {
403                 return result;
404             }
405         }
406
407         // compare nullable revision parameter
408         if (getRevision() == null) {
409             if (other.getRevision() != null) {
410                 return -1;
411             }
412         } else {
413             if (other.getRevision() == null) {
414                 return 1;
415             }
416             result = getRevision().compareTo(other.getRevision());
417             if (result != 0) {
418                 return result;
419             }
420         }
421
422         return result;
423     }
424
425 }