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