8de4954d319ea292de6f87177f04bc64533afedf
[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      * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
124      * expressions.
125      *
126      * @param patterns Patterns to compile
127      * @return Compiled patterns in an array
128      * @throws NullPointerException if the list or any of its elements is null
129      * @throws VerifyException if the list has fewer than two elements
130      */
131     public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
132         final int size = patterns.size();
133         verify(size > 1, "Patterns has to have at least 2 elements");
134         final Pattern[] result = new Pattern[size];
135         for (int i = 0; i < size; ++i) {
136             result[i] = Pattern.compile(patterns.get(i));
137         }
138         return result;
139     }
140
141     /**
142      * Check whether a specified string value matches a specified pattern. This method handles the distinction between
143      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
144      *
145      * @param value Value to be checked.
146      * @param pattern Enforcement pattern
147      * @param regex Source regular expression, as defined in YANG model
148      * @throws IllegalArgumentException if the value does not match the pattern
149      * @throws NullPointerException if any of the arguments are null
150      */
151     public static void checkPattern(final String value, final Pattern pattern, final String regex) {
152         if (!pattern.matcher(value).matches()) {
153             final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
154                 : "does not match required";
155             throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
156                     + regex + "\"");
157         }
158     }
159
160     /**
161      * Check whether a specified string value matches specified patterns. This method handles the distinction between
162      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
163      *
164      * @param value Value to be checked.
165      * @param patterns Enforcement patterns
166      * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
167      * @throws IllegalArgumentException if the value does not match the pattern
168      * @throws NullPointerException if any of the arguments are null
169      * @throws VerifyException if the size of patterns and regexes does not match
170      */
171     public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
172         verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
173         for (int i = 0; i < patterns.length; ++i) {
174             checkPattern(value, patterns[i], regexes[i]);
175         }
176     }
177
178     /**
179      * Throw an IllegalArgument exception describing a length violation.
180      *
181      * @param expected String describing expected lengths
182      * @param actual Actual observed object
183      * @throws IllegalArgumentException always
184      */
185     public static void throwInvalidLength(final String expected, final Object actual) {
186         throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
187     }
188
189     /**
190      * Throw an IllegalArgument exception describing a length violation.
191      *
192      * @param expected String describing expected lengths
193      * @param actual Actual observed byte array
194      * @throws IllegalArgumentException always
195      */
196     public static void throwInvalidLength(final String expected, final byte[] actual) {
197         // FIXME: MDSAL-692: use hex-encoding instead
198         throwInvalidLength(expected, Arrays.toString(actual));
199     }
200
201     /**
202      * Throw an IllegalArgument exception describing a range violation.
203      *
204      * @param expected String describing expected ranges
205      * @param actual Actual observed object
206      * @throws IllegalArgumentException always
207      */
208     public static void throwInvalidRange(final String expected, final Object actual) {
209         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
210     }
211
212     /**
213      * Throw an IllegalArgument exception describing a range violation.
214      *
215      * @param expected String describing expected ranges
216      * @param actual Actual observed value
217      * @throws IllegalArgumentException always
218      */
219     public static void throwInvalidRange(final String expected, final int actual) {
220         // Not a code duplication: provides faster string concat via StringBuilder.append(int)
221         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
222     }
223
224     /**
225      * Throw an IllegalArgument exception describing a range violation.
226      *
227      * @param expected String describing expected ranges
228      * @param actual Actual observed value
229      * @throws IllegalArgumentException always
230      */
231     public static void throwInvalidRange(final String expected, final long actual) {
232         // Not a code duplication: provides faster string concat via StringBuilder.append(long)
233         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
234     }
235
236     /**
237      * Throw an IllegalArgument exception describing a range violation.
238      *
239      * @param expected Objects describing expected ranges
240      * @param actual Actual observed byte array
241      * @throws IllegalArgumentException always
242      */
243     public static void throwInvalidRange(final Object[] expected, final Object actual) {
244         throwInvalidRange(Arrays.toString(expected), actual);
245     }
246
247     /**
248      * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
249      *
250      * @param expected String describing expected ranges
251      * @param actual Actual observed value
252      * @throws IllegalArgumentException always
253      */
254     public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
255         throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
256             + ".");
257     }
258
259     /**
260      * Check whether specified List is null and if so return an immutable list instead. This method supports
261      * non-null default getter methods.
262      *
263      * @param <T> list element type
264      * @param input input list, may be null
265      * @return Input list or an empty list.
266      */
267     public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
268         return input != null ? input : ImmutableList.of();
269     }
270
271     /**
272      * Check whether specified Map is null and if so return an immutable map instead. This method supports
273      * non-null default getter methods.
274      *
275      * @param <K> key type
276      * @param <V> value type
277      * @param input input map, may be null
278      * @return Input map or an empty map.
279      */
280     public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
281         return input != null ? input : ImmutableMap.of();
282     }
283
284     /**
285      * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
286      * Builder/implementation list handover.
287      *
288      * @param <T> list element type
289      * @param input input list, may be null
290      * @return Input list or null.
291      */
292     public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
293         return input != null && input.isEmpty() ? null : input;
294     }
295
296     /**
297      * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
298      * Builder/implementation list handover.
299      *
300      * @param <K> key type
301      * @param <V> value type
302      * @param input input map, may be null
303      * @return Input map or null.
304      */
305     public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
306         return input != null && input.isEmpty() ? null : input;
307     }
308
309     /**
310      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
311      * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
312      * for both non-present and present-with-null objects.
313      *
314      * @param obj Internal object to hash
315      * @return Wrapper object hash code
316      */
317     public static int wrapperHashCode(final @Nullable Object obj) {
318         return wrapHashCode(Objects.hashCode(obj));
319     }
320
321     /**
322      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
323      * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
324      * for both non-present and present-with-null objects.
325      *
326      * @param obj Internal object to hash
327      * @return Wrapper object hash code
328      */
329     public static int wrapperHashCode(final byte @Nullable[] obj) {
330         return wrapHashCode(Arrays.hashCode(obj));
331     }
332
333     /**
334      * Utility method for checking whether a target object is a compatible DataObject.
335      *
336      * @param requiredClass Required DataObject class
337      * @param obj Object to check, may be null
338      * @return Object cast to required class, if its implemented class matches requirement, null otherwise
339      * @throws NullPointerException if {@code requiredClass} is null
340      */
341     public static <T extends DataObject> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
342             final @Nullable Object obj) {
343         return obj instanceof DataObject && requiredClass.equals(((DataObject) obj).implementedInterface())
344             ? requiredClass.cast(obj) : null;
345     }
346
347     /**
348      * Utility method for checking whether a target object is compatible.
349      *
350      * @param requiredClass Required class
351      * @param fieldName name of the field being filled
352      * @param obj Object to check, may be null
353      * @return Object cast to required class, if its class matches requirement, or null
354      * @throws IllegalArgumentException if {@code obj} is not an instance of {@code requiredClass}
355      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
356      */
357     public static <T> @Nullable T checkFieldCast(final @NonNull Class<T> requiredClass, final @NonNull String fieldName,
358             final @Nullable Object obj) {
359         try {
360             return requiredClass.cast(obj);
361         } catch (ClassCastException e) {
362             throw new IllegalArgumentException("Invalid input value for property \"" + fieldName + "\"", e);
363         }
364     }
365
366     /**
367      * Utility method for checking whether the items of target list is compatible.
368      *
369      * @param requiredClass Required item class
370      * @param fieldName name of the field being filled
371      * @param list List, which items should be checked
372      * @throws IllegalArgumentException if a list item is not instance of {@code requiredItemClass}
373      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
374      */
375     @SuppressWarnings("unchecked")
376     public static <T> @Nullable List<T> checkListFieldCast(final @NonNull Class<?> requiredClass,
377             final @NonNull String fieldName, final @Nullable List<?> list) {
378         if (list != null) {
379             try {
380                 list.forEach(item -> requiredClass.cast(requireNonNull(item)));
381             } catch (ClassCastException | NullPointerException e) {
382                 throw new IllegalArgumentException("Invalid input list item for property \"" + requireNonNull(fieldName)
383                     + "\"", e);
384             }
385         }
386         return (List<T>) list;
387     }
388
389     /**
390      * The constant '31' is the result of folding this code:
391      * <pre>
392      *   <code>
393      *     final int prime = 31;
394      *     int result = 1;
395      *     result = result * prime + Objects.hashCode(obj);
396      *     return result;
397      *   </code>
398      * </pre>
399      * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
400      *
401      * @param hash Wrapped object hash
402      * @return Wrapper object hash
403      */
404     private static int wrapHashCode(final int hash) {
405         return hash == 0 ? 31 : hash;
406     }
407 }