bf3afc2945fa9f34743bbdc24d98801ecc51ca45
[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.Objects;
22 import java.util.regex.Pattern;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
25
26 /**
27  * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
28  * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
29  * general API stability requirements of the Binding Specification.
30  *
31  * @author Robert Varga
32  */
33 public final class CodeHelpers {
34     private CodeHelpers() {
35         // Hidden
36     }
37
38     /**
39      * Require that an a value-related expression is true.
40      *
41      * @param expression Expression to evaluate
42      * @param value Value being validated
43      * @param options Valid value options checked
44      * @throws IllegalArgumentException if expression is false
45      */
46     public static void validValue(final boolean expression, final Object value, final String options) {
47         checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
48     }
49
50     /**
51      * A shortcut for {@code Preconditions.checkNotNull(value, "Key component \"%s\" must not be null", name)}.
52      *
53      * @param value Value itself
54      * @param name Name of the value
55      * @return Non-null value
56      * @throws NullPointerException if value is null
57      */
58     public static <T> @NonNull T requireKeyProp(final @Nullable T value, final @NonNull String name) {
59         if (value == null) {
60             throw new NullPointerException("Key component \"" + name + "\" may not be null");
61         }
62         return value;
63     }
64
65     /**
66      * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
67      *
68      * @param value Value itself
69      * @throws NullPointerException if value is null
70      */
71     public static void requireValue(final @Nullable Object value) {
72         requireNonNull(value, "Supplied value may not be null");
73     }
74
75     /**
76      * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
77      *
78      * @param helper Helper to append to
79      * @param name Name of the value
80      * @param value Value to append
81      * @throws NullPointerException if the name or helper is null
82      */
83     public static void appendValue(final ToStringHelper helper, final @NonNull String name,
84             final @Nullable Object value) {
85         if (value != null) {
86             helper.add(name, value);
87         }
88     }
89
90     /**
91      * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
92      *
93      * @param helper Helper to append to
94      * @param name Name of the value
95      * @param value Value to append
96      * @throws NullPointerException if the name or helper is null
97      */
98     public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
99         if (value != null) {
100             helper.add(name, Arrays.toString(value));
101         }
102     }
103
104     /**
105      * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
106      * expressions.
107      *
108      * @param patterns Patterns to compile
109      * @return Compiled patterns in an array
110      * @throws NullPointerException if the list or any of its elements is null
111      * @throws VerifyException if the list has fewer than two elements
112      */
113     public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
114         final int size = patterns.size();
115         verify(size > 1, "Patterns has to have at least 2 elements");
116         final Pattern[] result = new Pattern[size];
117         for (int i = 0; i < size; ++i) {
118             result[i] = Pattern.compile(patterns.get(i));
119         }
120         return result;
121     }
122
123     /**
124      * Check whether a specified string value matches a specified pattern. This method handles the distinction between
125      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
126      *
127      * @param value Value to be checked.
128      * @param pattern Enforcement pattern
129      * @param regex Source regular expression, as defined in YANG model
130      * @throws IllegalArgumentException if the value does not match the pattern
131      * @throws NullPointerException if any of the arguments are null
132      */
133     public static void checkPattern(final String value, final Pattern pattern, final String regex) {
134         if (!pattern.matcher(value).matches()) {
135             final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
136                 : "does not match required";
137             throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
138                     + regex + "\"");
139         }
140     }
141
142     /**
143      * Check whether a specified string value matches specified patterns. This method handles the distinction between
144      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
145      *
146      * @param value Value to be checked.
147      * @param patterns Enforcement patterns
148      * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
149      * @throws IllegalArgumentException if the value does not match the pattern
150      * @throws NullPointerException if any of the arguments are null
151      * @throws VerifyException if the size of patterns and regexes does not match
152      */
153     public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
154         verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
155         for (int i = 0; i < patterns.length; ++i) {
156             checkPattern(value, patterns[i], regexes[i]);
157         }
158     }
159
160     /**
161      * Throw an IllegalArgument exception describing a length violation.
162      *
163      * @param expected String describing expected lengths
164      * @param actual Actual observed object
165      * @throws IllegalArgumentException always
166      */
167     public static void throwInvalidLength(final String expected, final Object actual) {
168         throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
169     }
170
171     /**
172      * Throw an IllegalArgument exception describing a length violation.
173      *
174      * @param expected String describing expected lengths
175      * @param actual Actual observed byte array
176      * @throws IllegalArgumentException always
177      */
178     public static void throwInvalidLength(final String expected, final byte[] actual) {
179         throwInvalidLength(expected, Arrays.toString(actual));
180     }
181
182     /**
183      * Throw an IllegalArgument exception describing a range violation.
184      *
185      * @param expected String describing expected ranges
186      * @param actual Actual observed object
187      * @throws IllegalArgumentException always
188      */
189     public static void throwInvalidRange(final String expected, final Object actual) {
190         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
191     }
192
193     /**
194      * Throw an IllegalArgument exception describing a range violation.
195      *
196      * @param expected String describing expected ranges
197      * @param actual Actual observed value
198      * @throws IllegalArgumentException always
199      */
200     public static void throwInvalidRange(final String expected, final int actual) {
201         // Not a code duplication: provides faster string concat via StringBuilder.append(int)
202         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
203     }
204
205     /**
206      * Throw an IllegalArgument exception describing a range violation.
207      *
208      * @param expected String describing expected ranges
209      * @param actual Actual observed value
210      * @throws IllegalArgumentException always
211      */
212     public static void throwInvalidRange(final String expected, final long actual) {
213         // Not a code duplication: provides faster string concat via StringBuilder.append(long)
214         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
215     }
216
217     /**
218      * Throw an IllegalArgument exception describing a range violation.
219      *
220      * @param expected Objects describing expected ranges
221      * @param actual Actual observed byte array
222      * @throws IllegalArgumentException always
223      */
224     public static void throwInvalidRange(final Object[] expected, final Object actual) {
225         throwInvalidRange(Arrays.toString(expected), actual);
226     }
227
228     /**
229      * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
230      *
231      * @param expected String describing expected ranges
232      * @param actual Actual observed value
233      * @throws IllegalArgumentException always
234      */
235     public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
236         throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
237             + ".");
238     }
239
240     /**
241      * Check whether specified List is null and if so return an immutable list instead. This method supports
242      * non-null default getter methods.
243      *
244      * @param <T> list element type
245      * @param input input list, may be null
246      * @return Input list or an empty list.
247      */
248     public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
249         return input != null ? input : ImmutableList.of();
250     }
251
252     /**
253      * Check whether specified Map is null and if so return an immutable map instead. This method supports
254      * non-null default getter methods.
255      *
256      * @param <K> key type
257      * @param <V> value type
258      * @param input input map, may be null
259      * @return Input map or an empty map.
260      */
261     public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
262         return input != null ? input : ImmutableMap.of();
263     }
264
265     /**
266      * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
267      * Builder/implementation list handover.
268      *
269      * @param <T> list element type
270      * @param input input list, may be null
271      * @return Input list or null.
272      */
273     public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
274         return input != null && input.isEmpty() ? null : input;
275     }
276
277     /**
278      * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
279      * Builder/implementation list handover.
280      *
281      * @param <K> key type
282      * @param <V> value type
283      * @param input input map, may be null
284      * @return Input map or null.
285      */
286     public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
287         return input != null && input.isEmpty() ? null : input;
288     }
289
290     /**
291      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
292      * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
293      * for both non-present and present-with-null objects.
294      *
295      * @param obj Internal object to hash
296      * @return Wrapper object hash code
297      */
298     public static int wrapperHashCode(final @Nullable Object obj) {
299         return wrapHashCode(Objects.hashCode(obj));
300     }
301
302     /**
303      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
304      * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
305      * for both non-present and present-with-null objects.
306      *
307      * @param obj Internal object to hash
308      * @return Wrapper object hash code
309      */
310     public static int wrapperHashCode(final byte @Nullable[] obj) {
311         return wrapHashCode(Arrays.hashCode(obj));
312     }
313
314     /**
315      * Utility method for checking whether a target object is a compatible DataObject.
316      *
317      * @param requiredClass Required DataObject class
318      * @param obj Object to check, may be null
319      * @return Object cast to required class, if its implemented class matches requirement, null otherwise
320      * @throws NullPointerException if {@code requiredClass} is null
321      */
322     public static <T extends DataObject> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
323             final @Nullable Object obj) {
324         return obj instanceof DataObject && requiredClass.equals(((DataObject) obj).implementedInterface())
325             ? requiredClass.cast(obj) : null;
326     }
327
328     /**
329      * Utility method for checking whether a target object is compatible.
330      *
331      * @param requiredClass Required class
332      * @param fieldName name of the field being filled
333      * @param obj Object to check, may be null
334      * @return Object cast to required class, if its class matches requirement, or null
335      * @throws IllegalArgumentException if {@code obj} is not an instance of {@code requiredClass}
336      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
337      */
338     public static <T> @Nullable T checkFieldCast(final @NonNull Class<T> requiredClass, final @NonNull String fieldName,
339             final @Nullable Object obj) {
340         try {
341             return requiredClass.cast(obj);
342         } catch (ClassCastException e) {
343             throw new IllegalArgumentException("Invalid input value for property \"" + fieldName + "\"", e);
344         }
345     }
346
347     /**
348      * Utility method for checking whether the items of target list is compatible.
349      *
350      * @param requiredClass Required item class
351      * @param fieldName name of the field being filled
352      * @param list List, which items should be checked
353      * @throws IllegalArgumentException if a list item is not instance of {@code requiredItemClass}
354      * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
355      */
356     @SuppressWarnings("unchecked")
357     public static <T> @Nullable List<T> checkListFieldCast(final @NonNull Class<?> requiredClass,
358             final @NonNull String fieldName, final @Nullable List<?> list) {
359         if (list != null) {
360             try {
361                 list.forEach(item -> requiredClass.cast(requireNonNull(item)));
362             } catch (ClassCastException | NullPointerException e) {
363                 throw new IllegalArgumentException("Invalid input list item for property \"" + requireNonNull(fieldName)
364                     + "\"", e);
365             }
366         }
367         return (List<T>) list;
368     }
369
370     /**
371      * The constant '31' is the result of folding this code:
372      * <pre>
373      *   <code>
374      *     final int prime = 31;
375      *     int result = 1;
376      *     result = result * prime + Objects.hashCode(obj);
377      *     return result;
378      *   </code>
379      * </pre>
380      * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
381      *
382      * @param hash Wrapped object hash
383      * @return Wrapper object hash
384      */
385     private static int wrapHashCode(final int hash) {
386         return hash == 0 ? 31 : hash;
387     }
388 }