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