774ee6cdebc81740ffdec6e4e3c1b9882b8498ad
[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 java.util.Arrays;
18 import java.util.List;
19 import java.util.Objects;
20 import java.util.regex.Pattern;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.eclipse.jdt.annotation.Nullable;
23
24 /**
25  * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
26  * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
27  * general API stability requirements of the Binding Specification.
28  *
29  * @author Robert Varga
30  */
31 public final class CodeHelpers {
32     private CodeHelpers() {
33         // Hidden
34     }
35
36     /**
37      * Require that an a value-related expression is true.
38      *
39      * @param expression Expression to evaluate
40      * @param value Value being validated
41      * @param options Valid value options checked
42      * @throws IllegalArgumentException if expression is false
43      */
44     public static void validValue(final boolean expression, final Object value, final String options) {
45         checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
46     }
47
48     /**
49      * Require an argument being received. This is similar to {@link java.util.Objects#requireNonNull(Object)}, but
50      * throws an IllegalArgumentException.
51      *
52      * <p>
53      * Implementation note: we expect argName to be a string literal or a constant, so that it's non-nullness can be
54      *                      quickly discovered for a call site (where we are going to be inlined).
55      *
56      * @param value Value itself
57      * @param name Symbolic name
58      * @return non-null value
59      * @throws IllegalArgumentException if value is null
60      * @throws NullPointerException if name is null
61      */
62     // FIXME: another advantage is that it is JDT-annotated, but we could live without that. At some point we should
63     //        schedule a big ISE-to-NPE conversion and just use Objects.requireNonNull() instead.
64     public static <T> @NonNull T nonNullValue(@Nullable final T value, final @NonNull String name) {
65         requireNonNull(name);
66         checkArgument(value != null, "%s must not be null", name);
67         return value;
68     }
69
70     /**
71      * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
72      *
73      * @param helper Helper to append to
74      * @param name Name of the value
75      * @param value Value to append
76      * @throws NullPointerException if the name or helper is null
77      */
78     public static void appendValue(final @NonNull ToStringHelper helper, final @NonNull String name,
79             final @Nullable Object value) {
80         if (value != null) {
81             helper.add(name, value);
82         }
83     }
84
85     /**
86      * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
87      *
88      * @param helper Helper to append to
89      * @param name Name of the value
90      * @param value Value to append
91      * @throws NullPointerException if the name or helper is null
92      */
93     public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
94         if (value != null) {
95             helper.add(name, Arrays.toString(value));
96         }
97     }
98
99     /**
100      * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
101      * expressions.
102      *
103      * @param patterns Patterns to compile
104      * @return Compiled patterns in an array
105      * @throws NullPointerException if the list or any of its elements is null
106      * @throws VerifyException if the list has fewer than two elements
107      */
108     public static @NonNull Pattern[] compilePatterns(final @NonNull List<String> patterns) {
109         final int size = patterns.size();
110         verify(size > 1, "Patterns has to have at least 2 elements");
111         final @NonNull Pattern[] result = new Pattern[size];
112         for (int i = 0; i < size; ++i) {
113             result[i] = Pattern.compile(patterns.get(i));
114         }
115         return result;
116     }
117
118     /**
119      * Check whether a specified string value matches a specified pattern. This method handles the distinction between
120      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
121      *
122      * @param value Value to be checked.
123      * @param pattern Enforcement pattern
124      * @param regex Source regular expression, as defined in YANG model
125      * @throws IllegalArgumentException if the value does not match the pattern
126      * @throws NullPointerException if any of the arguments are null
127      */
128     public static void checkPattern(final String value, final Pattern pattern, final String regex) {
129         if (!pattern.matcher(value).matches()) {
130             final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
131                 : "does not match required";
132             throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
133                     + regex + "\"");
134         }
135     }
136
137     /**
138      * Check whether a specified string value matches specified patterns. This method handles the distinction between
139      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
140      *
141      * @param value Value to be checked.
142      * @param patterns Enforcement patterns
143      * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
144      * @throws IllegalArgumentException if the value does not match the pattern
145      * @throws NullPointerException if any of the arguments are null
146      * @throws VerifyException if the size of patterns and regexes does not match
147      */
148     public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
149         verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
150         for (int i = 0; i < patterns.length; ++i) {
151             checkPattern(value, patterns[i], regexes[i]);
152         }
153     }
154
155     /**
156      * Throw an IllegalArgument exception describing a length violation.
157      *
158      * @param expected String describing expected lengths
159      * @param actual Actual observed object
160      * @throws IllegalArgumentException always
161      */
162     public static void throwInvalidLength(final String expected, final Object actual) {
163         throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
164     }
165
166     /**
167      * Throw an IllegalArgument exception describing a length violation.
168      *
169      * @param expected String describing expected lengths
170      * @param actual Actual observed byte array
171      * @throws IllegalArgumentException always
172      */
173     public static void throwInvalidLength(final String expected, final byte[] actual) {
174         throwInvalidLength(expected, Arrays.toString(actual));
175     }
176
177     /**
178      * Throw an IllegalArgument exception describing a range violation.
179      *
180      * @param expected String describing expected ranges
181      * @param actual Actual observed object
182      * @throws IllegalArgumentException always
183      */
184     public static void throwInvalidRange(final String expected, final Object actual) {
185         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
186     }
187
188     /**
189      * Throw an IllegalArgument exception describing a range violation.
190      *
191      * @param expected String describing expected ranges
192      * @param actual Actual observed value
193      * @throws IllegalArgumentException always
194      */
195     public static void throwInvalidRange(final String expected, final int actual) {
196         // Not a code duplication: provides faster string concat via StringBuilder.append(int)
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 long actual) {
208         // Not a code duplication: provides faster string concat via StringBuilder.append(long)
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 Objects describing expected ranges
216      * @param actual Actual observed byte array
217      * @throws IllegalArgumentException always
218      */
219     public static void throwInvalidRange(final Object[] expected, final Object actual) {
220         throwInvalidRange(Arrays.toString(expected), actual);
221     }
222
223     /**
224      * Check whether specified List is null and if so return an immutable list instead. This method supports
225      * non-null default getter methods.
226      *
227      * @param input input list, may be null
228      * @return Input list or an empty list.
229      */
230     public static <T> List<T> nonnull(final @Nullable List<T> input) {
231         return input != null ? input : ImmutableList.of();
232     }
233
234     /**
235      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
236      * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
237      * for both non-present and present-with-null objects.
238      *
239      * @param obj Internal object to hash
240      * @return Wrapper object hash code
241      */
242     public static int wrapperHashCode(final @Nullable Object obj) {
243         return wrapHashCode(Objects.hashCode(obj));
244     }
245
246     /**
247      * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
248      * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
249      * for both non-present and present-with-null objects.
250      *
251      * @param obj Internal object to hash
252      * @return Wrapper object hash code
253      */
254     public static int wrapperHashCode(final byte @Nullable[] obj) {
255         return wrapHashCode(Arrays.hashCode(obj));
256     }
257
258     /**
259      * The constant '31' is the result of folding this code:
260      * <pre>
261      *     final int prime = 31;
262      *     int result = 1;
263      *     result = result * prime + Objects.hashCode(obj);
264      *     return result;
265      * </pre>
266      * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
267      *
268      * @param hash Wrapped object hash
269      * @return Wrapper object hash
270      */
271     private static int wrapHashCode(final int hash) {
272         return hash == 0 ? 31 : hash;
273     }
274 }