2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.binding;
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;
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;
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;
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.
31 * @author Robert Varga
33 public final class CodeHelpers {
34 private CodeHelpers() {
39 * Require that an a value-related expression is true.
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
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);
51 * Require an argument being received. This is similar to {@link java.util.Objects#requireNonNull(Object)}, but
52 * throws an IllegalArgumentException.
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).
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
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) {
68 checkArgument(value != null, "%s must not be null", name);
73 * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
75 * @param value Value itself
76 * @throws NullPointerException if value is null
78 public static void requireValue(@Nullable final Object value) {
79 requireNonNull(value, "Supplied value may not be null");
83 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
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
90 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
91 final @Nullable Object value) {
93 helper.add(name, value);
98 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
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
105 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
107 helper.add(name, Arrays.toString(value));
112 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
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
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));
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.
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
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 \""
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.
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
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]);
168 * Throw an IllegalArgument exception describing a length violation.
170 * @param expected String describing expected lengths
171 * @param actual Actual observed object
172 * @throws IllegalArgumentException always
174 public static void throwInvalidLength(final String expected, final Object actual) {
175 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
179 * Throw an IllegalArgument exception describing a length violation.
181 * @param expected String describing expected lengths
182 * @param actual Actual observed byte array
183 * @throws IllegalArgumentException always
185 public static void throwInvalidLength(final String expected, final byte[] actual) {
186 throwInvalidLength(expected, Arrays.toString(actual));
190 * Throw an IllegalArgument exception describing a range violation.
192 * @param expected String describing expected ranges
193 * @param actual Actual observed object
194 * @throws IllegalArgumentException always
196 public static void throwInvalidRange(final String expected, final Object actual) {
197 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
201 * Throw an IllegalArgument exception describing a range violation.
203 * @param expected String describing expected ranges
204 * @param actual Actual observed value
205 * @throws IllegalArgumentException always
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 + ".");
213 * Throw an IllegalArgument exception describing a range violation.
215 * @param expected String describing expected ranges
216 * @param actual Actual observed value
217 * @throws IllegalArgumentException always
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 + ".");
225 * Throw an IllegalArgument exception describing a range violation.
227 * @param expected Objects describing expected ranges
228 * @param actual Actual observed byte array
229 * @throws IllegalArgumentException always
231 public static void throwInvalidRange(final Object[] expected, final Object actual) {
232 throwInvalidRange(Arrays.toString(expected), actual);
236 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
238 * @param expected String describing expected ranges
239 * @param actual Actual observed value
240 * @throws IllegalArgumentException always
242 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
243 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
248 * Check whether specified List is null and if so return an immutable list instead. This method supports
249 * non-null default getter methods.
251 * @param <T> list element type
252 * @param input input list, may be null
253 * @return Input list or an empty list.
255 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
256 return input != null ? input : ImmutableList.of();
260 * Check whether specified Map is null and if so return an immutable map instead. This method supports
261 * non-null default getter methods.
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.
268 public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
269 return input != null ? input : ImmutableMap.of();
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.
277 * @param obj Internal object to hash
278 * @return Wrapper object hash code
280 public static int wrapperHashCode(final @Nullable Object obj) {
281 return wrapHashCode(Objects.hashCode(obj));
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.
289 * @param obj Internal object to hash
290 * @return Wrapper object hash code
292 public static int wrapperHashCode(final byte @Nullable[] obj) {
293 return wrapHashCode(Arrays.hashCode(obj));
297 * The constant '31' is the result of folding this code:
299 * final int prime = 31;
301 * result = result * prime + Objects.hashCode(obj);
304 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
306 * @param hash Wrapped object hash
307 * @return Wrapper object hash
309 private static int wrapHashCode(final int hash) {
310 return hash == 0 ? 31 : hash;