92f26f8006725ea497373ddb4e426b1fb6a2949f
[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.List;
22 import java.util.Map;
23 import java.util.NoSuchElementException;
24 import java.util.Objects;
25 import java.util.Set;
26 import java.util.regex.Pattern;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29
30 /**
31  * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
32  * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
33  * general API stability requirements of the Binding Specification.
34  *
35  * @author Robert Varga
36  */
37 public final class CodeHelpers {
38     private CodeHelpers() {
39         // Hidden
40     }
41
42     /**
43      * Require that an a value-related expression is true.
44      *
45      * @param expression Expression to evaluate
46      * @param value Value being validated
47      * @param options Valid value options checked
48      * @throws IllegalArgumentException if expression is false
49      */
50     public static void validValue(final boolean expression, final Object value, final String options) {
51         checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
52     }
53
54     /**
55      * Return value and check whether specified value is null and if so throws exception. This method supports
56      * require default getter methods.
57      *
58      * @param value Value itself
59      * @param name Name of the value
60      * @return Non-null value
61      * @throws NoSuchElementException if value is null
62      */
63     public static <T> @NonNull T require(final @Nullable T value, final @NonNull String name) {
64         if (value == null) {
65             throw new NoSuchElementException("Value of " + name + " is not present");
66         }
67         return value;
68     }
69
70     /**
71      * A shortcut for {@code Preconditions.checkNotNull(value, "Key component \"%s\" must not be null", name)}.
72      *
73      * @param value Value itself
74      * @param name Name of the value
75      * @return Non-null value
76      * @throws NullPointerException if value is null
77      */
78     public static <T> @NonNull T requireKeyProp(final @Nullable T value, final @NonNull String name) {
79         if (value == null) {
80             throw new NullPointerException("Key component \"" + name + "\" may not be null");
81         }
82         return value;
83     }
84
85     /**
86      * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
87      *
88      * @param value Value itself
89      * @throws NullPointerException if value is null
90      */
91     public static void requireValue(final @Nullable Object value) {
92         requireNonNull(value, "Supplied value may not be null");
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 @NonNull String name,
104             final @Nullable Object value) {
105         if (value != null) {
106             helper.add(name, value);
107         }
108     }
109
110     /**
111      * Append a named value to a ToStringHelper. If the value is 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 null
117      */
118     public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
119         if (value != null) {
120             // FIXME: MDSAL-692: use hex-encoding instead
121             helper.add(name, Arrays.toString(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         // FIXME: MDSAL-692: use hex-encoding instead
218         throwInvalidLength(expected, Arrays.toString(actual));
219     }
220
221     /**
222      * Throw an IllegalArgument exception describing a range violation.
223      *
224      * @param expected String describing expected ranges
225      * @param actual Actual observed object
226      * @throws IllegalArgumentException always
227      */
228     public static void throwInvalidRange(final String expected, final Object actual) {
229         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
230     }
231
232     /**
233      * Throw an IllegalArgument exception describing a range violation.
234      *
235      * @param expected String describing expected ranges
236      * @param actual Actual observed value
237      * @throws IllegalArgumentException always
238      */
239     public static void throwInvalidRange(final String expected, final int actual) {
240         // Not a code duplication: provides faster string concat via StringBuilder.append(int)
241         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
242     }
243
244     /**
245      * Throw an IllegalArgument exception describing a range violation.
246      *
247      * @param expected String describing expected ranges
248      * @param actual Actual observed value
249      * @throws IllegalArgumentException always
250      */
251     public static void throwInvalidRange(final String expected, final long actual) {
252         // Not a code duplication: provides faster string concat via StringBuilder.append(long)
253         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
254     }
255
256     /**
257      * Throw an IllegalArgument exception describing a range violation.
258      *
259      * @param expected Objects describing expected ranges
260      * @param actual Actual observed byte array
261      * @throws IllegalArgumentException always
262      */
263     public static void throwInvalidRange(final Object[] expected, final Object actual) {
264         throwInvalidRange(Arrays.toString(expected), actual);
265     }
266
267     /**
268      * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
269      *
270      * @param expected String describing expected ranges
271      * @param actual Actual observed value
272      * @throws IllegalArgumentException always
273      */
274     public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
275         throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
276             + ".");
277     }
278
279     /**
280      * Check whether specified List is null and if so return an immutable list instead. This method supports
281      * non-null default getter methods.
282      *
283      * @param <T> list element type
284      * @param input input list, may be null
285      * @return Input list or an empty list.
286      */
287     public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
288         return input != null ? input : ImmutableList.of();
289     }
290
291     /**
292      * Check whether specified Map is null and if so return an immutable map instead. This method supports
293      * non-null default getter methods.
294      *
295      * @param <K> key type
296      * @param <V> value type
297      * @param input input map, may be null
298      * @return Input map or an empty map.
299      */
300     public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
301         return input != null ? input : ImmutableMap.of();
302     }
303
304     /**
305      * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
306      * Builder/implementation list handover.
307      *
308      * @param <T> list element type
309      * @param input input list, may be null
310      * @return Input list or null.
311      */
312     public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
313         return input != null && input.isEmpty() ? null : input;
314     }
315
316     /**
317      * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
318      * Builder/implementation list handover.
319      *
320      * @param <K> key type
321      * @param <V> value type
322      * @param input input map, may be null
323      * @return Input map or null.
324      */
325     public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
326         return input != null && input.isEmpty() ? null : input;
327     }
328
329     /**
330      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
331      * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
332      * for both non-present and present-with-null objects.
333      *
334      * @param obj Internal object to hash
335      * @return Wrapper object hash code
336      */
337     public static int wrapperHashCode(final @Nullable Object obj) {
338         return wrapHashCode(Objects.hashCode(obj));
339     }
340
341     /**
342      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
343      * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
344      * for both non-present and present-with-null objects.
345      *
346      * @param obj Internal object to hash
347      * @return Wrapper object hash code
348      */
349     public static int wrapperHashCode(final byte @Nullable[] obj) {
350         return wrapHashCode(Arrays.hashCode(obj));
351     }
352
353     /**
354      * Utility method for checking whether a target object is a compatible DataObject.
355      *
356      * @param requiredClass Required DataObject class
357      * @param obj Object to check, may be null
358      * @return Object cast to required class, if its implemented class matches requirement, null otherwise
359      * @throws NullPointerException if {@code requiredClass} is null
360      */
361     public static <T extends DataObject> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
362             final @Nullable Object obj) {
363         return obj instanceof DataObject && requiredClass.equals(((DataObject) obj).implementedInterface())
364             ? requiredClass.cast(obj) : null;
365     }
366
367     /**
368      * Utility method for checking whether a target object is compatible.
369      *
370      * @param requiredClass Required class
371      * @param fieldName name of the field being filled
372      * @param obj Object to check, may be null
373      * @return Object cast to required class, if its class matches requirement, or null
374      * @throws IllegalArgumentException if {@code obj} is not an instance of {@code requiredClass}
375      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
376      */
377     public static <T> @Nullable T checkFieldCast(final @NonNull Class<T> requiredClass, final @NonNull String fieldName,
378             final @Nullable Object obj) {
379         try {
380             return requiredClass.cast(obj);
381         } catch (ClassCastException e) {
382             throw new IllegalArgumentException("Invalid input value for property \"" + fieldName + "\"", e);
383         }
384     }
385
386     /**
387      * Utility method for checking whether the items of target list is compatible.
388      *
389      * @param requiredClass Required item class
390      * @param fieldName name of the field being filled
391      * @param list List, which items should be checked
392      * @return Type-checked List
393      * @throws IllegalArgumentException if a list item is not instance of {@code requiredItemClass}
394      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
395      */
396     @SuppressWarnings("unchecked")
397     public static <T> @Nullable List<T> checkListFieldCast(final @NonNull Class<?> requiredClass,
398             final @NonNull String fieldName, final @Nullable List<?> list) {
399         checkCollectionField(requiredClass, fieldName, list);
400         return (List<T>) list;
401     }
402
403     /**
404      * Utility method for checking whether the items of target list is compatible.
405      *
406      * @param requiredClass Required item class
407      * @param fieldName name of the field being filled
408      * @param set Set, which items should be checked
409      * @return Type-checked Set
410      * @throws IllegalArgumentException if a set item is not instance of {@code requiredItemClass}
411      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
412      */
413     @SuppressWarnings("unchecked")
414     public static <T> @Nullable Set<T> checkSetFieldCast(final @NonNull Class<?> requiredClass,
415             final @NonNull String fieldName, final @Nullable Set<?> set) {
416         checkCollectionField(requiredClass, fieldName, set);
417         return (Set<T>) set;
418     }
419
420     @SuppressFBWarnings(value = "DCN_NULLPOINTER_EXCEPTION",
421         justification = "Internal NPE->IAE conversion")
422     private static void checkCollectionField(final @NonNull Class<?> requiredClass,
423             final @NonNull String fieldName, final @Nullable Collection<?> collection) {
424         if (collection != null) {
425             try {
426                 collection.forEach(item -> requiredClass.cast(requireNonNull(item)));
427             } catch (ClassCastException | NullPointerException e) {
428                 throw new IllegalArgumentException("Invalid input list item for property \"" + requireNonNull(fieldName)
429                     + "\"", e);
430             }
431         }
432     }
433
434     /**
435      * The constant '31' is the result of folding this code:
436      * <pre>
437      *   <code>
438      *     final int prime = 31;
439      *     int result = 1;
440      *     result = result * prime + Objects.hashCode(obj);
441      *     return result;
442      *   </code>
443      * </pre>
444      * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
445      *
446      * @param hash Wrapped object hash
447      * @return Wrapper object hash
448      */
449     private static int wrapHashCode(final int hash) {
450         return hash == 0 ? 31 : hash;
451     }
452 }