Fix CodeHelper.nonnull() nullness annotation
[mdsal.git] / binding / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / CodeHelpers.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o.  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.binding;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.base.VerifyException;
16 import com.google.common.collect.ImmutableList;
17 import java.util.Arrays;
18 import java.util.List;
19 import java.util.Objects;
20 import java.util.regex.Pattern;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.eclipse.jdt.annotation.Nullable;
23
24 /**
25  * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
26  * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
27  * general API stability requirements of the Binding Specification.
28  *
29  * @author Robert Varga
30  */
31 public final class CodeHelpers {
32     private CodeHelpers() {
33         // Hidden
34     }
35
36     /**
37      * Require that an a value-related expression is true.
38      *
39      * @param expression Expression to evaluate
40      * @param value Value being validated
41      * @param options Valid value options checked
42      * @throws IllegalArgumentException if expression is false
43      */
44     public static void validValue(final boolean expression, final Object value, final String options) {
45         checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
46     }
47
48     /**
49      * Require an argument being received. This is similar to {@link java.util.Objects#requireNonNull(Object)}, but
50      * throws an IllegalArgumentException.
51      *
52      * <p>
53      * Implementation note: we expect argName to be a string literal or a constant, so that it's non-nullness can be
54      *                      quickly discovered for a call site (where we are going to be inlined).
55      *
56      * @param value Value itself
57      * @param name Symbolic name
58      * @return non-null value
59      * @throws IllegalArgumentException if value is null
60      * @throws NullPointerException if name is null
61      */
62     // FIXME: another advantage is that it is JDT-annotated, but we could live without that. At some point we should
63     //        schedule a big ISE-to-NPE conversion and just use Objects.requireNonNull() instead.
64     public static <T> @NonNull T nonNullValue(@Nullable final T value, final @NonNull String name) {
65         requireNonNull(name);
66         checkArgument(value != null, "%s must not be null", name);
67         return value;
68     }
69
70     /**
71      * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
72      *
73      * @param value Value itself
74      * @throws NullPointerException if value is null
75      */
76     public static void requireValue(@Nullable final Object value) {
77         requireNonNull(value, "Supplied value may not be null");
78     }
79
80     /**
81      * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
82      *
83      * @param helper Helper to append to
84      * @param name Name of the value
85      * @param value Value to append
86      * @throws NullPointerException if the name or helper is null
87      */
88     public static void appendValue(final ToStringHelper helper, final @NonNull String name,
89             final @Nullable Object value) {
90         if (value != null) {
91             helper.add(name, value);
92         }
93     }
94
95     /**
96      * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
97      *
98      * @param helper Helper to append to
99      * @param name Name of the value
100      * @param value Value to append
101      * @throws NullPointerException if the name or helper is null
102      */
103     public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
104         if (value != null) {
105             helper.add(name, Arrays.toString(value));
106         }
107     }
108
109     /**
110      * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
111      * expressions.
112      *
113      * @param patterns Patterns to compile
114      * @return Compiled patterns in an array
115      * @throws NullPointerException if the list or any of its elements is null
116      * @throws VerifyException if the list has fewer than two elements
117      */
118     public static @NonNull Pattern[] compilePatterns(final @NonNull List<String> patterns) {
119         final int size = patterns.size();
120         verify(size > 1, "Patterns has to have at least 2 elements");
121         final @NonNull Pattern[] result = new Pattern[size];
122         for (int i = 0; i < size; ++i) {
123             result[i] = Pattern.compile(patterns.get(i));
124         }
125         return result;
126     }
127
128     /**
129      * Check whether a specified string value matches a specified pattern. This method handles the distinction between
130      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
131      *
132      * @param value Value to be checked.
133      * @param pattern Enforcement pattern
134      * @param regex Source regular expression, as defined in YANG model
135      * @throws IllegalArgumentException if the value does not match the pattern
136      * @throws NullPointerException if any of the arguments are null
137      */
138     public static void checkPattern(final String value, final Pattern pattern, final String regex) {
139         if (!pattern.matcher(value).matches()) {
140             final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
141                 : "does not match required";
142             throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
143                     + regex + "\"");
144         }
145     }
146
147     /**
148      * Check whether a specified string value matches specified patterns. This method handles the distinction between
149      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
150      *
151      * @param value Value to be checked.
152      * @param patterns Enforcement patterns
153      * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
154      * @throws IllegalArgumentException if the value does not match the pattern
155      * @throws NullPointerException if any of the arguments are null
156      * @throws VerifyException if the size of patterns and regexes does not match
157      */
158     public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
159         verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
160         for (int i = 0; i < patterns.length; ++i) {
161             checkPattern(value, patterns[i], regexes[i]);
162         }
163     }
164
165     /**
166      * Throw an IllegalArgument exception describing a length violation.
167      *
168      * @param expected String describing expected lengths
169      * @param actual Actual observed object
170      * @throws IllegalArgumentException always
171      */
172     public static void throwInvalidLength(final String expected, final Object actual) {
173         throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
174     }
175
176     /**
177      * Throw an IllegalArgument exception describing a length violation.
178      *
179      * @param expected String describing expected lengths
180      * @param actual Actual observed byte array
181      * @throws IllegalArgumentException always
182      */
183     public static void throwInvalidLength(final String expected, final byte[] actual) {
184         throwInvalidLength(expected, Arrays.toString(actual));
185     }
186
187     /**
188      * Throw an IllegalArgument exception describing a range violation.
189      *
190      * @param expected String describing expected ranges
191      * @param actual Actual observed object
192      * @throws IllegalArgumentException always
193      */
194     public static void throwInvalidRange(final String expected, final Object actual) {
195         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
196     }
197
198     /**
199      * Throw an IllegalArgument exception describing a range violation.
200      *
201      * @param expected String describing expected ranges
202      * @param actual Actual observed value
203      * @throws IllegalArgumentException always
204      */
205     public static void throwInvalidRange(final String expected, final int actual) {
206         // Not a code duplication: provides faster string concat via StringBuilder.append(int)
207         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
208     }
209
210     /**
211      * Throw an IllegalArgument exception describing a range violation.
212      *
213      * @param expected String describing expected ranges
214      * @param actual Actual observed value
215      * @throws IllegalArgumentException always
216      */
217     public static void throwInvalidRange(final String expected, final long actual) {
218         // Not a code duplication: provides faster string concat via StringBuilder.append(long)
219         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
220     }
221
222     /**
223      * Throw an IllegalArgument exception describing a range violation.
224      *
225      * @param expected Objects describing expected ranges
226      * @param actual Actual observed byte array
227      * @throws IllegalArgumentException always
228      */
229     public static void throwInvalidRange(final Object[] expected, final Object actual) {
230         throwInvalidRange(Arrays.toString(expected), actual);
231     }
232
233     /**
234      * Check whether specified List is null and if so return an immutable list instead. This method supports
235      * non-null default getter methods.
236      *
237      * @param input input list, may be null
238      * @return Input list or an empty list.
239      */
240     public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
241         return input != null ? input : ImmutableList.of();
242     }
243
244     /**
245      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
246      * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
247      * for both non-present and present-with-null objects.
248      *
249      * @param obj Internal object to hash
250      * @return Wrapper object hash code
251      */
252     public static int wrapperHashCode(final @Nullable Object obj) {
253         return wrapHashCode(Objects.hashCode(obj));
254     }
255
256     /**
257      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
258      * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
259      * for both non-present and present-with-null objects.
260      *
261      * @param obj Internal object to hash
262      * @return Wrapper object hash code
263      */
264     public static int wrapperHashCode(final byte @Nullable[] obj) {
265         return wrapHashCode(Arrays.hashCode(obj));
266     }
267
268     /**
269      * The constant '31' is the result of folding this code:
270      * <pre>
271      *     final int prime = 31;
272      *     int result = 1;
273      *     result = result * prime + Objects.hashCode(obj);
274      *     return result;
275      * </pre>
276      * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
277      *
278      * @param hash Wrapped object hash
279      * @return Wrapper object hash
280      */
281     private static int wrapHashCode(final int hash) {
282         return hash == 0 ? 31 : hash;
283     }
284 }