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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.HexFormat;
22 import java.util.List;
24 import java.util.NoSuchElementException;
25 import java.util.Objects;
27 import java.util.regex.Pattern;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.eclipse.jdt.annotation.Nullable;
32 * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
33 * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
34 * general API stability requirements of the Binding Specification.
36 * @author Robert Varga
38 public final class CodeHelpers {
39 private CodeHelpers() {
44 * Require that an a value-related expression is true.
46 * @param expression Expression to evaluate
47 * @param value Value being validated
48 * @param options Valid value options checked
49 * @throws IllegalArgumentException if expression is false
51 public static void validValue(final boolean expression, final Object value, final String options) {
52 checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
56 * Return value and check whether specified value is null and if so throws exception. This method supports
57 * require default getter methods.
59 * @param value Value itself
60 * @param name Name of the value
61 * @return Non-null value
62 * @throws NoSuchElementException if value is null
64 public static <T> @NonNull T require(final @Nullable T value, final @NonNull String name) {
66 throw new NoSuchElementException("Value of " + name + " is not present");
72 * A shortcut for {@code Preconditions.checkNotNull(value, "Key component \"%s\" must not be null", name)}.
74 * @param value Value itself
75 * @param name Name of the value
76 * @return Non-null value
77 * @throws NullPointerException if value is null
79 public static <T> @NonNull T requireKeyProp(final @Nullable T value, final @NonNull String name) {
81 throw new NullPointerException("Key component \"" + name + "\" may not be null");
87 * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
89 * @param value Value itself
90 * @throws NullPointerException if value is null
92 public static void requireValue(final @Nullable Object value) {
93 requireNonNull(value, "Supplied value may not be null");
97 * Append a {@code bits} individual value. If the value is {@code false}, this method does nothing.
99 * @param helper Helper to append to
100 * @param name Name of the bit
101 * @param value Value to append
102 * @throws NullPointerException if any argument is {@code null}
104 public static void appendBit(final ToStringHelper helper, final @NonNull String name, final boolean value) {
106 helper.addValue(name);
111 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
113 * @param helper Helper to append to
114 * @param name Name of the value
115 * @param value Value to append
116 * @throws NullPointerException if the name or helper is null
118 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
119 final @Nullable Object value) {
121 helper.add(name, value);
126 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
128 * @param helper Helper to append to
129 * @param name Name of the value
130 * @param value Value to append
131 * @throws NullPointerException if the name or helper is null
133 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
135 helper.add(name, HexFormat.of().formatHex(value));
140 * Append augmentation map of an Augmentable to a ToStringHelper. If augmentations are null or empt, this method
143 * @param helper Helper to append to
144 * @param name Name of the augmentation value
145 * @param augmentable Augmentable object to
146 * @throws NullPointerException if any argument is null
148 public static void appendAugmentations(final ToStringHelper helper, final String name,
149 final Augmentable<?> augmentable) {
150 final var augments = augmentable.augmentations();
151 if (!augments.isEmpty()) {
152 helper.add(name, augments.values());
157 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
160 * @param patterns Patterns to compile
161 * @return Compiled patterns in an array
162 * @throws NullPointerException if the list or any of its elements is null
163 * @throws VerifyException if the list has fewer than two elements
165 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
166 final int size = patterns.size();
167 verify(size > 1, "Patterns has to have at least 2 elements");
168 final Pattern[] result = new Pattern[size];
169 for (int i = 0; i < size; ++i) {
170 result[i] = Pattern.compile(patterns.get(i));
176 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
177 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
179 * @param value Value to be checked.
180 * @param pattern Enforcement pattern
181 * @param regex Source regular expression, as defined in YANG model
182 * @throws IllegalArgumentException if the value does not match the pattern
183 * @throws NullPointerException if any of the arguments are null
185 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
186 if (!pattern.matcher(value).matches()) {
187 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
188 : "does not match required";
189 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
195 * Check whether a specified string value matches specified patterns. This method handles the distinction between
196 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
198 * @param value Value to be checked.
199 * @param patterns Enforcement patterns
200 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
201 * @throws IllegalArgumentException if the value does not match the pattern
202 * @throws NullPointerException if any of the arguments are null
203 * @throws VerifyException if the size of patterns and regexes does not match
205 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
206 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
207 for (int i = 0; i < patterns.length; ++i) {
208 checkPattern(value, patterns[i], regexes[i]);
213 * Throw an IllegalArgument exception describing a length violation.
215 * @param expected String describing expected lengths
216 * @param actual Actual observed object
217 * @throws IllegalArgumentException always
219 public static void throwInvalidLength(final String expected, final Object actual) {
220 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
224 * Throw an IllegalArgument exception describing a length violation.
226 * @param expected String describing expected lengths
227 * @param actual Actual observed byte array
228 * @throws IllegalArgumentException always
230 public static void throwInvalidLength(final String expected, final byte[] actual) {
231 throwInvalidLength(expected, HexFormat.of().formatHex(actual));
235 * Throw an IllegalArgument exception describing a range violation.
237 * @param expected String describing expected ranges
238 * @param actual Actual observed object
239 * @throws IllegalArgumentException always
241 public static void throwInvalidRange(final String expected, final Object actual) {
242 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
246 * Throw an IllegalArgument exception describing a range violation.
248 * @param expected String describing expected ranges
249 * @param actual Actual observed value
250 * @throws IllegalArgumentException always
252 public static void throwInvalidRange(final String expected, final int actual) {
253 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
254 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
258 * Throw an IllegalArgument exception describing a range violation.
260 * @param expected String describing expected ranges
261 * @param actual Actual observed value
262 * @throws IllegalArgumentException always
264 public static void throwInvalidRange(final String expected, final long actual) {
265 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
266 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
270 * Throw an IllegalArgument exception describing a range violation.
272 * @param expected Objects describing expected ranges
273 * @param actual Actual observed byte array
274 * @throws IllegalArgumentException always
276 public static void throwInvalidRange(final Object[] expected, final Object actual) {
277 throwInvalidRange(Arrays.toString(expected), actual);
281 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
283 * @param expected String describing expected ranges
284 * @param actual Actual observed value
285 * @throws IllegalArgumentException always
287 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
288 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
293 * Check whether specified List is null and if so return an immutable list instead. This method supports
294 * non-null default getter methods.
296 * @param <T> list element type
297 * @param input input list, may be null
298 * @return Input list or an empty list.
300 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
301 return input != null ? input : ImmutableList.of();
305 * Check whether specified Map is null and if so return an immutable map instead. This method supports
306 * non-null default getter methods.
308 * @param <K> key type
309 * @param <V> value type
310 * @param input input map, may be null
311 * @return Input map or an empty map.
313 public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
314 return input != null ? input : ImmutableMap.of();
318 * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
319 * Builder/implementation list handover.
321 * @param <T> list element type
322 * @param input input list, may be null
323 * @return Input list or null.
325 public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
326 return input != null && input.isEmpty() ? null : input;
330 * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
331 * Builder/implementation list handover.
333 * @param <K> key type
334 * @param <V> value type
335 * @param input input map, may be null
336 * @return Input map or null.
338 public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
339 return input != null && input.isEmpty() ? null : input;
343 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
344 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
345 * for both non-present and present-with-null objects.
347 * @param obj Internal object to hash
348 * @return Wrapper object hash code
350 public static int wrapperHashCode(final @Nullable Object obj) {
351 return wrapHashCode(Objects.hashCode(obj));
355 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
356 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
357 * for both non-present and present-with-null objects.
359 * @param obj Internal object to hash
360 * @return Wrapper object hash code
362 public static int wrapperHashCode(final byte @Nullable[] obj) {
363 return wrapHashCode(Arrays.hashCode(obj));
367 * The constant '31' is the result of folding this code:
370 * final int prime = 31;
372 * result = result * prime + Objects.hashCode(obj);
376 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
378 * @param hash Wrapped object hash
379 * @return Wrapper object hash
381 private static int wrapHashCode(final int hash) {
382 return hash == 0 ? 31 : hash;
386 * Check that the specified {@link EnumTypeObject} object is not {@code null}. This method is meant to be used with
387 * {@code ofName(String)} and {@code ofValue(int)} static factory methods.
389 * @param obj enumeration object, possibly null
390 * @param name User-supplied enumeration name
391 * @return Enumeration object
392 * @throws IllegalArgumentException if {@code obj} is null
394 public static <T extends EnumTypeObject> @NonNull T checkEnum(final @Nullable T obj, final String name) {
396 throw new IllegalArgumentException("\"" + name + "\" is not a valid name");
402 * Check that the specified {@link EnumTypeObject} object is not {@code null}. This method is meant to be used with
403 * {@code ofName(String)} and {@code ofValue(int)} static factory methods.
405 * @param obj enumeration object, possibly null
406 * @param value User-supplied enumeration value
407 * @return Enumeration object
408 * @throws IllegalArgumentException if {@code obj} is null
410 public static <T extends EnumTypeObject> @NonNull T checkEnum(final @Nullable T obj, final int value) {
412 throw new IllegalArgumentException(value + " is not a valid value");
418 * Utility method for checking whether a target object is a compatible {@link BindingContract}.
420 * @param requiredClass Required BindingContract class
421 * @param obj Object to check, may be null
422 * @return Object cast to required class, if its implemented class matches requirement, null otherwise
423 * @throws NullPointerException if {@code requiredClass} is null
425 public static <T extends BindingContract<?>> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
426 final @Nullable Object obj) {
427 return obj instanceof BindingContract<?> contract && requiredClass.equals(contract.implementedInterface())
428 ? requiredClass.cast(obj) : null;
432 * Utility method for checking whether a target object is compatible.
434 * @param requiredClass Required class
435 * @param fieldName name of the field being filled
436 * @param obj Object to check, may be null
437 * @return Object cast to required class, if its class matches requirement, or null
438 * @throws IllegalArgumentException if {@code obj} is not an instance of {@code requiredClass}
439 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
441 public static <T> @Nullable T checkFieldCast(final @NonNull Class<T> requiredClass, final @NonNull String fieldName,
442 final @Nullable Object obj) {
444 return requiredClass.cast(obj);
445 } catch (ClassCastException e) {
446 throw new IllegalArgumentException("Invalid input value for property \"" + fieldName + "\"", e);
451 * Utility method for checking whether the items of target list is compatible.
453 * @param requiredClass Required item class
454 * @param fieldName name of the field being filled
455 * @param list List, which items should be checked
456 * @return Type-checked List
457 * @throws IllegalArgumentException if a list item is not instance of {@code requiredClass}
458 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
460 @SuppressWarnings("unchecked")
461 public static <T> @Nullable List<T> checkListFieldCast(final @NonNull Class<?> requiredClass,
462 final @NonNull String fieldName, final @Nullable List<?> list) {
463 checkCollectionField(requiredClass, fieldName, list);
464 return (List<T>) list;
468 * Utility method for checking whether the items of target set is compatible.
470 * @param requiredClass Required item class
471 * @param fieldName name of the field being filled
472 * @param set Set, which items should be checked
473 * @return Type-checked Set
474 * @throws IllegalArgumentException if a set item is not instance of {@code requiredItemClass}
475 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
477 @SuppressWarnings("unchecked")
478 public static <T> @Nullable Set<T> checkSetFieldCast(final @NonNull Class<?> requiredClass,
479 final @NonNull String fieldName, final @Nullable Set<?> set) {
480 checkCollectionField(requiredClass, fieldName, set);
484 @SuppressFBWarnings(value = "DCN_NULLPOINTER_EXCEPTION",
485 justification = "Internal NPE->IAE conversion")
486 private static void checkCollectionField(final @NonNull Class<?> requiredClass,
487 final @NonNull String fieldName, final @Nullable Collection<?> collection) {
488 if (collection != null) {
490 collection.forEach(item -> requiredClass.cast(requireNonNull(item)));
491 } catch (ClassCastException | NullPointerException e) {
492 throw new IllegalArgumentException("Invalid input item for property \"" + requireNonNull(fieldName)