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