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