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 java.math.BigInteger;
18 import java.util.Arrays;
19 import java.util.List;
20 import java.util.Objects;
21 import java.util.regex.Pattern;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.yangtools.yang.common.Uint16;
25 import org.opendaylight.yangtools.yang.common.Uint32;
26 import org.opendaylight.yangtools.yang.common.Uint64;
27 import org.opendaylight.yangtools.yang.common.Uint8;
30 * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
31 * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
32 * general API stability requirements of the Binding Specification.
34 * @author Robert Varga
36 public final class CodeHelpers {
37 private CodeHelpers() {
42 * Require that an a value-related expression is true.
44 * @param expression Expression to evaluate
45 * @param value Value being validated
46 * @param options Valid value options checked
47 * @throws IllegalArgumentException if expression is false
49 public static void validValue(final boolean expression, final Object value, final String options) {
50 checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
54 * Require an argument being received. This is similar to {@link java.util.Objects#requireNonNull(Object)}, but
55 * throws an IllegalArgumentException.
58 * Implementation note: we expect argName to be a string literal or a constant, so that it's non-nullness can be
59 * quickly discovered for a call site (where we are going to be inlined).
61 * @param value Value itself
62 * @param name Symbolic name
63 * @return non-null value
64 * @throws IllegalArgumentException if value is null
65 * @throws NullPointerException if name is null
67 // FIXME: another advantage is that it is JDT-annotated, but we could live without that. At some point we should
68 // schedule a big ISE-to-NPE conversion and just use Objects.requireNonNull() instead.
69 public static <T> @NonNull T nonNullValue(@Nullable final T value, final @NonNull String name) {
71 checkArgument(value != null, "%s must not be null", name);
76 * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
78 * @param value Value itself
79 * @throws NullPointerException if value is null
81 public static void requireValue(@Nullable final Object value) {
82 requireNonNull(value, "Supplied value may not be null");
86 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
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
93 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
94 final @Nullable Object value) {
96 helper.add(name, value);
101 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
103 * @param helper Helper to append to
104 * @param name Name of the value
105 * @param value Value to append
106 * @throws NullPointerException if the name or helper is null
108 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
110 helper.add(name, Arrays.toString(value));
115 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
118 * @param patterns Patterns to compile
119 * @return Compiled patterns in an array
120 * @throws NullPointerException if the list or any of its elements is null
121 * @throws VerifyException if the list has fewer than two elements
123 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
124 final int size = patterns.size();
125 verify(size > 1, "Patterns has to have at least 2 elements");
126 final Pattern[] result = new Pattern[size];
127 for (int i = 0; i < size; ++i) {
128 result[i] = Pattern.compile(patterns.get(i));
134 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
135 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
137 * @param value Value to be checked.
138 * @param pattern Enforcement pattern
139 * @param regex Source regular expression, as defined in YANG model
140 * @throws IllegalArgumentException if the value does not match the pattern
141 * @throws NullPointerException if any of the arguments are null
143 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
144 if (!pattern.matcher(value).matches()) {
145 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
146 : "does not match required";
147 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
153 * Check whether a specified string value matches specified patterns. This method handles the distinction between
154 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
156 * @param value Value to be checked.
157 * @param patterns Enforcement patterns
158 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
159 * @throws IllegalArgumentException if the value does not match the pattern
160 * @throws NullPointerException if any of the arguments are null
161 * @throws VerifyException if the size of patterns and regexes does not match
163 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
164 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
165 for (int i = 0; i < patterns.length; ++i) {
166 checkPattern(value, patterns[i], regexes[i]);
171 * Throw an IllegalArgument exception describing a length violation.
173 * @param expected String describing expected lengths
174 * @param actual Actual observed object
175 * @throws IllegalArgumentException always
177 public static void throwInvalidLength(final String expected, final Object actual) {
178 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
182 * Throw an IllegalArgument exception describing a length violation.
184 * @param expected String describing expected lengths
185 * @param actual Actual observed byte array
186 * @throws IllegalArgumentException always
188 public static void throwInvalidLength(final String expected, final byte[] actual) {
189 throwInvalidLength(expected, Arrays.toString(actual));
193 * Throw an IllegalArgument exception describing a range violation.
195 * @param expected String describing expected ranges
196 * @param actual Actual observed object
197 * @throws IllegalArgumentException always
199 public static void throwInvalidRange(final String expected, final Object actual) {
200 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
204 * Throw an IllegalArgument exception describing a range violation.
206 * @param expected String describing expected ranges
207 * @param actual Actual observed value
208 * @throws IllegalArgumentException always
210 public static void throwInvalidRange(final String expected, final int actual) {
211 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
212 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
216 * Throw an IllegalArgument exception describing a range violation.
218 * @param expected String describing expected ranges
219 * @param actual Actual observed value
220 * @throws IllegalArgumentException always
222 public static void throwInvalidRange(final String expected, final long actual) {
223 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
224 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
228 * Throw an IllegalArgument exception describing a range violation.
230 * @param expected Objects describing expected ranges
231 * @param actual Actual observed byte array
232 * @throws IllegalArgumentException always
234 public static void throwInvalidRange(final Object[] expected, final Object actual) {
235 throwInvalidRange(Arrays.toString(expected), actual);
239 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
241 * @param expected String describing expected ranges
242 * @param actual Actual observed value
243 * @throws IllegalArgumentException always
245 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
246 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
251 * Check whether specified List is null and if so return an immutable list instead. This method supports
252 * non-null default getter methods.
254 * @param input input list, may be null
255 * @return Input list or an empty list.
257 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
258 return input != null ? input : ImmutableList.of();
262 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
263 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
264 * for both non-present and present-with-null objects.
266 * @param obj Internal object to hash
267 * @return Wrapper object hash code
269 public static int wrapperHashCode(final @Nullable Object obj) {
270 return wrapHashCode(Objects.hashCode(obj));
274 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
275 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
276 * for both non-present and present-with-null objects.
278 * @param obj Internal object to hash
279 * @return Wrapper object hash code
281 public static int wrapperHashCode(final byte @Nullable[] obj) {
282 return wrapHashCode(Arrays.hashCode(obj));
286 * Compatibility utility for converting a legacy {@link Short} {@code uint8} value to its {@link Uint8}
289 * @param value Legacy value
290 * @return Converted value
291 * @throws IllegalArgumentException if the value does not fit an Uint8
292 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
293 * compatibility methods.
296 public static @Nullable Uint8 compatUint(final @Nullable Short value) {
297 return value == null ? null : Uint8.valueOf(value.shortValue());
301 * Compatibility utility for converting a legacy {@link Integer} {@code uint16} value to its {@link Uint16}
304 * @param value Legacy value
305 * @return Converted value
306 * @throws IllegalArgumentException if the value does not fit an Uint16
307 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
308 * compatibility methods.
311 public static @Nullable Uint16 compatUint(final @Nullable Integer value) {
312 return value == null ? null : Uint16.valueOf(value.intValue());
316 * Compatibility utility for converting a legacy {@link Long} {@code uint32} value to its {@link Uint32}
319 * @param value Legacy value
320 * @return Converted value
321 * @throws IllegalArgumentException if the value does not fit an Uint32
322 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
323 * compatibility methods.
326 public static @Nullable Uint32 compatUint(final @Nullable Long value) {
327 return value == null ? null : Uint32.valueOf(value.longValue());
331 * Compatibility utility for converting a legacy {@link BigInteger} {@code uint64} value to its {@link Uint64}
334 * @param value Legacy value
335 * @return Converted value
336 * @throws IllegalArgumentException if the value does not fit an Uint64
337 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
338 * compatibility methods.
341 public static @Nullable Uint64 compatUint(final @Nullable BigInteger value) {
342 return value == null ? null : Uint64.valueOf(value);
346 * The constant '31' is the result of folding this code:
348 * final int prime = 31;
350 * result = result * prime + Objects.hashCode(obj);
353 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
355 * @param hash Wrapped object hash
356 * @return Wrapper object hash
358 private static int wrapHashCode(final int hash) {
359 return hash == 0 ? 31 : hash;