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