Do not leak SpotBugs from yang-binding
[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 com.google.common.collect.ImmutableMap;
18 import java.util.Arrays;
19 import java.util.HexFormat;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.NoSuchElementException;
23 import java.util.Objects;
24 import java.util.Set;
25 import java.util.regex.Pattern;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
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 public final class CodeHelpers {
35     private CodeHelpers() {
36         // Hidden
37     }
38
39     /**
40      * Require that an a value-related expression is true.
41      *
42      * @param expression Expression to evaluate
43      * @param value Value being validated
44      * @param options Valid value options checked
45      * @throws IllegalArgumentException if expression is false
46      */
47     public static void validValue(final boolean expression, final Object value, final String options) {
48         checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
49     }
50
51     /**
52      * Return value and check whether specified value is {@code null} and if so throws exception. This method supports
53      * require default getter methods.
54      *
55      * @param value Value itself
56      * @param name Name of the value
57      * @return Non-null value
58      * @throws NoSuchElementException if value is {@code null}
59      */
60     public static <T> @NonNull T require(final @Nullable T value, final @NonNull String name) {
61         if (value == null) {
62             throw new NoSuchElementException("Value of " + name + " is not present");
63         }
64         return value;
65     }
66
67     /**
68      * A shortcut for {@code Preconditions.checkNotNull(value, "Key component \"%s\" must not be null", name)}.
69      *
70      * @param value Value itself
71      * @param name Name of the value
72      * @return Non-null value
73      * @throws NullPointerException if value is {@code null}
74      */
75     public static <T> @NonNull T requireKeyProp(final @Nullable T value, final @NonNull String name) {
76         if (value == null) {
77             throw new NullPointerException("Key component \"" + name + "\" may not be null");
78         }
79         return value;
80     }
81
82     /**
83      * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
84      *
85      * @param value Value itself
86      * @throws NullPointerException if value is {@code null}
87      */
88     public static void requireValue(final @Nullable Object value) {
89         requireNonNull(value, "Supplied value may not be null");
90     }
91
92     /**
93      * Append a {@code bits} individual value. If the value is {@code false}, this method does nothing.
94      *
95      * @param helper Helper to append to
96      * @param name Name of the bit
97      * @param value Value to append
98      * @throws NullPointerException if any argument is {@code null}
99      */
100     public static void appendBit(final ToStringHelper helper, final @NonNull String name, final boolean value) {
101         if (value) {
102             helper.addValue(name);
103         }
104     }
105
106     /**
107      * Append a named value to a ToStringHelper. If the value is {@code null}, this method does nothing.
108      *
109      * @param helper Helper to append to
110      * @param name Name of the value
111      * @param value Value to append
112      * @throws NullPointerException if the name or helper is {@code null}
113      */
114     public static void appendValue(final ToStringHelper helper, final @NonNull String name,
115             final @Nullable Object value) {
116         if (value != null) {
117             helper.add(name, value);
118         }
119     }
120
121     /**
122      * Append a named value to a ToStringHelper. If the value is {@code null}, this method does nothing.
123      *
124      * @param helper Helper to append to
125      * @param name Name of the value
126      * @param value Value to append
127      * @throws NullPointerException if the name or helper is {@code null}
128      */
129     public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
130         if (value != null) {
131             helper.add(name, HexFormat.of().formatHex(value));
132         }
133     }
134
135     /**
136      * Append augmentation map of an Augmentable to a ToStringHelper. If augmentations are {@code null} or empty, this
137      * method does nothing.
138      *
139      * @param helper Helper to append to
140      * @param name Name of the augmentation value
141      * @param augmentable Augmentable object to
142      * @throws NullPointerException if any argument is {@code null}
143      */
144     public static void appendAugmentations(final ToStringHelper helper, final String name,
145             final Augmentable<?> augmentable) {
146         final var augments = augmentable.augmentations();
147         if (!augments.isEmpty()) {
148             helper.add(name, augments.values());
149         }
150     }
151
152     /**
153      * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
154      * expressions.
155      *
156      * @param patterns Patterns to compile
157      * @return Compiled patterns in an array
158      * @throws NullPointerException if the list or any of its elements is {@code null}
159      * @throws VerifyException if the list has fewer than two elements
160      */
161     public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
162         final int size = patterns.size();
163         verify(size > 1, "Patterns has to have at least 2 elements");
164         final Pattern[] result = new Pattern[size];
165         for (int i = 0; i < size; ++i) {
166             result[i] = Pattern.compile(patterns.get(i));
167         }
168         return result;
169     }
170
171     /**
172      * Check whether a specified string value matches a specified pattern. This method handles the distinction between
173      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
174      *
175      * @param value Value to be checked.
176      * @param pattern Enforcement pattern
177      * @param regex Source regular expression, as defined in YANG model
178      * @throws IllegalArgumentException if the value does not match the pattern
179      * @throws NullPointerException if any of the arguments is {@code null}
180      */
181     public static void checkPattern(final String value, final Pattern pattern, final String regex) {
182         if (!pattern.matcher(value).matches()) {
183             final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
184                 : "does not match required";
185             throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
186                     + regex + "\"");
187         }
188     }
189
190     /**
191      * Check whether a specified string value matches specified patterns. This method handles the distinction between
192      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
193      *
194      * @param value Value to be checked.
195      * @param patterns Enforcement patterns
196      * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
197      * @throws IllegalArgumentException if the value does not match the pattern
198      * @throws NullPointerException if any of the arguments is {@code null}
199      * @throws VerifyException if the size of patterns and regexes does not match
200      */
201     public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
202         verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
203         for (int i = 0; i < patterns.length; ++i) {
204             checkPattern(value, patterns[i], regexes[i]);
205         }
206     }
207
208     /**
209      * Throw an IllegalArgument exception describing a length violation.
210      *
211      * @param expected String describing expected lengths
212      * @param actual Actual observed object
213      * @throws IllegalArgumentException always
214      */
215     public static void throwInvalidLength(final String expected, final Object actual) {
216         throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
217     }
218
219     /**
220      * Throw an IllegalArgument exception describing a length violation.
221      *
222      * @param expected String describing expected lengths
223      * @param actual Actual observed byte array
224      * @throws IllegalArgumentException always
225      */
226     public static void throwInvalidLength(final String expected, final byte[] actual) {
227         throwInvalidLength(expected, HexFormat.of().formatHex(actual));
228     }
229
230     /**
231      * Throw an IllegalArgument exception describing a range violation.
232      *
233      * @param expected String describing expected ranges
234      * @param actual Actual observed object
235      * @throws IllegalArgumentException always
236      */
237     public static void throwInvalidRange(final String expected, final Object actual) {
238         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
239     }
240
241     /**
242      * Throw an IllegalArgument exception describing a range violation.
243      *
244      * @param expected String describing expected ranges
245      * @param actual Actual observed value
246      * @throws IllegalArgumentException always
247      */
248     public static void throwInvalidRange(final String expected, final int actual) {
249         // Not a code duplication: provides faster string concat via StringBuilder.append(int)
250         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
251     }
252
253     /**
254      * Throw an IllegalArgument exception describing a range violation.
255      *
256      * @param expected String describing expected ranges
257      * @param actual Actual observed value
258      * @throws IllegalArgumentException always
259      */
260     public static void throwInvalidRange(final String expected, final long actual) {
261         // Not a code duplication: provides faster string concat via StringBuilder.append(long)
262         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
263     }
264
265     /**
266      * Throw an IllegalArgument exception describing a range violation.
267      *
268      * @param expected Objects describing expected ranges
269      * @param actual Actual observed byte array
270      * @throws IllegalArgumentException always
271      */
272     public static void throwInvalidRange(final Object[] expected, final Object actual) {
273         throwInvalidRange(Arrays.toString(expected), actual);
274     }
275
276     /**
277      * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
278      *
279      * @param expected String describing expected ranges
280      * @param actual Actual observed value
281      * @throws IllegalArgumentException always
282      */
283     public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
284         throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
285             + ".");
286     }
287
288     /**
289      * Check whether specified List is {@code null} and if so return an immutable list instead. This method supports
290      * non-null default getter methods.
291      *
292      * @param <T> list element type
293      * @param input input list, may be {@code null}
294      * @return Input list or an empty list.
295      */
296     public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
297         return input != null ? input : ImmutableList.of();
298     }
299
300     /**
301      * Check whether specified Map is {@code null} and if so return an immutable map instead. This method supports
302      * non-null default getter methods.
303      *
304      * @param <K> key type
305      * @param <V> value type
306      * @param input input map, may be {@code null}
307      * @return Input map or an empty map.
308      */
309     public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
310         return input != null ? input : ImmutableMap.of();
311     }
312
313     /**
314      * Check whether specified List is empty and if so return {@code null}, otherwise return input list. This method
315      * supports Builder/implementation list handover.
316      *
317      * @param <T> list element type
318      * @param input input list, may be {@code null}
319      * @return Input list or {@code null}.
320      */
321     public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
322         return input != null && input.isEmpty() ? null : input;
323     }
324
325     /**
326      * Check whether specified Map is empty and if so return {@code null}, otherwise return input map. This method
327      * supports Builder/implementation list handover.
328      *
329      * @param <K> key type
330      * @param <V> value type
331      * @param input input map, may be {@code null}
332      * @return Input map or {@code null}.
333      */
334     public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
335         return input != null && input.isEmpty() ? null : input;
336     }
337
338     /**
339      * Return hash code of a single-property wrapper class. Since the wrapper is not {@code null}, we really want to
340      * discern this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with
341      * {@code 0} for both non-present and present-with-null objects.
342      *
343      * @param obj Internal object to hash
344      * @return Wrapper object hash code
345      */
346     public static int wrapperHashCode(final @Nullable Object obj) {
347         return wrapHashCode(Objects.hashCode(obj));
348     }
349
350     /**
351      * Return hash code of a single-property wrapper class. Since the wrapper is not {@code null}, we really want to
352      * discern this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with
353      * {@code 0} for both non-present and present-with-null objects.
354      *
355      * @param obj Internal object to hash
356      * @return Wrapper object hash code
357      */
358     public static int wrapperHashCode(final byte @Nullable[] obj) {
359         return wrapHashCode(Arrays.hashCode(obj));
360     }
361
362     /**
363      * The constant '31' is the result of folding this code:
364      * <pre>
365      *   <code>
366      *     final int prime = 31;
367      *     int result = 1;
368      *     result = result * prime + Objects.hashCode(obj);
369      *     return result;
370      *   </code>
371      * </pre>
372      * when hashCode is returned as 0, such as due to obj being {@code null} or its hashCode being 0.
373      *
374      * @param hash Wrapped object hash
375      * @return Wrapper object hash
376      */
377     private static int wrapHashCode(final int hash) {
378         return hash == 0 ? 31 : hash;
379     }
380
381     /**
382      * Check that the specified {@link EnumTypeObject} object is not {@code null}. This method is meant to be used with
383      * {@code ofName(String)} and {@code ofValue(int)} static factory methods.
384      *
385      * @param obj enumeration object, possibly {@code null}
386      * @param name User-supplied enumeration name
387      * @return Enumeration object
388      * @throws IllegalArgumentException if {@code obj} is {@code null}
389      */
390     public static <T extends EnumTypeObject> @NonNull T checkEnum(final @Nullable T obj, final String name) {
391         if (obj == null) {
392             throw new IllegalArgumentException("\"" + name + "\" is not a valid name");
393         }
394         return obj;
395     }
396
397     /**
398      * Check that the specified {@link EnumTypeObject} object is not {@code null}. This method is meant to be used with
399      * {@code ofName(String)} and {@code ofValue(int)} static factory methods.
400      *
401      * @param obj enumeration object, possibly {@code null}
402      * @param value User-supplied enumeration value
403      * @return Enumeration object
404      * @throws IllegalArgumentException if {@code obj} is {@code null}
405      */
406     public static <T extends EnumTypeObject> @NonNull T checkEnum(final @Nullable T obj, final int value) {
407         if (obj == null) {
408             throw new IllegalArgumentException(value + " is not a valid value");
409         }
410         return obj;
411     }
412
413     /**
414      * Utility method for checking whether a target object is a compatible {@link BindingContract}.
415      *
416      * @param requiredClass Required BindingContract class
417      * @param obj Object to check, may be {@code null}
418      * @return Object cast to required class, if its implemented class matches requirement, {@code null} otherwise
419      * @throws NullPointerException if {@code requiredClass} is {@code null}
420      */
421     public static <T extends BindingContract<?>> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
422             final @Nullable Object obj) {
423         return obj instanceof BindingContract<?> contract && requiredClass.equals(contract.implementedInterface())
424             ? requiredClass.cast(obj) : null;
425     }
426
427     /**
428      * Utility method for checking whether a target object is compatible.
429      *
430      * @param requiredClass Required class
431      * @param fieldName name of the field being filled
432      * @param obj Object to check, may be {@code null}
433      * @return Object cast to required class, if its class matches requirement, or {@code null}
434      * @throws IllegalArgumentException if {@code obj} is not an instance of {@code requiredClass}
435      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is {@code null}
436      */
437     public static <T> @Nullable T checkFieldCast(final @NonNull Class<T> requiredClass, final @NonNull String fieldName,
438             final @Nullable Object obj) {
439         try {
440             return requiredClass.cast(obj);
441         } catch (ClassCastException e) {
442             throw new IllegalArgumentException("Invalid input value for property \"" + fieldName + "\"", e);
443         }
444     }
445
446     /**
447      * Utility method for checking whether the items of target list is compatible.
448      *
449      * @param requiredClass Required item class
450      * @param fieldName name of the field being filled
451      * @param list List, which items should be checked
452      * @return Type-checked List
453      * @throws IllegalArgumentException if a list item is not instance of {@code requiredClass}
454      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is {@code null}
455      */
456     @SuppressWarnings("unchecked")
457     public static <T> @Nullable List<T> checkListFieldCast(final @NonNull Class<?> requiredClass,
458             final @NonNull String fieldName, final @Nullable List<?> list) {
459         DoNotLeakSpotbugs.checkCollectionField(requiredClass, fieldName, list);
460         return (List<T>) list;
461     }
462
463     /**
464      * Utility method for checking whether the items of target set is compatible.
465      *
466      * @param requiredClass Required item class
467      * @param fieldName name of the field being filled
468      * @param set Set, which items should be checked
469      * @return Type-checked Set
470      * @throws IllegalArgumentException if a set item is not instance of {@code requiredItemClass}
471      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is {@code null}
472      */
473     @SuppressWarnings("unchecked")
474     public static <T> @Nullable Set<T> checkSetFieldCast(final @NonNull Class<?> requiredClass,
475             final @NonNull String fieldName, final @Nullable Set<?> set) {
476         DoNotLeakSpotbugs.checkCollectionField(requiredClass, fieldName, set);
477         return (Set<T>) set;
478     }
479 }