9f24fe2c45ac719f88d648e007fcf307ddd6fc8c
[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.List;
20 import java.util.Map;
21 import java.util.NoSuchElementException;
22 import java.util.Objects;
23 import java.util.regex.Pattern;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.eclipse.jdt.annotation.Nullable;
26
27 /**
28  * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
29  * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
30  * general API stability requirements of the Binding Specification.
31  *
32  * @author Robert Varga
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 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 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 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 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 named value to a ToStringHelper. If the value is null, this method does nothing.
94      *
95      * @param helper Helper to append to
96      * @param name Name of the value
97      * @param value Value to append
98      * @throws NullPointerException if the name or helper is null
99      */
100     public static void appendValue(final ToStringHelper helper, final @NonNull String name,
101             final @Nullable Object value) {
102         if (value != null) {
103             helper.add(name, value);
104         }
105     }
106
107     /**
108      * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
109      *
110      * @param helper Helper to append to
111      * @param name Name of the value
112      * @param value Value to append
113      * @throws NullPointerException if the name or helper is null
114      */
115     public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
116         if (value != null) {
117             // FIXME: MDSAL-692: use hex-encoding instead
118             helper.add(name, Arrays.toString(value));
119         }
120     }
121
122     /**
123      * Append augmentation map of an Augmentable to a ToStringHelper. If augmentations are null or empt, this method
124      * does nothing.
125      *
126      * @param helper Helper to append to
127      * @param name Name of the augmentation value
128      * @param augmentable Augmentable object to
129      * @throws NullPointerException if any argument is null
130      */
131     public static void appendAugmentations(final ToStringHelper helper, final String name,
132             final Augmentable<?> augmentable) {
133         final var augments = augmentable.augmentations();
134         if (!augments.isEmpty()) {
135             helper.add(name, augments.values());
136         }
137     }
138
139     /**
140      * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
141      * expressions.
142      *
143      * @param patterns Patterns to compile
144      * @return Compiled patterns in an array
145      * @throws NullPointerException if the list or any of its elements is null
146      * @throws VerifyException if the list has fewer than two elements
147      */
148     public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
149         final int size = patterns.size();
150         verify(size > 1, "Patterns has to have at least 2 elements");
151         final Pattern[] result = new Pattern[size];
152         for (int i = 0; i < size; ++i) {
153             result[i] = Pattern.compile(patterns.get(i));
154         }
155         return result;
156     }
157
158     /**
159      * Check whether a specified string value matches a specified pattern. This method handles the distinction between
160      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
161      *
162      * @param value Value to be checked.
163      * @param pattern Enforcement pattern
164      * @param regex Source regular expression, as defined in YANG model
165      * @throws IllegalArgumentException if the value does not match the pattern
166      * @throws NullPointerException if any of the arguments are null
167      */
168     public static void checkPattern(final String value, final Pattern pattern, final String regex) {
169         if (!pattern.matcher(value).matches()) {
170             final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
171                 : "does not match required";
172             throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
173                     + regex + "\"");
174         }
175     }
176
177     /**
178      * Check whether a specified string value matches specified patterns. This method handles the distinction between
179      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
180      *
181      * @param value Value to be checked.
182      * @param patterns Enforcement patterns
183      * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
184      * @throws IllegalArgumentException if the value does not match the pattern
185      * @throws NullPointerException if any of the arguments are null
186      * @throws VerifyException if the size of patterns and regexes does not match
187      */
188     public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
189         verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
190         for (int i = 0; i < patterns.length; ++i) {
191             checkPattern(value, patterns[i], regexes[i]);
192         }
193     }
194
195     /**
196      * Throw an IllegalArgument exception describing a length violation.
197      *
198      * @param expected String describing expected lengths
199      * @param actual Actual observed object
200      * @throws IllegalArgumentException always
201      */
202     public static void throwInvalidLength(final String expected, final Object actual) {
203         throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
204     }
205
206     /**
207      * Throw an IllegalArgument exception describing a length violation.
208      *
209      * @param expected String describing expected lengths
210      * @param actual Actual observed byte array
211      * @throws IllegalArgumentException always
212      */
213     public static void throwInvalidLength(final String expected, final byte[] actual) {
214         // FIXME: MDSAL-692: use hex-encoding instead
215         throwInvalidLength(expected, Arrays.toString(actual));
216     }
217
218     /**
219      * Throw an IllegalArgument exception describing a range violation.
220      *
221      * @param expected String describing expected ranges
222      * @param actual Actual observed object
223      * @throws IllegalArgumentException always
224      */
225     public static void throwInvalidRange(final String expected, final Object actual) {
226         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
227     }
228
229     /**
230      * Throw an IllegalArgument exception describing a range violation.
231      *
232      * @param expected String describing expected ranges
233      * @param actual Actual observed value
234      * @throws IllegalArgumentException always
235      */
236     public static void throwInvalidRange(final String expected, final int actual) {
237         // Not a code duplication: provides faster string concat via StringBuilder.append(int)
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 long actual) {
249         // Not a code duplication: provides faster string concat via StringBuilder.append(long)
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 Objects describing expected ranges
257      * @param actual Actual observed byte array
258      * @throws IllegalArgumentException always
259      */
260     public static void throwInvalidRange(final Object[] expected, final Object actual) {
261         throwInvalidRange(Arrays.toString(expected), actual);
262     }
263
264     /**
265      * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
266      *
267      * @param expected String describing expected ranges
268      * @param actual Actual observed value
269      * @throws IllegalArgumentException always
270      */
271     public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
272         throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
273             + ".");
274     }
275
276     /**
277      * Check whether specified List is null and if so return an immutable list instead. This method supports
278      * non-null default getter methods.
279      *
280      * @param <T> list element type
281      * @param input input list, may be null
282      * @return Input list or an empty list.
283      */
284     public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
285         return input != null ? input : ImmutableList.of();
286     }
287
288     /**
289      * Check whether specified Map is null and if so return an immutable map instead. This method supports
290      * non-null default getter methods.
291      *
292      * @param <K> key type
293      * @param <V> value type
294      * @param input input map, may be null
295      * @return Input map or an empty map.
296      */
297     public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
298         return input != null ? input : ImmutableMap.of();
299     }
300
301     /**
302      * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
303      * Builder/implementation list handover.
304      *
305      * @param <T> list element type
306      * @param input input list, may be null
307      * @return Input list or null.
308      */
309     public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
310         return input != null && input.isEmpty() ? null : input;
311     }
312
313     /**
314      * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
315      * Builder/implementation list handover.
316      *
317      * @param <K> key type
318      * @param <V> value type
319      * @param input input map, may be null
320      * @return Input map or null.
321      */
322     public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
323         return input != null && input.isEmpty() ? null : input;
324     }
325
326     /**
327      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
328      * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
329      * for both non-present and present-with-null objects.
330      *
331      * @param obj Internal object to hash
332      * @return Wrapper object hash code
333      */
334     public static int wrapperHashCode(final @Nullable Object obj) {
335         return wrapHashCode(Objects.hashCode(obj));
336     }
337
338     /**
339      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
340      * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
341      * 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 byte @Nullable[] obj) {
347         return wrapHashCode(Arrays.hashCode(obj));
348     }
349
350     /**
351      * Utility method for checking whether a target object is a compatible DataObject.
352      *
353      * @param requiredClass Required DataObject class
354      * @param obj Object to check, may be null
355      * @return Object cast to required class, if its implemented class matches requirement, null otherwise
356      * @throws NullPointerException if {@code requiredClass} is null
357      */
358     public static <T extends DataObject> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
359             final @Nullable Object obj) {
360         return obj instanceof DataObject && requiredClass.equals(((DataObject) obj).implementedInterface())
361             ? requiredClass.cast(obj) : null;
362     }
363
364     /**
365      * Utility method for checking whether a target object is compatible.
366      *
367      * @param requiredClass Required class
368      * @param fieldName name of the field being filled
369      * @param obj Object to check, may be null
370      * @return Object cast to required class, if its class matches requirement, or null
371      * @throws IllegalArgumentException if {@code obj} is not an instance of {@code requiredClass}
372      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
373      */
374     public static <T> @Nullable T checkFieldCast(final @NonNull Class<T> requiredClass, final @NonNull String fieldName,
375             final @Nullable Object obj) {
376         try {
377             return requiredClass.cast(obj);
378         } catch (ClassCastException e) {
379             throw new IllegalArgumentException("Invalid input value for property \"" + fieldName + "\"", e);
380         }
381     }
382
383     /**
384      * Utility method for checking whether the items of target list is compatible.
385      *
386      * @param requiredClass Required item class
387      * @param fieldName name of the field being filled
388      * @param list List, which items should be checked
389      * @throws IllegalArgumentException if a list item is not instance of {@code requiredItemClass}
390      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
391      */
392     @SuppressWarnings("unchecked")
393     public static <T> @Nullable List<T> checkListFieldCast(final @NonNull Class<?> requiredClass,
394             final @NonNull String fieldName, final @Nullable List<?> list) {
395         if (list != null) {
396             try {
397                 list.forEach(item -> requiredClass.cast(requireNonNull(item)));
398             } catch (ClassCastException | NullPointerException e) {
399                 throw new IllegalArgumentException("Invalid input list item for property \"" + requireNonNull(fieldName)
400                     + "\"", e);
401             }
402         }
403         return (List<T>) list;
404     }
405
406     /**
407      * The constant '31' is the result of folding this code:
408      * <pre>
409      *   <code>
410      *     final int prime = 31;
411      *     int result = 1;
412      *     result = result * prime + Objects.hashCode(obj);
413      *     return result;
414      *   </code>
415      * </pre>
416      * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
417      *
418      * @param hash Wrapped object hash
419      * @return Wrapper object hash
420      */
421     private static int wrapHashCode(final int hash) {
422         return hash == 0 ? 31 : hash;
423     }
424 }