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