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