Make QName use externalizable proxy pattern
[yangtools.git] / yang / yang-common / src / main / java / org / opendaylight / yangtools / yang / common / QName.java
index 0ac89ae8da2c1d634d134bc07977877e5a9c4484..2f6c2bf6c421d4bba45e0b0bb7044fb9380fdfce 100644 (file)
@@ -7,27 +7,40 @@
  */
 package org.opendaylight.yangtools.yang.common;
 
-import static org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil.getRevisionFormat;
-
+import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.Objects.requireNonNull;
+
+import com.google.common.base.CharMatcher;
+import com.google.common.collect.Interner;
+import com.google.common.collect.Interners;
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
 import java.io.Serializable;
 import java.net.URI;
 import java.net.URISyntaxException;
-import java.text.ParseException;
-import java.util.Date;
 import java.util.Objects;
+import java.util.Optional;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
+import javax.annotation.RegEx;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.yangtools.concepts.Identifier;
 import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.concepts.WritableObject;
 
 /**
- * The QName from XML consists of local name of element and XML namespace, but
- * for our use, we added module revision to it.
+ * The QName from XML consists of local name of element and XML namespace, but for our use, we added module revision to
+ * it.
+ *
+ * <p>
+ * In YANG context QName is full name of defined node, type, procedure or notification. QName consists of XML namespace,
+ * YANG model revision and local name of defined type. It is used to prevent name clashes between nodes with same local
+ * name, but from different schemas.
  *
- * In YANG context QName is full name of defined node, type, procedure or
- * notification. QName consists of XML namespace, YANG model revision and local
- * name of defined type. It is used to prevent name clashes between nodes with
- * same local name, but from different schemas.
+ * <p>
+ * The local name must conform to <a href="https://tools.ietf.org/html/rfc7950#section-6.2">RFC7950 Section 6.2</a>.
  *
  * <ul>
  * <li><b>XMLNamespace</b> - {@link #getNamespace()} - the namespace assigned to the YANG module which
@@ -37,55 +50,35 @@ import org.opendaylight.yangtools.concepts.Immutable;
  * <li><b>LocalName</b> - {@link #getLocalName()} - the YANG schema identifier which were defined for this
  * node in the YANG module</li>
  * </ul>
- *
- * QName may also have <code>prefix</code> assigned, but prefix does not
- * affect equality and identity of two QNames and carry only information
- * which may be useful for serializers / deserializers.
- *
- *
  */
