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 com.google.common.collect.Maps;
19 import java.math.BigInteger;
20 import java.util.Arrays;
21 import java.util.List;
23 import java.util.Objects;
24 import java.util.regex.Pattern;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.yangtools.yang.common.Uint16;
28 import org.opendaylight.yangtools.yang.common.Uint32;
29 import org.opendaylight.yangtools.yang.common.Uint64;
30 import org.opendaylight.yangtools.yang.common.Uint8;
33 * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
34 * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
35 * general API stability requirements of the Binding Specification.
37 * @author Robert Varga
39 public final class CodeHelpers {
40 private CodeHelpers() {
45 * Require that an a value-related expression is true.
47 * @param expression Expression to evaluate
48 * @param value Value being validated
49 * @param options Valid value options checked
50 * @throws IllegalArgumentException if expression is false
52 public static void validValue(final boolean expression, final Object value, final String options) {
53 checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
57 * A shortcut for {@code Preconditions.checkNotNull(value, "Key component \"%s\" must not be null", name)}.
59 * @param value Value itself
60 * @param name Name of the value
61 * @return Non-null value
62 * @throws NullPointerException if value is null
64 public static <T> @NonNull T requireKeyProp(final @Nullable T value, final @NonNull String name) {
66 throw new NullPointerException("Key component \"" + name + "\" may not be null");
72 * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
74 * @param value Value itself
75 * @throws NullPointerException if value is null
77 public static void requireValue(final @Nullable Object value) {
78 requireNonNull(value, "Supplied value may not be null");
82 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
84 * @param helper Helper to append to
85 * @param name Name of the value
86 * @param value Value to append
87 * @throws NullPointerException if the name or helper is null
89 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
90 final @Nullable Object value) {
92 helper.add(name, value);
97 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
99 * @param helper Helper to append to
100 * @param name Name of the value
101 * @param value Value to append
102 * @throws NullPointerException if the name or helper is null
104 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
106 helper.add(name, Arrays.toString(value));
111 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
114 * @param patterns Patterns to compile
115 * @return Compiled patterns in an array
116 * @throws NullPointerException if the list or any of its elements is null
117 * @throws VerifyException if the list has fewer than two elements
119 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
120 final int size = patterns.size();
121 verify(size > 1, "Patterns has to have at least 2 elements");
122 final Pattern[] result = new Pattern[size];
123 for (int i = 0; i < size; ++i) {
124 result[i] = Pattern.compile(patterns.get(i));
130 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
131 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
133 * @param value Value to be checked.
134 * @param pattern Enforcement pattern
135 * @param regex Source regular expression, as defined in YANG model
136 * @throws IllegalArgumentException if the value does not match the pattern
137 * @throws NullPointerException if any of the arguments are null
139 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
140 if (!pattern.matcher(value).matches()) {
141 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
142 : "does not match required";
143 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
149 * Check whether a specified string value matches specified patterns. This method handles the distinction between
150 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
152 * @param value Value to be checked.
153 * @param patterns Enforcement patterns
154 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
155 * @throws IllegalArgumentException if the value does not match the pattern
156 * @throws NullPointerException if any of the arguments are null
157 * @throws VerifyException if the size of patterns and regexes does not match
159 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
160 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
161 for (int i = 0; i < patterns.length; ++i) {
162 checkPattern(value, patterns[i], regexes[i]);
167 * Throw an IllegalArgument exception describing a length violation.
169 * @param expected String describing expected lengths
170 * @param actual Actual observed object
171 * @throws IllegalArgumentException always
173 public static void throwInvalidLength(final String expected, final Object actual) {
174 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
178 * Throw an IllegalArgument exception describing a length violation.
180 * @param expected String describing expected lengths
181 * @param actual Actual observed byte array
182 * @throws IllegalArgumentException always
184 public static void throwInvalidLength(final String expected, final byte[] actual) {
185 throwInvalidLength(expected, Arrays.toString(actual));
189 * Throw an IllegalArgument exception describing a range violation.
191 * @param expected String describing expected ranges
192 * @param actual Actual observed object
193 * @throws IllegalArgumentException always
195 public static void throwInvalidRange(final String expected, final Object actual) {
196 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
200 * Throw an IllegalArgument exception describing a range violation.
202 * @param expected String describing expected ranges
203 * @param actual Actual observed value
204 * @throws IllegalArgumentException always
206 public static void throwInvalidRange(final String expected, final int actual) {
207 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
208 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
212 * Throw an IllegalArgument exception describing a range violation.
214 * @param expected String describing expected ranges
215 * @param actual Actual observed value
216 * @throws IllegalArgumentException always
218 public static void throwInvalidRange(final String expected, final long actual) {
219 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
220 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
224 * Throw an IllegalArgument exception describing a range violation.
226 * @param expected Objects describing expected ranges
227 * @param actual Actual observed byte array
228 * @throws IllegalArgumentException always
230 public static void throwInvalidRange(final Object[] expected, final Object actual) {
231 throwInvalidRange(Arrays.toString(expected), actual);
235 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
237 * @param expected String describing expected ranges
238 * @param actual Actual observed value
239 * @throws IllegalArgumentException always
241 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
242 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
247 * Check whether specified List is null and if so return an immutable list instead. This method supports
248 * non-null default getter methods.
250 * @param <T> list element type
251 * @param input input list, may be null
252 * @return Input list or an empty list.
254 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
255 return input != null ? input : ImmutableList.of();
259 * Check whether specified Map is null and if so return an immutable map instead. This method supports
260 * non-null default getter methods.
262 * @param <K> key type
263 * @param <V> value type
264 * @param input input map, may be null
265 * @return Input map or an empty map.
267 public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
268 return input != null ? input : ImmutableMap.of();
272 * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
273 * Builder/implementation list handover.
275 * @param <T> list element type
276 * @param input input list, may be null
277 * @return Input list or null.
279 public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
280 return input != null && input.isEmpty() ? null : input;
284 * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
285 * Builder/implementation list handover.
287 * @param <K> key type
288 * @param <V> value type
289 * @param input input map, may be null
290 * @return Input map or null.
292 public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
293 return input != null && input.isEmpty() ? null : input;
297 * Compatibility utility for turning a List of identifiable objects to an indexed map.
299 * @param <K> key type
300 * @param <V> identifiable type
301 * @param list legacy list
302 * @return Indexed map
303 * @throws IllegalArgumentException if the list contains entries with the same key
304 * @throws NullPointerException if the list contains a null entry
305 * @deprecated This method is a transitional helper used only in methods deprecated themselves.
307 // FIXME: MDSAL-540: remove this method
309 public static <K extends Identifier<V>, V extends Identifiable<K>> @Nullable Map<K, V> compatMap(
310 final @Nullable List<V> list) {
311 return list == null || list.isEmpty() ? null : Maps.uniqueIndex(list, Identifiable::key);
315 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
316 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
317 * for both non-present and present-with-null objects.
319 * @param obj Internal object to hash
320 * @return Wrapper object hash code
322 public static int wrapperHashCode(final @Nullable Object obj) {
323 return wrapHashCode(Objects.hashCode(obj));
327 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
328 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
329 * for both non-present and present-with-null objects.
331 * @param obj Internal object to hash
332 * @return Wrapper object hash code
334 public static int wrapperHashCode(final byte @Nullable[] obj) {
335 return wrapHashCode(Arrays.hashCode(obj));
339 * Compatibility utility for converting a legacy {@link Short} {@code uint8} value to its {@link Uint8}
342 * @param value Legacy value
343 * @return Converted value
344 * @throws IllegalArgumentException if the value does not fit an Uint8
345 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
346 * compatibility methods.
349 public static @Nullable Uint8 compatUint(final @Nullable Short value) {
350 return value == null ? null : Uint8.valueOf(value.shortValue());
354 * Compatibility utility for converting a legacy {@link Integer} {@code uint16} value to its {@link Uint16}
357 * @param value Legacy value
358 * @return Converted value
359 * @throws IllegalArgumentException if the value does not fit an Uint16
360 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
361 * compatibility methods.
364 public static @Nullable Uint16 compatUint(final @Nullable Integer value) {
365 return value == null ? null : Uint16.valueOf(value.intValue());
369 * Compatibility utility for converting a legacy {@link Long} {@code uint32} value to its {@link Uint32}
372 * @param value Legacy value
373 * @return Converted value
374 * @throws IllegalArgumentException if the value does not fit an Uint32
375 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
376 * compatibility methods.
379 public static @Nullable Uint32 compatUint(final @Nullable Long value) {
380 return value == null ? null : Uint32.valueOf(value.longValue());
384 * Compatibility utility for converting a legacy {@link BigInteger} {@code uint64} value to its {@link Uint64}
387 * @param value Legacy value
388 * @return Converted value
389 * @throws IllegalArgumentException if the value does not fit an Uint64
390 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
391 * compatibility methods.
394 public static @Nullable Uint64 compatUint(final @Nullable BigInteger value) {
395 return value == null ? null : Uint64.valueOf(value);
399 * Utility method for checking whether a target object is a compatible DataObject.
401 * @param requiredClass Required DataObject class
402 * @param obj Object to check, may be null
403 * @return Object cast to required class, if its implemented class matches requirement, null otherwise
404 * @throws NullPointerException if {@code requiredClass} is null
406 public static <T extends DataObject> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
407 final @Nullable Object obj) {
408 return obj instanceof DataObject && requiredClass.equals(((DataObject) obj).implementedInterface())
409 ? requiredClass.cast(obj) : null;
413 * The constant '31' is the result of folding this code:
415 * final int prime = 31;
417 * result = result * prime + Objects.hashCode(obj);
420 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
422 * @param hash Wrapped object hash
423 * @return Wrapper object hash
425 private static int wrapHashCode(final int hash) {
426 return hash == 0 ? 31 : hash;