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