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