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.NonNull;
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.
56 public final class QName implements Immutable, Serializable, Comparable<QName>, Identifier, WritableObject {
57 private static final Interner<QName> INTERNER = Interners.newWeakInterner();
58 private static final long serialVersionUID = 5398411242927766414L;
60 static final String QNAME_REVISION_DELIMITER = "?revision=";
61 static final String QNAME_LEFT_PARENTHESIS = "(";
62 static final String QNAME_RIGHT_PARENTHESIS = ")";
65 private static final String QNAME_STRING_FULL = "^\\((.+)\\?revision=(.+)\\)(.+)$";
66 private static final Pattern QNAME_PATTERN_FULL = Pattern.compile(QNAME_STRING_FULL);
69 private static final String QNAME_STRING_NO_REVISION = "^\\((.+)\\)(.+)$";
70 private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile(QNAME_STRING_NO_REVISION);
72 private static final char[] ILLEGAL_CHARACTERS = { '?', '(', ')', '&', ':' };
74 private final @NonNull QNameModule module;
75 private final @NonNull String localName;
76 private transient int hash = 0;
78 private QName(final QNameModule module, final String localName) {
79 this.module = requireNonNull(module);
80 this.localName = requireNonNull(localName);
87 * the namespace assigned to the YANG module
89 * YANG schema identifier
91 private QName(final URI namespace, final String localName) {
92 this(QNameModule.create(namespace), checkLocalName(localName));
95 private static String checkLocalName(final String localName) {
96 checkArgument(localName != null, "Parameter 'localName' may not be null.");
97 checkArgument(!localName.isEmpty(), "Parameter 'localName' must be a non-empty string.");
99 for (final char c : ILLEGAL_CHARACTERS) {
100 if (localName.indexOf(c) != -1) {
101 throw new IllegalArgumentException("Parameter 'localName':'" + localName
102 + "' contains illegal character '" + c + "'");
108 public static QName create(final String input) {
109 Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
110 if (matcher.matches()) {
111 final String namespace = matcher.group(1);
112 final String revision = matcher.group(2);
113 final String localName = matcher.group(3);
114 return create(namespace, revision, localName);
116 matcher = QNAME_PATTERN_NO_REVISION.matcher(input);
117 if (matcher.matches()) {
118 final URI namespace = URI.create(matcher.group(1));
119 final String localName = matcher.group(2);
120 return new QName(namespace, localName);
122 throw new IllegalArgumentException("Invalid input: " + input);
125 public static QName create(final QName base, final String localName) {
126 return create(base.getModule(), localName);
133 * Namespace and revision enclosed as a QNameModule
135 * Local name part of QName. MUST NOT BE null.
136 * @return Instance of QName
138 public static QName create(final QNameModule qnameModule, final String localName) {
139 return new QName(requireNonNull(qnameModule, "module may not be null"), checkLocalName(localName));
146 * Namespace of QName or null if namespace is undefined.
148 * Revision of namespace or null if revision is unspecified.
150 * Local name part of QName. MUST NOT BE null.
151 * @return Instance of QName
153 public static QName create(final URI namespace, final @Nullable Revision revision, final String localName) {
154 return create(QNameModule.create(namespace, revision), localName);
161 * Namespace of QName or null if namespace is undefined.
163 * Revision of namespace.
165 * Local name part of QName. MUST NOT BE null.
166 * @return Instance of QName
168 public static QName create(final URI namespace, final Optional<Revision> revision, final String localName) {
169 return create(QNameModule.create(namespace, revision), localName);
176 * Namespace of QName or null if namespace is undefined.
178 * Revision of namespace or null if revision is unspecified.
180 * Local name part of QName. MUST NOT BE null.
181 * @return Instance of QName
183 public static QName create(final String namespace, final String localName, final Revision revision) {
184 final URI namespaceUri = parseNamespace(namespace);
185 return create(QNameModule.create(namespaceUri, revision), localName);
192 * Namespace of QName, MUST NOT BE Null.
194 * Revision of namespace / YANG module. MUST NOT BE null, MUST BE
195 * in format <code>YYYY-mm-dd</code>.
197 * Local name part of QName. MUST NOT BE null.
198 * @return A new QName
199 * @throws NullPointerException
200 * If any of parameters is null.
201 * @throws IllegalArgumentException
202 * If <code>namespace</code> is not valid URI or
203 * <code>revision</code> is not according to format
204 * <code>YYYY-mm-dd</code>.
206 public static QName create(final String namespace, final String revision, final String localName) {
207 final URI namespaceUri = parseNamespace(namespace);
208 final Revision revisionDate = Revision.of(revision);
209 return create(namespaceUri, revisionDate, localName);
216 * Namespace of QName, MUST NOT BE Null.
218 * Local name part of QName. MUST NOT BE null.
219 * @return A new QName
220 * @throws NullPointerException
221 * If any of parameters is null.
222 * @throws IllegalArgumentException
223 * If <code>namespace</code> is not valid URI.
225 public static QName create(final String namespace, final String localName) {
226 return create(parseNamespace(namespace), localName);
233 * Namespace of QName, MUST NOT BE null.
235 * Local name part of QName. MUST NOT BE null.
236 * @return A new QName
237 * @throws NullPointerException
238 * If any of parameters is null.
239 * @throws IllegalArgumentException
240 * If <code>namespace</code> is not valid URI.
242 public static QName create(final URI namespace, final String localName) {
243 return new QName(namespace, localName);
247 * Read a QName from a DataInput. The format is expected to match the output format of {@link #writeTo(DataOutput)}.
249 * @param in DataInput to read
250 * @return A QName instance
251 * @throws IOException if I/O error occurs
253 public static QName readFrom(final DataInput in) throws IOException {
254 final QNameModule module = QNameModule.readFrom(in);
255 return new QName(module, checkLocalName(in.readUTF()));
259 * Get the module component of the QName.
261 * @return Module component
263 public QNameModule getModule() {
268 * Returns XMLNamespace assigned to the YANG module.
270 * @return XMLNamespace assigned to the YANG module.
272 public URI getNamespace() {
273 return module.getNamespace();
277 * Returns YANG schema identifier which were defined for this node in the
280 * @return YANG schema identifier which were defined for this node in the
283 public String getLocalName() {
288 * Returns revision of the YANG module if the module has defined revision.
290 * @return revision of the YANG module if the module has defined revision.
292 public Optional<Revision> getRevision() {
293 return module.getRevision();
297 * Return an interned reference to a equivalent QName.
299 * @return Interned reference, or this object if it was interned.
301 public QName intern() {
302 // We also want to make sure we keep the QNameModule cached
303 final QNameModule cacheMod = module.intern();
305 // Identity comparison is here on purpose, as we are deciding whether to potentially store 'qname' into the
306 // interner. It is important that it does not hold user-supplied reference (such a String instance from
307 // parsing of an XML document).
308 final QName template = cacheMod == module ? this : QName.create(cacheMod, localName.intern());
310 return INTERNER.intern(template);
314 public int hashCode() {
316 hash = Objects.hash(module, localName);
322 * Compares the specified object with this list for equality. Returns
323 * <tt>true</tt> if and only if the specified object is also instance of
324 * {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
325 * {@link #getRevision()} are equals to same properties of this instance.
327 * @param obj the object to be compared for equality with this QName
328 * @return <tt>true</tt> if the specified object is equal to this QName
332 public boolean equals(final Object obj) {
336 if (!(obj instanceof QName)) {
339 final QName other = (QName) obj;
340 return Objects.equals(localName, other.localName) && module.equals(other.module);
343 private static URI parseNamespace(final String namespace) {
345 return new URI(namespace);
346 } catch (final URISyntaxException ue) {
347 throw new IllegalArgumentException("Namespace '" + namespace + "' is not a valid URI", ue);
352 public String toString() {
353 final StringBuilder sb = new StringBuilder();
354 if (getNamespace() != null) {
355 sb.append(QNAME_LEFT_PARENTHESIS).append(getNamespace());
357 final Optional<Revision> rev = getRevision();
358 if (rev.isPresent()) {
359 sb.append(QNAME_REVISION_DELIMITER).append(rev.get());
361 sb.append(QNAME_RIGHT_PARENTHESIS);
363 sb.append(localName);
364 return sb.toString();
368 * Returns a QName with the specified QNameModule and the same localname as this one.
370 * @param newModule New QNameModule to use
371 * @return a QName with specified QNameModule and same local name as this one
373 public QName withModule(@NonNull final QNameModule newModule) {
374 return new QName(newModule, localName);
378 * Returns a QName with the same namespace and local name, but with no revision. If this QName does not have
379 * a Revision, this object is retured.
381 * @return a QName with the same namespace and local name, but with no revision.
383 public QName withoutRevision() {
384 return getRevision().isPresent() ? new QName(module.withoutRevision(), localName) : this;
388 * Formats {@link Revision} representing revision to format <code>YYYY-mm-dd</code>
391 * YANG Specification defines format for <code>revision</code> as
392 * YYYY-mm-dd. This format for revision is reused accross multiple places
393 * such as capabilities URI, YANG modules, etc.
396 * Date object to format
397 * @return String representation or null if the input was null.
399 public static String formattedRevision(final Optional<Revision> revision) {
400 return revision.map(Revision::toString).orElse(null);
404 * Compares this QName to other, without comparing revision.
407 * Compares instance of this to other instance of QName and returns true if
408 * both instances have equal <code>localName</code> ({@link #getLocalName()}
409 * ) and <code>namespace</code> ({@link #getNamespace()}).
412 * Other QName. Must not be null.
413 * @return true if this instance and other have equals localName and
415 * @throws NullPointerException
416 * if <code>other</code> is null.
418 public boolean isEqualWithoutRevision(final QName other) {
419 return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
422 // FIXME: this comparison function looks odd. We are sorting first by local name and then by module? What is
423 // the impact on iteration order of SortedMap<QName, ?>?
425 @SuppressWarnings("checkstyle:parameterName")
426 public int compareTo(final QName o) {
427 // compare mandatory localName parameter
428 int result = localName.compareTo(o.localName);
432 return module.compareTo(o.module);
436 public void writeTo(final DataOutput out) throws IOException {
438 out.writeUTF(localName);