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