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.HexFormat;
20 import java.util.List;
22 import java.util.NoSuchElementException;
23 import java.util.Objects;
25 import java.util.regex.Pattern;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
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 public final class CodeHelpers {
35 private CodeHelpers() {
40 * Require that an a value-related expression is true.
42 * @param expression Expression to evaluate
43 * @param value Value being validated
44 * @param options Valid value options checked
45 * @throws IllegalArgumentException if expression is false
47 public static void validValue(final boolean expression, final Object value, final String options) {
48 checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
52 * Return value and check whether specified value is {@code null} and if so throws exception. This method supports
53 * require default getter methods.
55 * @param value Value itself
56 * @param name Name of the value
57 * @return Non-null value
58 * @throws NoSuchElementException if value is {@code null}
60 public static <T> @NonNull T require(final @Nullable T value, final @NonNull String name) {
62 throw new NoSuchElementException("Value of " + name + " is not present");
68 * A shortcut for {@code Preconditions.checkNotNull(value, "Key component \"%s\" must not be null", name)}.
70 * @param value Value itself
71 * @param name Name of the value
72 * @return Non-null value
73 * @throws NullPointerException if value is {@code null}
75 public static <T> @NonNull T requireKeyProp(final @Nullable T value, final @NonNull String name) {
77 throw new NullPointerException("Key component \"" + name + "\" may not be null");
83 * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
85 * @param value Value itself
86 * @throws NullPointerException if value is {@code null}
88 public static void requireValue(final @Nullable Object value) {
89 requireNonNull(value, "Supplied value may not be null");
93 * Append a {@code bits} individual value. If the value is {@code false}, this method does nothing.
95 * @param helper Helper to append to
96 * @param name Name of the bit
97 * @param value Value to append
98 * @throws NullPointerException if any argument is {@code null}
100 public static void appendBit(final ToStringHelper helper, final @NonNull String name, final boolean value) {
102 helper.addValue(name);
107 * Append a named value to a ToStringHelper. If the value is {@code null}, this method does nothing.
109 * @param helper Helper to append to
110 * @param name Name of the value
111 * @param value Value to append
112 * @throws NullPointerException if the name or helper is {@code null}
114 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
115 final @Nullable Object value) {
117 helper.add(name, value);
122 * Append a named value to a ToStringHelper. If the value is {@code null}, this method does nothing.
124 * @param helper Helper to append to
125 * @param name Name of the value
126 * @param value Value to append
127 * @throws NullPointerException if the name or helper is {@code null}
129 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
131 helper.add(name, HexFormat.of().formatHex(value));
136 * Append augmentation map of an Augmentable to a ToStringHelper. If augmentations are {@code null} or empty, this
137 * method does nothing.
139 * @param helper Helper to append to
140 * @param name Name of the augmentation value
141 * @param augmentable Augmentable object to
142 * @throws NullPointerException if any argument is {@code null}
144 public static void appendAugmentations(final ToStringHelper helper, final String name,
145 final Augmentable<?> augmentable) {
146 final var augments = augmentable.augmentations();
147 if (!augments.isEmpty()) {
148 helper.add(name, augments.values());
153 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
156 * @param patterns Patterns to compile
157 * @return Compiled patterns in an array
158 * @throws NullPointerException if the list or any of its elements is {@code null}
159 * @throws VerifyException if the list has fewer than two elements
161 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
162 final int size = patterns.size();
163 verify(size > 1, "Patterns has to have at least 2 elements");
164 final Pattern[] result = new Pattern[size];
165 for (int i = 0; i < size; ++i) {
166 result[i] = Pattern.compile(patterns.get(i));
172 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
173 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
175 * @param value Value to be checked.
176 * @param pattern Enforcement pattern
177 * @param regex Source regular expression, as defined in YANG model
178 * @throws IllegalArgumentException if the value does not match the pattern
179 * @throws NullPointerException if any of the arguments is {@code null}
181 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
182 if (!pattern.matcher(value).matches()) {
183 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
184 : "does not match required";
185 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
191 * Check whether a specified string value matches specified patterns. This method handles the distinction between
192 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
194 * @param value Value to be checked.
195 * @param patterns Enforcement patterns
196 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
197 * @throws IllegalArgumentException if the value does not match the pattern
198 * @throws NullPointerException if any of the arguments is {@code null}
199 * @throws VerifyException if the size of patterns and regexes does not match
201 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
202 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
203 for (int i = 0; i < patterns.length; ++i) {
204 checkPattern(value, patterns[i], regexes[i]);
209 * Throw an IllegalArgument exception describing a length violation.
211 * @param expected String describing expected lengths
212 * @param actual Actual observed object
213 * @throws IllegalArgumentException always
215 public static void throwInvalidLength(final String expected, final Object actual) {
216 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
220 * Throw an IllegalArgument exception describing a length violation.
222 * @param expected String describing expected lengths
223 * @param actual Actual observed byte array
224 * @throws IllegalArgumentException always
226 public static void throwInvalidLength(final String expected, final byte[] actual) {
227 throwInvalidLength(expected, HexFormat.of().formatHex(actual));
231 * Throw an IllegalArgument exception describing a range violation.
233 * @param expected String describing expected ranges
234 * @param actual Actual observed object
235 * @throws IllegalArgumentException always
237 public static void throwInvalidRange(final String expected, final Object actual) {
238 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
242 * Throw an IllegalArgument exception describing a range violation.
244 * @param expected String describing expected ranges
245 * @param actual Actual observed value
246 * @throws IllegalArgumentException always
248 public static void throwInvalidRange(final String expected, final int actual) {
249 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
250 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
254 * Throw an IllegalArgument exception describing a range violation.
256 * @param expected String describing expected ranges
257 * @param actual Actual observed value
258 * @throws IllegalArgumentException always
260 public static void throwInvalidRange(final String expected, final long actual) {
261 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
262 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
266 * Throw an IllegalArgument exception describing a range violation.
268 * @param expected Objects describing expected ranges
269 * @param actual Actual observed byte array
270 * @throws IllegalArgumentException always
272 public static void throwInvalidRange(final Object[] expected, final Object actual) {
273 throwInvalidRange(Arrays.toString(expected), actual);
277 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
279 * @param expected String describing expected ranges
280 * @param actual Actual observed value
281 * @throws IllegalArgumentException always
283 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
284 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
289 * Check whether specified List is {@code null} and if so return an immutable list instead. This method supports
290 * non-null default getter methods.
292 * @param <T> list element type
293 * @param input input list, may be {@code null}
294 * @return Input list or an empty list.
296 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
297 return input != null ? input : ImmutableList.of();
301 * Check whether specified Map is {@code null} and if so return an immutable map instead. This method supports
302 * non-null default getter methods.
304 * @param <K> key type
305 * @param <V> value type
306 * @param input input map, may be {@code null}
307 * @return Input map or an empty map.
309 public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
310 return input != null ? input : ImmutableMap.of();
314 * Check whether specified List is empty and if so return {@code null}, otherwise return input list. This method
315 * supports Builder/implementation list handover.
317 * @param <T> list element type
318 * @param input input list, may be {@code null}
319 * @return Input list or {@code null}.
321 public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
322 return input != null && input.isEmpty() ? null : input;
326 * Check whether specified Map is empty and if so return {@code null}, otherwise return input map. This method
327 * supports Builder/implementation list handover.
329 * @param <K> key type
330 * @param <V> value type
331 * @param input input map, may be {@code null}
332 * @return Input map or {@code null}.
334 public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
335 return input != null && input.isEmpty() ? null : input;
339 * Return hash code of a single-property wrapper class. Since the wrapper is not {@code null}, we really want to
340 * discern this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with
341 * {@code 0} for both non-present and present-with-null objects.
343 * @param obj Internal object to hash
344 * @return Wrapper object hash code
346 public static int wrapperHashCode(final @Nullable Object obj) {
347 return wrapHashCode(Objects.hashCode(obj));
351 * Return hash code of a single-property wrapper class. Since the wrapper is not {@code null}, we really want to
352 * discern this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with
353 * {@code 0} for both non-present and present-with-null objects.
355 * @param obj Internal object to hash
356 * @return Wrapper object hash code
358 public static int wrapperHashCode(final byte @Nullable[] obj) {
359 return wrapHashCode(Arrays.hashCode(obj));
363 * The constant '31' is the result of folding this code:
366 * final int prime = 31;
368 * result = result * prime + Objects.hashCode(obj);
372 * when hashCode is returned as 0, such as due to obj being {@code null} or its hashCode being 0.
374 * @param hash Wrapped object hash
375 * @return Wrapper object hash
377 private static int wrapHashCode(final int hash) {
378 return hash == 0 ? 31 : hash;
382 * Check that the specified {@link EnumTypeObject} object is not {@code null}. This method is meant to be used with
383 * {@code ofName(String)} and {@code ofValue(int)} static factory methods.
385 * @param obj enumeration object, possibly {@code null}
386 * @param name User-supplied enumeration name
387 * @return Enumeration object
388 * @throws IllegalArgumentException if {@code obj} is {@code null}
390 public static <T extends EnumTypeObject> @NonNull T checkEnum(final @Nullable T obj, final String name) {
392 throw new IllegalArgumentException("\"" + name + "\" is not a valid name");
398 * Check that the specified {@link EnumTypeObject} object is not {@code null}. This method is meant to be used with
399 * {@code ofName(String)} and {@code ofValue(int)} static factory methods.
401 * @param obj enumeration object, possibly {@code null}
402 * @param value User-supplied enumeration value
403 * @return Enumeration object
404 * @throws IllegalArgumentException if {@code obj} is {@code null}
406 public static <T extends EnumTypeObject> @NonNull T checkEnum(final @Nullable T obj, final int value) {
408 throw new IllegalArgumentException(value + " is not a valid value");
414 * Utility method for checking whether a target object is a compatible {@link BindingContract}.
416 * @param requiredClass Required BindingContract class
417 * @param obj Object to check, may be {@code null}
418 * @return Object cast to required class, if its implemented class matches requirement, {@code null} otherwise
419 * @throws NullPointerException if {@code requiredClass} is {@code null}
421 public static <T extends BindingContract<?>> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
422 final @Nullable Object obj) {
423 return obj instanceof BindingContract<?> contract && requiredClass.equals(contract.implementedInterface())
424 ? requiredClass.cast(obj) : null;
428 * Utility method for checking whether a target object is compatible.
430 * @param requiredClass Required class
431 * @param fieldName name of the field being filled
432 * @param obj Object to check, may be {@code null}
433 * @return Object cast to required class, if its class matches requirement, or {@code null}
434 * @throws IllegalArgumentException if {@code obj} is not an instance of {@code requiredClass}
435 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is {@code null}
437 public static <T> @Nullable T checkFieldCast(final @NonNull Class<T> requiredClass, final @NonNull String fieldName,
438 final @Nullable Object obj) {
440 return requiredClass.cast(obj);
441 } catch (ClassCastException e) {
442 throw new IllegalArgumentException("Invalid input value for property \"" + fieldName + "\"", e);
447 * Utility method for checking whether the items of target list is compatible.
449 * @param requiredClass Required item class
450 * @param fieldName name of the field being filled
451 * @param list List, which items should be checked
452 * @return Type-checked List
453 * @throws IllegalArgumentException if a list item is not instance of {@code requiredClass}
454 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is {@code null}
456 @SuppressWarnings("unchecked")
457 public static <T> @Nullable List<T> checkListFieldCast(final @NonNull Class<T> requiredClass,
458 final @NonNull String fieldName, final @Nullable List<?> list) {
459 DoNotLeakSpotbugs.checkCollectionField(requiredClass, fieldName, list);
460 return (List<T>) list;
464 * Utility method for checking whether the items of target set is compatible.
466 * @param requiredClass Required item class
467 * @param fieldName name of the field being filled
468 * @param set Set, which items should be checked
469 * @return Type-checked Set
470 * @throws IllegalArgumentException if a set item is not instance of {@code requiredItemClass}
471 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is {@code null}
473 @SuppressWarnings("unchecked")
474 public static <T> @Nullable Set<T> checkSetFieldCast(final @NonNull Class<T> requiredClass,
475 final @NonNull String fieldName, final @Nullable Set<?> set) {
476 DoNotLeakSpotbugs.checkCollectionField(requiredClass, fieldName, set);