f7292db2b1eca367d7b9ed14eb53fdf8ba185634
[yangtools.git] / common / yang-common / src / main / java / org / opendaylight / yangtools / yang / common / XMLNamespace.java
1 /*
2  * Copyright (c) 2021 PANTHEON.tech, s.r.o. 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 java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.Interner;
13 import com.google.common.collect.Interners;
14 import java.io.Serializable;
15 import java.net.URI;
16 import java.net.URISyntaxException;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.opendaylight.yangtools.concepts.Immutable;
19
20 /**
21  * A simple type capture of {@code namespace} statement's argument according to
22  * <a href="https://tools.ietf.org/html/rfc6020#section-7.1.3">RFC6020</a>.
23  */
24 public final class XMLNamespace implements Comparable<XMLNamespace>, Immutable, Serializable {
25     private static final Interner<XMLNamespace> INTERNER = Interners.newWeakInterner();
26     private static final long serialVersionUID = 1L;
27
28     private final String namespace;
29
30     private XMLNamespace(final String namespace) {
31         this.namespace = requireNonNull(namespace);
32     }
33
34     // FIXME: add documentation
35     public static @NonNull XMLNamespace of(final String namespace) {
36         try {
37             // Validation only
38             new URI(namespace);
39         } catch (final URISyntaxException e) {
40             throw new IllegalArgumentException("Namespace '" + namespace + "' is not a valid URI", e);
41         }
42
43         return new XMLNamespace(namespace);
44     }
45
46     /**
47      * Return an interned reference to a equivalent XMLNamespace.
48      *
49      * @return Interned reference, or this object if it was interned.
50      */
51     public @NonNull XMLNamespace intern() {
52         return INTERNER.intern(this);
53     }
54
55     @Override
56     @SuppressWarnings("checkstyle:parameterName")
57     public int compareTo(final XMLNamespace o) {
58         return namespace.compareTo(o.namespace);
59     }
60
61     @Override
62     public int hashCode() {
63         return namespace.hashCode();
64     }
65
66     @Override
67     public boolean equals(final Object obj) {
68         return this == obj || obj instanceof XMLNamespace && namespace.equals(((XMLNamespace) obj).namespace);
69     }
70
71     @Override
72     public String toString() {
73         return namespace;
74     }
75
76     Object writeReplace() {
77         return new XNv1(this);
78     }
79 }