Migrate RFC references to rfc-editor.org
[yangtools.git] / common / yang-common / src / main / java / org / opendaylight / yangtools / yang / common / Revision.java
1 /*
2  * Copyright (c) 2016 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 java.util.Objects.requireNonNull;
11
12 import java.io.Externalizable;
13 import java.io.IOException;
14 import java.io.ObjectInput;
15 import java.io.ObjectOutput;
16 import java.io.Serial;
17 import java.io.Serializable;
18 import java.time.format.DateTimeFormatter;
19 import java.time.format.DateTimeParseException;
20 import java.util.Optional;
21 import java.util.regex.Pattern;
22 import org.checkerframework.checker.regex.qual.Regex;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.yangtools.concepts.Immutable;
26
27 /**
28  * Dedicated object identifying a YANG module revision.
29  *
30  * <h2>API design note</h2>
31  * This class defines the contents of a revision statement, but modules do not require to have a revision (e.g. they
32  * have not started to keep track of revisions).
33  *
34  * <p>
35  * APIs which involve this class should always transfer instances via {@code Optional<Revision>}, which is
36  * the primary bridge data type. Implementations can use nullable fields with explicit conversions to/from
37  * {@link Optional}. Both patterns can take advantage of {@link #compare(Optional, Optional)} and
38  * {@link #compare(Revision, Revision)} respectively.
39  *
40  * @author Robert Varga
41  */
42 public final class Revision implements Comparable<Revision>, Immutable, Serializable {
43     // Note: since we are using writeReplace() this version is not significant.
44     @Serial
45     private static final long serialVersionUID = 1L;
46
47     private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
48
49     @Regex
50     // FIXME: we should improve this to filter incorrect dates -- see constructor.
51     private static final String STRING_FORMAT_PATTERN_STR = "\\d\\d\\d\\d\\-\\d\\d-\\d\\d";
52
53     /**
54      * String format pattern, which can be used to match parts of a string into components.
55      */
56     public static final Pattern STRING_FORMAT_PATTERN = Pattern.compile(STRING_FORMAT_PATTERN_STR);
57
58     /**
59      * Revision which compares as greater than any other valid revision.
60      */
61     public static final Revision MAX_VALUE = Revision.of("9999-12-31");
62
63     private final @NonNull String str;
64
65     private Revision(final @NonNull String str) {
66         /*
67          * According to RFC7950 (https://www.rfc-editor.org/rfc/rfc7950#section-7.1.9):
68          *
69          *   The "revision" statement specifies the editorial revision history of
70          *   the module, including the initial revision.  A series of "revision"
71          *   statements detail the changes in the module's definition.  The
72          *   argument is a date string in the format "YYYY-MM-DD", [...]
73          *
74          * Hence we use JDK-provided parsing faculties to parse the date.
75          */
76         FORMATTER.parse(str);
77         this.str = str;
78     }
79
80     /**
81      * Parse a revision string.
82      *
83      * @param str String to be parsed
84      * @return A Revision instance.
85      * @throws DateTimeParseException if the string format does not conform specification.
86      * @throws NullPointerException if the string is null
87      */
88     public static @NonNull Revision of(final @NonNull String str) {
89         return new Revision(str);
90     }
91
92     /**
93      * Parse a (potentially null) revision string. Null strings result result in {@link Optional#empty()}.
94      *
95      * @param str String to be parsed
96      * @return An optional Revision instance.
97      * @throws DateTimeParseException if the string format does not conform specification.
98      */
99     public static @NonNull Optional<Revision> ofNullable(final @Nullable String str) {
100         return str == null ? Optional.empty() : Optional.of(new Revision(str));
101     }
102
103     /**
104      * Compare two {@link Optional}s wrapping Revisions. Arguments and return value are consistent with
105      * {@link java.util.Comparator#compare(Object, Object)} interface contract. Missing revisions compare as lower
106      * than any other revision.
107      *
108      * @param first First optional revision
109      * @param second Second optional revision
110      * @return Positive, zero, or negative integer.
111      */
112     public static int compare(final @NonNull Optional<Revision> first, final @NonNull Optional<Revision> second) {
113         if (first.isPresent()) {
114             return second.isPresent() ? first.orElseThrow().compareTo(second.orElseThrow()) : 1;
115         }
116         return second.isPresent() ? -1 : 0;
117     }
118
119     /**
120      * Compare two explicitly nullable Revisions. Unlike {@link #compareTo(Revision)}, this handles both arguments
121      * being null such that total ordering is defined.
122      *
123      * @param first First revision
124      * @param second Second revision
125      * @return Positive, zero, or negative integer.
126      */
127     public static int compare(final @Nullable Revision first, final @Nullable Revision second) {
128         if (first != null) {
129             return second != null ? first.compareTo(second) : 1;
130         }
131         return second != null ? -1 : 0;
132     }
133
134     @Override
135     @SuppressWarnings("checkstyle:parameterName")
136     public int compareTo(final Revision o) {
137         // Since all strings conform to the format, we can use their comparable property to do the correct thing
138         // with respect to temporal ordering.
139         return str.compareTo(o.str);
140     }
141
142     @Override
143     public int hashCode() {
144         return str.hashCode();
145     }
146
147     @Override
148     public boolean equals(final Object obj) {
149         return this == obj || obj instanceof Revision other && str.equals(other.str);
150     }
151
152     @Override
153     public String toString() {
154         return str;
155     }
156
157     @Serial
158     Object writeReplace() {
159         return new Proxy(str);
160     }
161
162     private static final class Proxy implements Externalizable {
163         @Serial
164         private static final long serialVersionUID = 1L;
165
166         private String str;
167
168         @SuppressWarnings("checkstyle:redundantModifier")
169         public Proxy() {
170             // For Externalizable
171         }
172
173         Proxy(final String str) {
174             this.str = requireNonNull(str);
175         }
176
177         @Override
178         public void writeExternal(final ObjectOutput out) throws IOException {
179             out.writeObject(str);
180         }
181
182         @Override
183         public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
184             str = (String) in.readObject();
185         }
186
187         @Serial
188         private Object readResolve() {
189             return Revision.of(requireNonNull(str));
190         }
191     }
192 }