2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.common;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.collect.Interner;
14 import com.google.common.collect.Interners;
15 import java.io.DataInput;
16 import java.io.DataOutput;
17 import java.io.IOException;
18 import java.io.Serializable;
20 import java.net.URISyntaxException;
21 import java.util.Objects;
22 import java.util.Optional;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import javax.annotation.RegEx;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.yangtools.concepts.Identifier;
29 import org.opendaylight.yangtools.concepts.Immutable;
30 import org.opendaylight.yangtools.concepts.WritableObject;
33 * The QName from XML consists of local name of element and XML namespace, but
34 * for our use, we added module revision to it.
37 * In YANG context QName is full name of defined node, type, procedure or
38 * notification. QName consists of XML namespace, YANG model revision and local
39 * name of defined type. It is used to prevent name clashes between nodes with
40 * same local name, but from different schemas.
43 * <li><b>XMLNamespace</b> - {@link #getNamespace()} - the namespace assigned to the YANG module which
44 * defined element, type, procedure or notification.</li>
45 * <li><b>Revision</b> - {@link #getRevision()} - the revision of the YANG module which describes the
47 * <li><b>LocalName</b> - {@link #getLocalName()} - the YANG schema identifier which were defined for this
48 * node in the YANG module</li>
52 * QName may also have <code>prefix</code> assigned, but prefix does not
53 * affect equality and identity of two QNames and carry only information
54 * which may be useful for serializers / deserializers.
57 public final class QName implements Immutable, Serializable, Comparable<QName>, Identifier, WritableObject {
58 private static final Interner<QName> INTERNER = Interners.newWeakInterner();
59 private static final long serialVersionUID = 5398411242927766414L;
61 static final String QNAME_REVISION_DELIMITER = "?revision=";
62 static final String QNAME_LEFT_PARENTHESIS = "(";
63 static final String QNAME_RIGHT_PARENTHESIS = ")";
66 private static final String QNAME_STRING_FULL = "^\\((.+)\\?revision=(.+)\\)(.+)$";
67 private static final Pattern QNAME_PATTERN_FULL = Pattern.compile(QNAME_STRING_FULL);
70 private static final String QNAME_STRING_NO_REVISION = "^\\((.+)\\)(.+)$";
71 private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile(QNAME_STRING_NO_REVISION);
73 private static final char[] ILLEGAL_CHARACTERS = { '?', '(', ')', '&', ':' };
75 private final QNameModule module;
76 private final String localName;
77 private transient int hash = 0;
79 private QName(final QNameModule module, final String localName) {
80 this.module = requireNonNull(module);
81 this.localName = requireNonNull(localName);
88 * the namespace assigned to the YANG module
90 * YANG schema identifier
92 private QName(final URI namespace, final String localName) {
93 this(QNameModule.create(namespace), checkLocalName(localName));
96 private static String checkLocalName(final String localName) {
97 checkArgument(localName != null, "Parameter 'localName' may not be null.");
98 checkArgument(!localName.isEmpty(), "Parameter 'localName' must be a non-empty string.");
100 for (final char c : ILLEGAL_CHARACTERS) {
101 if (localName.indexOf(c) != -1) {
102 throw new IllegalArgumentException("Parameter 'localName':'" + localName
103 + "' contains illegal character '" + c + "'");
109 public static QName create(final String input) {
110 Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
111 if (matcher.matches()) {
112 final String namespace = matcher.group(1);
113 final String revision = matcher.group(2);
114 final String localName = matcher.group(3);
115 return create(namespace, revision, localName);
117 matcher = QNAME_PATTERN_NO_REVISION.matcher(input);
118 if (matcher.matches()) {
119 final URI namespace = URI.create(matcher.group(1));
120 final String localName = matcher.group(2);
121 return new QName(namespace, localName);
123 throw new IllegalArgumentException("Invalid input: " + input);
126 public static QName create(final QName base, final String localName) {
127 return create(base.getModule(), localName);
133 * @param qnameModule Namespace and revision enclosed as a QNameModule
134 * @param localName Local name part of QName. MUST NOT BE null.
135 * @return Instance of QName
137 public static QName create(final QNameModule qnameModule, final String localName) {
138 return new QName(requireNonNull(qnameModule, "module may not be null"), checkLocalName(localName));
144 * @param namespace Namespace of QName or null if namespace is undefined.
145 * @param revision Revision of namespace or null if revision is unspecified.
146 * @param localName Local name part of QName. MUST NOT BE null.
147 * @return Instance of QName
149 public static QName create(final URI namespace, final @Nullable Revision revision, final String localName) {
150 return create(QNameModule.create(namespace, revision), localName);
156 * @param namespace Namespace of QName or null if namespace is undefined.
157 * @param revision Revision of namespace.
158 * @param localName Local name part of QName. MUST NOT BE null.
159 * @return Instance of QName
161 public static QName create(final URI namespace, final Optional<Revision> revision, final String localName) {
162 return create(QNameModule.create(namespace, revision), localName);
169 * Namespace of QName or null if namespace is undefined.
171 * Revision of namespace or null if revision is unspecified.
173 * Local name part of QName. MUST NOT BE null.
174 * @return Instance of QName
176 public static QName create(final String namespace, final String localName, final Revision revision) {
177 final URI namespaceUri = parseNamespace(namespace);
178 return create(QNameModule.create(namespaceUri, revision), localName);
185 * Namespace of QName, MUST NOT BE Null.
187 * Revision of namespace / YANG module. MUST NOT BE null, MUST BE
188 * in format <code>YYYY-mm-dd</code>.
190 * Local name part of QName. MUST NOT BE null.
191 * @return A new QName
192 * @throws NullPointerException
193 * If any of parameters is null.
194 * @throws IllegalArgumentException
195 * If <code>namespace</code> is not valid URI or
196 * <code>revision</code> is not according to format
197 * <code>YYYY-mm-dd</code>.
199 public static QName create(final String namespace, final String revision, final String localName) {
200 final URI namespaceUri = parseNamespace(namespace);
201 final Revision revisionDate = Revision.of(revision);
202 return create(namespaceUri, revisionDate, localName);
208 * @param namespace Namespace of QName, MUST NOT BE Null.
209 * @param localName Local name part of QName. MUST NOT BE null.
210 * @return A new QName
211 * @throws NullPointerException If any of parameters is null.
212 * @throws IllegalArgumentException If <code>namespace</code> is not valid URI.
214 public static QName create(final String namespace, final String localName) {
215 return create(parseNamespace(namespace), localName);
221 * @param namespace Namespace of QName, MUST NOT BE null.
222 * @param localName Local name part of QName. MUST NOT BE null.
223 * @return A new QName
224 * @throws NullPointerException If any of parameters is null.
225 * @throws IllegalArgumentException If <code>namespace</code> is not valid URI.
227 public static QName create(final URI namespace, final String localName) {
228 return new QName(namespace, localName);
232 * Read a QName from a DataInput. The format is expected to match the output format of {@link #writeTo(DataOutput)}.
234 * @param in DataInput to read
235 * @return A QName instance
236 * @throws IOException if I/O error occurs
238 public static QName readFrom(final DataInput in) throws IOException {
239 final QNameModule module = QNameModule.readFrom(in);
240 return new QName(module, checkLocalName(in.readUTF()));
244 * Get the module component of the QName.
246 * @return Module component
248 public QNameModule getModule() {
253 * Returns XMLNamespace assigned to the YANG module.
255 * @return XMLNamespace assigned to the YANG module.
257 public URI getNamespace() {
258 return module.getNamespace();
262 * Returns YANG schema identifier which were defined for this node in the
265 * @return YANG schema identifier which were defined for this node in the
268 public String getLocalName() {
273 * Returns revision of the YANG module if the module has defined revision.
275 * @return revision of the YANG module if the module has defined revision.
277 public Optional<Revision> getRevision() {
278 return module.getRevision();
282 * Return an interned reference to a equivalent QName.
284 * @return Interned reference, or this object if it was interned.
286 public QName intern() {
287 // We also want to make sure we keep the QNameModule cached
288 final QNameModule cacheMod = module.intern();
290 // Identity comparison is here on purpose, as we are deciding whether to potentially store 'qname' into the
291 // interner. It is important that it does not hold user-supplied reference (such a String instance from
292 // parsing of an XML document).
293 final QName template = cacheMod == module ? this : QName.create(cacheMod, localName.intern());
295 return INTERNER.intern(template);
299 public int hashCode() {
301 hash = Objects.hash(module, localName);
307 * Compares the specified object with this list for equality. Returns
308 * <tt>true</tt> if and only if the specified object is also instance of
309 * {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
310 * {@link #getRevision()} are equals to same properties of this instance.
312 * @param obj the object to be compared for equality with this QName
313 * @return <tt>true</tt> if the specified object is equal to this QName
317 public boolean equals(final @Nullable Object obj) {
321 if (!(obj instanceof QName)) {
324 final QName other = (QName) obj;
325 return Objects.equals(localName, other.localName) && module.equals(other.module);
328 private static URI parseNamespace(final String namespace) {
330 return new URI(namespace);
331 } catch (final URISyntaxException ue) {
332 throw new IllegalArgumentException("Namespace '" + namespace + "' is not a valid URI", ue);
337 public String toString() {
338 final StringBuilder sb = new StringBuilder();
339 if (getNamespace() != null) {
340 sb.append(QNAME_LEFT_PARENTHESIS).append(getNamespace());
342 final Optional<Revision> rev = getRevision();
343 if (rev.isPresent()) {
344 sb.append(QNAME_REVISION_DELIMITER).append(rev.get());
346 sb.append(QNAME_RIGHT_PARENTHESIS);
348 sb.append(localName);
349 return sb.toString();
353 * Returns a QName with the specified QNameModule and the same localname as this one.
355 * @param newModule New QNameModule to use
356 * @return a QName with specified QNameModule and same local name as this one
358 public QName withModule(final QNameModule newModule) {
359 return new QName(newModule, localName);
363 * Returns a QName with the same namespace and local name, but with no revision. If this QName does not have
364 * a Revision, this object is returned.
366 * @return a QName with the same namespace and local name, but with no revision.
368 public QName withoutRevision() {
369 return getRevision().isPresent() ? new QName(module.withoutRevision(), localName) : this;
373 * Formats {@link Revision} representing revision to format <code>YYYY-mm-dd</code>
376 * YANG Specification defines format for <code>revision</code> as
377 * YYYY-mm-dd. This format for revision is reused accross multiple places
378 * such as capabilities URI, YANG modules, etc.
381 * Date object to format
382 * @return String representation or null if the input was null.
384 public static String formattedRevision(final Optional<Revision> revision) {
385 return revision.map(Revision::toString).orElse(null);
389 * Compares this QName to other, without comparing revision.
392 * Compares instance of this to other instance of QName and returns true if
393 * both instances have equal <code>localName</code> ({@link #getLocalName()}
394 * ) and <code>namespace</code> ({@link #getNamespace()}).
397 * Other QName. Must not be null.
398 * @return true if this instance and other have equals localName and
400 * @throws NullPointerException
401 * if <code>other</code> is null.
403 public boolean isEqualWithoutRevision(final QName other) {
404 return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
407 // FIXME: this comparison function looks odd. We are sorting first by local name and then by module? What is
408 // the impact on iteration order of SortedMap<QName, ?>?
410 @SuppressWarnings("checkstyle:parameterName")
411 public int compareTo(final QName o) {
412 // compare mandatory localName parameter
413 int result = localName.compareTo(o.localName);
417 return module.compareTo(o.module);
421 public void writeTo(final DataOutput out) throws IOException {
423 out.writeUTF(localName);