-public final class QName implements Immutable, Serializable, Comparable<QName> {
+public final class QName implements Immutable, Serializable, Comparable<QName>, Identifier, WritableObject {
+    private static final Interner<QName> INTERNER = Interners.newWeakInterner();
     private static final long serialVersionUID = 5398411242927766414L;
 
     static final String QNAME_REVISION_DELIMITER = "?revision=";
     static final String QNAME_LEFT_PARENTHESIS = "(";
     static final String QNAME_RIGHT_PARENTHESIS = ")";
 
-    private static final Pattern QNAME_PATTERN_FULL = Pattern.compile("^\\((.+)\\" + QNAME_REVISION_DELIMITER
-            + "(.+)\\)(.+)$");
-    private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile("^\\((.+)\\)(.+)$");
-    private static final Pattern QNAME_PATTERN_NO_NAMESPACE_NO_REVISION = Pattern.compile("^(.+)$");
+    @RegEx
+    private static final String QNAME_STRING_FULL = "^\\((.+)\\?revision=(.+)\\)(.+)$";
+    private static final Pattern QNAME_PATTERN_FULL = Pattern.compile(QNAME_STRING_FULL);
 
-    private static final char[] ILLEGAL_CHARACTERS = new char[] { '?', '(', ')', '&' };
+    @RegEx
+    private static final String QNAME_STRING_NO_REVISION = "^\\((.+)\\)(.+)$";
+    private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile(QNAME_STRING_NO_REVISION);
 
-    // Mandatory
-    private final QNameModule module;
-    // Mandatory
-    private final String localName;
-    // Nullable
-    private final String prefix;
+    private static final CharMatcher IDENTIFIER_START =
+            CharMatcher.inRange('A', 'Z').or(CharMatcher.inRange('a', 'z').or(CharMatcher.is('_'))).precomputed();
+    private static final CharMatcher NOT_IDENTIFIER_PART =
+            IDENTIFIER_START.or(CharMatcher.inRange('0', '9')).or(CharMatcher.anyOf("-.")).negate().precomputed();
 
-    private QName(final QNameModule module, final String prefix, final String localName) {
-        this.localName = checkLocalName(localName);
-        this.prefix = prefix;
-        this.module = module;
-    }
+    private final @NonNull QNameModule module;
+    private final @NonNull String localName;
+    private transient int hash = 0;
 
-    /**
-     * QName Constructor.
-     *
-     * @param namespace
-     *            the namespace assigned to the YANG module
-     * @param revision
-     *            the revision of the YANG module
-     * @param prefix
-     *            locally defined prefix assigned to local name
-     * @param localName
-     *            YANG schema identifier
-     *
-     */
-    public QName(final URI namespace, final Date revision, final String prefix, final String localName) {
-        this(QNameModule.create(namespace, revision), prefix, localName);
+    private QName(final QNameModule module, final @NonNull String localName) {
+        this.module = requireNonNull(module);
+        this.localName = requireNonNull(localName);
     }
 
     /**
@@ -96,47 +89,141 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
      * @param localName
      *            YANG schema identifier
      */
-    public QName(final URI namespace, final String localName) {
-        this(namespace, null, "", localName);
+    private QName(final URI namespace, final String localName) {
+        this(QNameModule.create(namespace), checkLocalName(localName));
     }
 
-    private static String checkLocalName(final String localName) {
-        if (localName == null) {
-            throw new IllegalArgumentException("Parameter 'localName' may not be null.");
-        }
-        if (localName.length() == 0) {
-            throw new IllegalArgumentException("Parameter 'localName' must be a non-empty string.");
-        }
-
-        for (char c : ILLEGAL_CHARACTERS) {
-            if (localName.indexOf(c) != -1) {
-                throw new IllegalArgumentException(String.format(
-                        "Parameter 'localName':'%s' contains illegal character '%s'", localName, c));
-            }
-        }
+    private static @NonNull String checkLocalName(final String localName) {
+        checkArgument(localName != null, "Parameter 'localName' may not be null.");
+        checkArgument(!localName.isEmpty(), "Parameter 'localName' must be a non-empty string.");
+        checkArgument(IDENTIFIER_START.matches(localName.charAt(0)) && NOT_IDENTIFIER_PART.indexIn(localName, 1) == -1,
+                "String '%s' is not a valid identifier", localName);
         return localName;
     }
 
-    public static QName create(final String input) {
+    public static @NonNull QName create(final String input) {
         Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
         if (matcher.matches()) {
-            String namespace = matcher.group(1);
-            String revision = matcher.group(2);
-            String localName = matcher.group(3);
+            final String namespace = matcher.group(1);
+            final String revision = matcher.group(2);
+            final String localName = matcher.group(3);
             return create(namespace, revision, localName);
         }
         matcher = QNAME_PATTERN_NO_REVISION.matcher(input);
         if (matcher.matches()) {
-            URI namespace = URI.create(matcher.group(1));
-            String localName = matcher.group(2);
+            final URI namespace = URI.create(matcher.group(1));
+            final String localName = matcher.group(2);
             return new QName(namespace, localName);
         }
-        matcher = QNAME_PATTERN_NO_NAMESPACE_NO_REVISION.matcher(input);
-        if (matcher.matches()) {
-            String localName = matcher.group(1);
-            return new QName((URI) null, localName);
-        }
-        throw new IllegalArgumentException("Invalid input:" + input);
+        throw new IllegalArgumentException("Invalid input: " + input);
+    }
+
+    public static @NonNull QName create(final QName base, final String localName) {
+        return create(base.getModule(), localName);
+    }
+
+    /**
+     * Creates new QName.
+     *
+     * @param qnameModule
+     *            Namespace and revision enclosed as a QNameModule
+     * @param localName
+     *            Local name part of QName. MUST NOT BE null.
+     * @return Instance of QName
+     */
+    public static @NonNull QName create(final QNameModule qnameModule, final String localName) {
+        return new QName(requireNonNull(qnameModule, "module may not be null"), checkLocalName(localName));
+    }
+
+    /**
+     * Creates new QName.
+     *
+     * @param namespace Namespace of QName or null if namespace is undefined.
+     * @param revision Revision of namespace or null if revision is unspecified.
+     * @param localName Local name part of QName. MUST NOT BE null.
+     * @return Instance of QName
+     */
+    public static @NonNull QName create(final URI namespace, final @Nullable Revision revision,
+            final String localName) {
+        return create(QNameModule.create(namespace, revision), localName);
+    }
+
+    /**
+     * Creates new QName.
+     *
+     * @param namespace Namespace of QName or null if namespace is undefined.
+     * @param revision Revision of namespace.
+     * @param localName Local name part of QName. MUST NOT BE null.
+     * @return Instance of QName
+     */
+    public static @NonNull QName create(final URI namespace, final Optional<Revision> revision,
+            final String localName) {
+        return create(QNameModule.create(namespace, revision), localName);
+    }
+
+    /**
+     * Creates new QName.
+     *
+     * @param namespace Namespace of QName or null if namespace is undefined.
+     * @param revision Revision of namespace or null if revision is unspecified.
+     * @param localName Local name part of QName. MUST NOT BE null.
+     * @return Instance of QName
+     */
+    public static @NonNull QName create(final String namespace, final String localName, final Revision revision) {
+        return create(QNameModule.create(parseNamespace(namespace), revision), localName);
+    }
+
+    /**
+     * Creates new QName.
+     *
+     * @param namespace Namespace of QName, MUST NOT BE Null.
+     * @param revision Revision of namespace / YANG module. MUST NOT BE null, MUST BE in format {@code YYYY-mm-dd}.
+     * @param localName Local name part of QName. MUST NOT BE null.
+     * @return A new QName
+     * @throws NullPointerException If any of parameters is null.
+     * @throws IllegalArgumentException If {@code namespace} is not valid URI or {@code revision} does not conform
+     *         to {@code YYYY-mm-dd}.
+     */
+    public static @NonNull QName create(final String namespace, final String revision, final String localName) {
+        return create(parseNamespace(namespace), Revision.of(revision), localName);
+    }
+
+    /**
+     * Creates new QName.
+     *
+     * @param namespace Namespace of QName, MUST NOT BE Null.
+     * @param localName Local name part of QName. MUST NOT BE null.
+     * @return A new QName
+     * @throws NullPointerException If any of parameters is null.
+     * @throws IllegalArgumentException If {@code namespace} is not valid URI.
+     */
+    public static @NonNull QName create(final String namespace, final String localName) {
+        return create(parseNamespace(namespace), localName);
+    }
+
+    /**
+     * Creates new QName.
+     *
+     * @param namespace Namespace of QName, MUST NOT BE null.
+     * @param localName Local name part of QName. MUST NOT BE null.
+     * @return A new QName
+     * @throws NullPointerException If any of parameters is null.
+     * @throws IllegalArgumentException If <code>namespace</code> is not valid URI.
+     */
+    public static @NonNull QName create(final URI namespace, final String localName) {
+        return new QName(namespace, localName);
+    }
+
+    /**
+     * Read a QName from a DataInput. The format is expected to match the output format of {@link #writeTo(DataOutput)}.
+     *
+     * @param in DataInput to read
+     * @return A QName instance
+     * @throws IOException if I/O error occurs
+     */
+    public static QName readFrom(final DataInput in) throws IOException {
+        final QNameModule module = QNameModule.readFrom(in);
+        return new QName(module, checkLocalName(in.readUTF()));
     }
 
     /**
@@ -144,7 +231,7 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
      *
      * @return Module component
      */
-    public QNameModule getModule() {
+    public @NonNull QNameModule getModule() {
         return module;
     }
 
@@ -153,60 +240,62 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
      *
      * @return XMLNamespace assigned to the YANG module.
      */
-    public URI getNamespace() {
+    public @NonNull URI getNamespace() {
         return module.getNamespace();
     }
 
     /**
      * Returns YANG schema identifier which were defined for this node in the
-     * YANG module
+     * YANG module.
      *
      * @return YANG schema identifier which were defined for this node in the
      *         YANG module
      */
-    public String getLocalName() {
+    public @NonNull String getLocalName() {
         return localName;
     }
 
     /**
-     * Returns revision of the YANG module if the module has defined revision,
-     * otherwise returns <code>null</code>
+     * Returns revision of the YANG module if the module has defined revision.
      *
-     * @return revision of the YANG module if the module has defined revision,
-     *         otherwise returns <code>null</code>
+     * @return revision of the YANG module if the module has defined revision.
      */
-    public Date getRevision() {
+    public @NonNull Optional<Revision> getRevision() {
         return module.getRevision();
     }
 
     /**
-     * Returns locally defined prefix assigned to local name
+     * Return an interned reference to a equivalent QName.
      *
-     * @return locally defined prefix assigned to local name
+     * @return Interned reference, or this object if it was interned.
      */
-    public String getPrefix() {
-        return prefix;
+    public @NonNull QName intern() {
+        // We also want to make sure we keep the QNameModule cached
+        final QNameModule cacheMod = module.intern();
+
+        // Identity comparison is here on purpose, as we are deciding whether to potentially store 'qname' into the
+        // interner. It is important that it does not hold user-supplied reference (such a String instance from
+        // parsing of an XML document).
+        final QName template = cacheMod == module ? this : new QName(cacheMod, localName.intern());
+
+        return INTERNER.intern(template);
     }
 
     @Override
     public int hashCode() {
-        final int prime = 31;
-        int result = 1;
-        result = prime * result + ((localName == null) ? 0 : localName.hashCode());
-        result = prime * result + module.hashCode();
-        return result;
+        if (hash == 0) {
+            hash = Objects.hash(module, localName);
+        }
+        return hash;
     }
 
     /**
-     *
-     * Compares the specified object with this list for equality.  Returns
-     * <tt>true</tt> if and only if the specified object is also instance of
-     * {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
+     * Compares the specified object with this list for equality.  Returns {@code true} if and only if the specified
+     * object is also instance of {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
      * {@link #getRevision()} are equals to same properties of this instance.
      *
-     * @param o the object to be compared for equality with this QName
-     * @return <tt>true</tt> if the specified object is equal to this QName
-     *
+     * @param obj the object to be compared for equality with this QName
+     * @return {@code true} if the specified object is equal to this QName
      */
     @Override
     public boolean equals(final Object obj) {
@@ -217,223 +306,102 @@ public final class QName implements Immutable, Serializable, Comparable<QName> {
             return false;
         }
         final QName other = (QName) obj;
-        if (localName == null) {
-            if (other.localName != null) {
-                return false;
-            }
-        } else if (!localName.equals(other.localName)) {
-            return false;
-        }
-        return module.equals(other.module);
-    }
-
-    public static QName create(final QName base, final String localName) {
-        return new QName(base.getModule(), base.getPrefix(), localName);
-    }
-
-    /**
-     * Creates new QName.
-     *
-     * @param qnameModule
-     *            Namespace and revision enclosed as a QNameModule
-     * @param prefix
-     *            Namespace prefix
-     * @param localName
-     *            Local name part of QName. MUST NOT BE null.
-     * @return Instance of QName
-     */
-    public static QName create(final QNameModule module, final String prefix, final String localName) {
-        if (module == null) {
-            throw new NullPointerException("module may not be null");
-        }
-        return new QName(module, prefix, localName);
-    }
-
-    /**
-     * Creates new QName.
-     *
-     * @param qnameModule
-     *            Namespace and revision enclosed as a QNameModule
-     * @param localName
-     *            Local name part of QName. MUST NOT BE null.
-     * @return Instance of QName
-     */
-    public static QName create(final QNameModule qnameModule, final String localName) {
-        return new QName(qnameModule, null, localName);
-    }
-
-    /**
-     * Creates new QName.
-     *
-     * @param namespace
-     *            Namespace of QName or null if namespace is undefined.
-     * @param revision
-     *            Revision of namespace or null if revision is unspecified.
-     * @param localName
-     *            Local name part of QName. MUST NOT BE null.
-     * @return Instance of QName
-     */
-    public static QName create(final URI namespace, final Date revision, final String localName) {
-        return new QName(QNameModule.create(namespace, revision), null, localName);
+        return Objects.equals(localName, other.localName) && module.equals(other.module);
     }
 
-    /**
-     *
-     * Creates new QName.
-     *
-     * @param namespace
-     *            Namespace of QName, MUST NOT BE Null.
-     * @param revision
-     *            Revision of namespace / YANG module. MUST NOT BE null, MUST BE
-     *            in format <code>YYYY-mm-dd</code>.
-     * @param localName
-     *            Local name part of QName. MUST NOT BE null.
-     * @return
-     * @throws NullPointerException
-     *             If any of paramaters is null.
-     * @throws IllegalArgumentException
-     *             If <code>namespace</code> is not valid URI or
-     *             <code>revision</code> is not according to format
-     *             <code>YYYY-mm-dd</code>.
-     */
-    public static QName create(final String namespace, final String revision, final String localName)
-            throws IllegalArgumentException {
-        final URI namespaceUri;
+    private static @NonNull URI parseNamespace(final String namespace) {
         try {
-            namespaceUri = new URI(namespace);
-        } catch (URISyntaxException ue) {
-            throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
+            return new URI(namespace);
+        } catch (final URISyntaxException ue) {
+            throw new IllegalArgumentException("Namespace '" + namespace + "' is not a valid URI", ue);
         }
-
-        Date revisionDate = parseRevision(revision);
-        return create(namespaceUri, revisionDate, localName);
     }
 
     @Override
-    public String toString() {
-        StringBuilder sb = new StringBuilder();
+    public @NonNull String toString() {
+        final StringBuilder sb = new StringBuilder();
         if (getNamespace() != null) {
-            sb.append(QNAME_LEFT_PARENTHESIS + getNamespace());
+            sb.append(QNAME_LEFT_PARENTHESIS).append(getNamespace());
 
-            if (getFormattedRevision() != null) {
-                sb.append(QNAME_REVISION_DELIMITER + getFormattedRevision());
+            final Optional<Revision> rev = getRevision();
+            if (rev.isPresent()) {
+                sb.append(QNAME_REVISION_DELIMITER).append(rev.get());
             }
             sb.append(QNAME_RIGHT_PARENTHESIS);
         }
-        sb.append(localName);
-        return sb.toString();
+        return sb.append(localName).toString();
     }
 
     /**
-     * Return string representation of revision in format
-     * <code>YYYY-mm-dd</code>
-     *
-     * YANG Specification defines format for <code>revision</code> as
-     * YYYY-mm-dd. This format for revision is reused accross multiple places
-     * such as capabilities URI, YANG modules, etc.
+     * Returns a QName with the specified QNameModule and the same localname as this one.
      *
-     * @return String representation of revision or null, if revision is not
-     *         set.
+     * @param newModule New QNameModule to use
+     * @return a QName with specified QNameModule and same local name as this one
      */
-    public String getFormattedRevision() {
-        return module.getFormattedRevision();
+    public @NonNull QName withModule(final QNameModule newModule) {
+        return new QName(newModule, localName);
     }
 
     /**
-     * Creates copy of this with revision and prefix unset.
+     * Returns a QName with the same namespace and local name, but with no revision. If this QName does not have
+     * a Revision, this object is returned.
      *
-     * @return copy of this QName with revision and prefix unset.
+     * @return a QName with the same namespace and local name, but with no revision.
      */
-    public QName withoutRevision() {
-        return QName.create(getNamespace(), null, localName);
-    }
-
-    public static Date parseRevision(final String formatedDate) {
-        try {
-            return getRevisionFormat().parse(formatedDate);
-        } catch (ParseException | RuntimeException e) {
-            throw new IllegalArgumentException(
-                    String.format("Revision '%s'is not in a supported format", formatedDate), e);
-        }
+    public @NonNull QName withoutRevision() {
+        final QNameModule newModule;
+        return (newModule = module.withoutRevision()) == module ? this : new QName(newModule, localName);
     }
 
     /**
-     * Formats {@link Date} representing revision to format
-     * <code>YYYY-mm-dd</code>
+     * Formats {@link Revision} representing revision to format {@code YYYY-mm-dd}
      *
-     * YANG Specification defines format for <code>revision</code> as
-     * YYYY-mm-dd. This format for revision is reused accross multiple places
-     * such as capabilities URI, YANG modules, etc.
+     * <p>
+     * YANG Specification defines format for {@code revision<} as YYYY-mm-dd. This format for revision is reused across
+     * multiple places such as capabilities URI, YANG modules, etc.
      *
-     * @param revision
-     *            Date object to format or null
+     * @param revision Date object to format
      * @return String representation or null if the input was null.
      */
-    public static String formattedRevision(final Date revision) {
-        if (revision == null) {
-            return null;
-        }
-        return getRevisionFormat().format(revision);
+    public static @Nullable String formattedRevision(final Optional<Revision> revision) {
+        return revision.map(Revision::toString).orElse(null);
     }
 
     /**
-     *
      * Compares this QName to other, without comparing revision.
      *
-     * Compares instance of this to other instance of QName and returns true if
-     * both instances have equal <code>localName</code> ({@link #getLocalName()}
-     * ) and <code>namespace</code> ({@link #getNamespace()}).
+     * <p>
+     * Compares instance of this to other instance of QName and returns true if both instances have equal
+     * {@code localName} ({@link #getLocalName()}) and @{code namespace} ({@link #getNamespace()}).
      *
-     * @param other
-     *            Other QName. Must not be null.
-     * @return true if this instance and other have equals localName and
-     *         namespace.
-     * @throws NullPointerException
-     *             if <code>other</code> is null.
+     * @param other Other QName. Must not be null.
+     * @return true if this instance and other have equals localName and namespace.
+     * @throws NullPointerException if {@code other} is null.
      */
     public boolean isEqualWithoutRevision(final QName other) {
         return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
     }
 
+    // FIXME: this comparison function looks odd. We are sorting first by local name and then by module? What is
+    //        the impact on iteration order of SortedMap<QName, ?>?
     @Override
-    public int compareTo(final QName other) {
+    @SuppressWarnings("checkstyle:parameterName")
+    public int compareTo(final QName o) {
         // compare mandatory localName parameter
-        int result = localName.compareTo(other.localName);
+        int result = localName.compareTo(o.localName);
         if (result != 0) {
             return result;
         }
+        return module.compareTo(o.module);
+    }
 
-        // compare nullable namespace parameter
-        if (getNamespace() == null) {
-            if (other.getNamespace() != null) {
-                return -1;
-            }
-        } else {
-            if (other.getNamespace() == null) {
-                return 1;
-            }
-            result = getNamespace().compareTo(other.getNamespace());
-            if (result != 0) {
-                return result;
-            }
-        }
-
-        // compare nullable revision parameter
-        if (getRevision() == null) {
-            if (other.getRevision() != null) {
-                return -1;
-            }
-        } else {
-            if (other.getRevision() == null) {
-                return 1;
-            }
-            result = getRevision().compareTo(other.getRevision());
-            if (result != 0) {
-                return result;
-            }
-        }
-
-        return result;
+    @Override
+    public void writeTo(final DataOutput out) throws IOException {
+        module.writeTo(out);
+        out.writeUTF(localName);
     }
 
+    Object writeReplace() {
+        return new QNv1(this);
+    }
 }