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