Revert "Remove deprecated uint migration elements"
[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 Objects.requireNonNull(value, "Supplied value may not be null")}.
58      *
59      * @param value Value itself
60      * @throws NullPointerException if value is null
61      */
62     public static void requireValue(@Nullable final Object value) {
63         requireNonNull(value, "Supplied value may not be null");
64     }
65
66     /**
67      * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
68      *
69      * @param helper Helper to append to
70      * @param name Name of the value
71      * @param value Value to append
72      * @throws NullPointerException if the name or helper is null
73      */
74     public static void appendValue(final ToStringHelper helper, final @NonNull String name,
75             final @Nullable Object value) {
76         if (value != null) {
77             helper.add(name, value);
78         }
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 String name, final byte[] value) {
90         if (value != null) {
91             helper.add(name, Arrays.toString(value));
92         }
93     }
94
95     /**
96      * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
97      * expressions.
98      *
99      * @param patterns Patterns to compile
100      * @return Compiled patterns in an array
101      * @throws NullPointerException if the list or any of its elements is null
102      * @throws VerifyException if the list has fewer than two elements
103      */
104     public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
105         final int size = patterns.size();
106         verify(size > 1, "Patterns has to have at least 2 elements");
107         final Pattern[] result = new Pattern[size];
108         for (int i = 0; i < size; ++i) {
109             result[i] = Pattern.compile(patterns.get(i));
110         }
111         return result;
112     }
113
114     /**
115      * Check whether a specified string value matches a specified pattern. This method handles the distinction between
116      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
117      *
118      * @param value Value to be checked.
119      * @param pattern Enforcement pattern
120      * @param regex Source regular expression, as defined in YANG model
121      * @throws IllegalArgumentException if the value does not match the pattern
122      * @throws NullPointerException if any of the arguments are null
123      */
124     public static void checkPattern(final String value, final Pattern pattern, final String regex) {
125         if (!pattern.matcher(value).matches()) {
126             final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
127                 : "does not match required";
128             throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
129                     + regex + "\"");
130         }
131     }
132
133     /**
134      * Check whether a specified string value matches specified patterns. This method handles the distinction between
135      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
136      *
137      * @param value Value to be checked.
138      * @param patterns Enforcement patterns
139      * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
140      * @throws IllegalArgumentException if the value does not match the pattern
141      * @throws NullPointerException if any of the arguments are null
142      * @throws VerifyException if the size of patterns and regexes does not match
143      */
144     public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
145         verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
146         for (int i = 0; i < patterns.length; ++i) {
147             checkPattern(value, patterns[i], regexes[i]);
148         }
149     }
150
151     /**
152      * Throw an IllegalArgument exception describing a length violation.
153      *
154      * @param expected String describing expected lengths
155      * @param actual Actual observed object
156      * @throws IllegalArgumentException always
157      */
158     public static void throwInvalidLength(final String expected, final Object actual) {
159         throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
160     }
161
162     /**
163      * Throw an IllegalArgument exception describing a length violation.
164      *
165      * @param expected String describing expected lengths
166      * @param actual Actual observed byte array
167      * @throws IllegalArgumentException always
168      */
169     public static void throwInvalidLength(final String expected, final byte[] actual) {
170         throwInvalidLength(expected, Arrays.toString(actual));
171     }
172
173     /**
174      * Throw an IllegalArgument exception describing a range violation.
175      *
176      * @param expected String describing expected ranges
177      * @param actual Actual observed object
178      * @throws IllegalArgumentException always
179      */
180     public static void throwInvalidRange(final String expected, final Object actual) {
181         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
182     }
183
184     /**
185      * Throw an IllegalArgument exception describing a range violation.
186      *
187      * @param expected String describing expected ranges
188      * @param actual Actual observed value
189      * @throws IllegalArgumentException always
190      */
191     public static void throwInvalidRange(final String expected, final int actual) {
192         // Not a code duplication: provides faster string concat via StringBuilder.append(int)
193         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
194     }
195
196     /**
197      * Throw an IllegalArgument exception describing a range violation.
198      *
199      * @param expected String describing expected ranges
200      * @param actual Actual observed value
201      * @throws IllegalArgumentException always
202      */
203     public static void throwInvalidRange(final String expected, final long actual) {
204         // Not a code duplication: provides faster string concat via StringBuilder.append(long)
205         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
206     }
207
208     /**
209      * Throw an IllegalArgument exception describing a range violation.
210      *
211      * @param expected Objects describing expected ranges
212      * @param actual Actual observed byte array
213      * @throws IllegalArgumentException always
214      */
215     public static void throwInvalidRange(final Object[] expected, final Object actual) {
216         throwInvalidRange(Arrays.toString(expected), actual);
217     }
218
219     /**
220      * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
221      *
222      * @param expected String describing expected ranges
223      * @param actual Actual observed value
224      * @throws IllegalArgumentException always
225      */
226     public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
227         throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
228             + ".");
229     }
230
231     /**
232      * Check whether specified List is null and if so return an immutable list instead. This method supports
233      * non-null default getter methods.
234      *
235      * @param <T> list element type
236      * @param input input list, may be null
237      * @return Input list or an empty list.
238      */
239     public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
240         return input != null ? input : ImmutableList.of();
241     }
242
243     /**
244      * Check whether specified Map is null and if so return an immutable map instead. This method supports
245      * non-null default getter methods.
246      *
247      * @param <K> key type
248      * @param <V> value type
249      * @param input input map, may be null
250      * @return Input map or an empty map.
251      */
252     public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
253         return input != null ? input : ImmutableMap.of();
254     }
255
256     /**
257      * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
258      * Builder/implementation list handover.
259      *
260      * @param <T> list element type
261      * @param input input list, may be null
262      * @return Input list or null.
263      */
264     public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
265         return input != null && input.isEmpty() ? null : input;
266     }
267
268     /**
269      * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
270      * Builder/implementation list handover.
271      *
272      * @param <K> key type
273      * @param <V> value type
274      * @param input input map, may be null
275      * @return Input map or null.
276      */
277     public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
278         return input != null && input.isEmpty() ? null : input;
279     }
280
281     /**
282      * Compatibility utility for turning a List of identifiable objects to an indexed map.
283      *
284      * @param <K> key type
285      * @param <V> identifiable type
286      * @param list legacy list
287      * @return Indexed map
288      * @throws IllegalArgumentException if the list contains entries with the same key
289      * @throws NullPointerException if the list contains a null entry
290      * @deprecated This method is a transitional helper used only in methods deprecated themselves.
291      */
292     // FIXME: MDSAL-540: remove this method
293     @Deprecated
294     public static <K extends Identifier<V>, V extends Identifiable<K>> @Nullable Map<K, V> compatMap(
295             final @Nullable List<V> list) {
296         return list == null || list.isEmpty() ? null : Maps.uniqueIndex(list, Identifiable::key);
297     }
298
299     /**
300      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
301      * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
302      * for both non-present and present-with-null objects.
303      *
304      * @param obj Internal object to hash
305      * @return Wrapper object hash code
306      */
307     public static int wrapperHashCode(final @Nullable Object obj) {
308         return wrapHashCode(Objects.hashCode(obj));
309     }
310
311     /**
312      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
313      * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
314      * for both non-present and present-with-null objects.
315      *
316      * @param obj Internal object to hash
317      * @return Wrapper object hash code
318      */
319     public static int wrapperHashCode(final byte @Nullable[] obj) {
320         return wrapHashCode(Arrays.hashCode(obj));
321     }
322
323     /**
324      * Compatibility utility for converting a legacy {@link Short} {@code uint8} value to its {@link Uint8}
325      * counterpart.
326      *
327      * @param value Legacy value
328      * @return Converted value
329      * @throws IllegalArgumentException if the value does not fit an Uint8
330      * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
331      *             compatibility methods.
332      */
333     @Deprecated
334     public static @Nullable Uint8 compatUint(final @Nullable Short value) {
335         return value == null ? null : Uint8.valueOf(value.shortValue());
336     }
337
338     /**
339      * Compatibility utility for converting a legacy {@link Integer} {@code uint16} value to its {@link Uint16}
340      * counterpart.
341      *
342      * @param value Legacy value
343      * @return Converted value
344      * @throws IllegalArgumentException if the value does not fit an Uint16
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 Uint16 compatUint(final @Nullable Integer value) {
350         return value == null ? null : Uint16.valueOf(value.intValue());
351     }
352
353     /**
354      * Compatibility utility for converting a legacy {@link Long} {@code uint32} value to its {@link Uint32}
355      * counterpart.
356      *
357      * @param value Legacy value
358      * @return Converted value
359      * @throws IllegalArgumentException if the value does not fit an Uint32
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 Uint32 compatUint(final @Nullable Long value) {
365         return value == null ? null : Uint32.valueOf(value.longValue());
366     }
367
368     /**
369      * Compatibility utility for converting a legacy {@link BigInteger} {@code uint64} value to its {@link Uint64}
370      * counterpart.
371      *
372      * @param value Legacy value
373      * @return Converted value
374      * @throws IllegalArgumentException if the value does not fit an Uint64
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 Uint64 compatUint(final @Nullable BigInteger value) {
380         return value == null ? null : Uint64.valueOf(value);
381     }
382
383     /**
384      * The constant '31' is the result of folding this code:
385      * <pre>
386      *     final int prime = 31;
387      *     int result = 1;
388      *     result = result * prime + Objects.hashCode(obj);
389      *     return result;
390      * </pre>
391      * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
392      *
393      * @param hash Wrapped object hash
394      * @return Wrapper object hash
395      */
396     private static int wrapHashCode(final int hash) {
397         return hash == 0 ? 31 : hash;
398     }
399 }