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.Collection;
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 * @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 * Return value and check whether specified value is null and if so throws exception. This method supports
55 * require default getter methods.
57 * @param value Value itself
58 * @param name Name of the value
59 * @return Non-null value
60 * @throws NoSuchElementException if value is null
62 public static <T> @NonNull T require(final @Nullable T value, final @NonNull String name) {
64 throw new NoSuchElementException("Value of " + name + " is not present");
70 * A shortcut for {@code Preconditions.checkNotNull(value, "Key component \"%s\" must not be null", name)}.
72 * @param value Value itself
73 * @param name Name of the value
74 * @return Non-null value
75 * @throws NullPointerException if value is null
77 public static <T> @NonNull T requireKeyProp(final @Nullable T value, final @NonNull String name) {
79 throw new NullPointerException("Key component \"" + name + "\" may not be null");
85 * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
87 * @param value Value itself
88 * @throws NullPointerException if value is null
90 public static void requireValue(final @Nullable Object value) {
91 requireNonNull(value, "Supplied value may not be null");
95 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
97 * @param helper Helper to append to
98 * @param name Name of the value
99 * @param value Value to append
100 * @throws NullPointerException if the name or helper is null
102 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
103 final @Nullable Object value) {
105 helper.add(name, value);
110 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
112 * @param helper Helper to append to
113 * @param name Name of the value
114 * @param value Value to append
115 * @throws NullPointerException if the name or helper is null
117 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
119 // FIXME: MDSAL-692: use hex-encoding instead
120 helper.add(name, Arrays.toString(value));
125 * Append augmentation map of an Augmentable to a ToStringHelper. If augmentations are null or empt, this method
128 * @param helper Helper to append to
129 * @param name Name of the augmentation value
130 * @param augmentable Augmentable object to
131 * @throws NullPointerException if any argument is null
133 public static void appendAugmentations(final ToStringHelper helper, final String name,
134 final Augmentable<?> augmentable) {
135 final var augments = augmentable.augmentations();
136 if (!augments.isEmpty()) {
137 helper.add(name, augments.values());
142 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
145 * @param patterns Patterns to compile
146 * @return Compiled patterns in an array
147 * @throws NullPointerException if the list or any of its elements is null
148 * @throws VerifyException if the list has fewer than two elements
150 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
151 final int size = patterns.size();
152 verify(size > 1, "Patterns has to have at least 2 elements");
153 final Pattern[] result = new Pattern[size];
154 for (int i = 0; i < size; ++i) {
155 result[i] = Pattern.compile(patterns.get(i));
161 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
162 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
164 * @param value Value to be checked.
165 * @param pattern Enforcement pattern
166 * @param regex Source regular expression, as defined in YANG model
167 * @throws IllegalArgumentException if the value does not match the pattern
168 * @throws NullPointerException if any of the arguments are null
170 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
171 if (!pattern.matcher(value).matches()) {
172 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
173 : "does not match required";
174 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
180 * Check whether a specified string value matches specified patterns. This method handles the distinction between
181 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
183 * @param value Value to be checked.
184 * @param patterns Enforcement patterns
185 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
186 * @throws IllegalArgumentException if the value does not match the pattern
187 * @throws NullPointerException if any of the arguments are null
188 * @throws VerifyException if the size of patterns and regexes does not match
190 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
191 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
192 for (int i = 0; i < patterns.length; ++i) {
193 checkPattern(value, patterns[i], regexes[i]);
198 * Throw an IllegalArgument exception describing a length violation.
200 * @param expected String describing expected lengths
201 * @param actual Actual observed object
202 * @throws IllegalArgumentException always
204 public static void throwInvalidLength(final String expected, final Object actual) {
205 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
209 * Throw an IllegalArgument exception describing a length violation.
211 * @param expected String describing expected lengths
212 * @param actual Actual observed byte array
213 * @throws IllegalArgumentException always
215 public static void throwInvalidLength(final String expected, final byte[] actual) {
216 // FIXME: MDSAL-692: use hex-encoding instead
217 throwInvalidLength(expected, Arrays.toString(actual));
221 * Throw an IllegalArgument exception describing a range violation.
223 * @param expected String describing expected ranges
224 * @param actual Actual observed object
225 * @throws IllegalArgumentException always
227 public static void throwInvalidRange(final String expected, final Object actual) {
228 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
232 * Throw an IllegalArgument exception describing a range violation.
234 * @param expected String describing expected ranges
235 * @param actual Actual observed value
236 * @throws IllegalArgumentException always
238 public static void throwInvalidRange(final String expected, final int actual) {
239 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
240 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
244 * Throw an IllegalArgument exception describing a range violation.
246 * @param expected String describing expected ranges
247 * @param actual Actual observed value
248 * @throws IllegalArgumentException always
250 public static void throwInvalidRange(final String expected, final long actual) {
251 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
252 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
256 * Throw an IllegalArgument exception describing a range violation.
258 * @param expected Objects describing expected ranges
259 * @param actual Actual observed byte array
260 * @throws IllegalArgumentException always
262 public static void throwInvalidRange(final Object[] expected, final Object actual) {
263 throwInvalidRange(Arrays.toString(expected), actual);
267 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
269 * @param expected String describing expected ranges
270 * @param actual Actual observed value
271 * @throws IllegalArgumentException always
273 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
274 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
279 * Check whether specified List is null and if so return an immutable list instead. This method supports
280 * non-null default getter methods.
282 * @param <T> list element type
283 * @param input input list, may be null
284 * @return Input list or an empty list.
286 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
287 return input != null ? input : ImmutableList.of();
291 * Check whether specified Map is null and if so return an immutable map instead. This method supports
292 * non-null default getter methods.
294 * @param <K> key type
295 * @param <V> value type
296 * @param input input map, may be null
297 * @return Input map or an empty map.
299 public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
300 return input != null ? input : ImmutableMap.of();
304 * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
305 * Builder/implementation list handover.
307 * @param <T> list element type
308 * @param input input list, may be null
309 * @return Input list or null.
311 public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
312 return input != null && input.isEmpty() ? null : input;
316 * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
317 * Builder/implementation list handover.
319 * @param <K> key type
320 * @param <V> value type
321 * @param input input map, may be null
322 * @return Input map or null.
324 public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
325 return input != null && input.isEmpty() ? null : input;
329 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
330 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
331 * for both non-present and present-with-null objects.
333 * @param obj Internal object to hash
334 * @return Wrapper object hash code
336 public static int wrapperHashCode(final @Nullable Object obj) {
337 return wrapHashCode(Objects.hashCode(obj));
341 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
342 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
343 * for both non-present and present-with-null objects.
345 * @param obj Internal object to hash
346 * @return Wrapper object hash code
348 public static int wrapperHashCode(final byte @Nullable[] obj) {
349 return wrapHashCode(Arrays.hashCode(obj));
353 * Utility method for checking whether a target object is a compatible DataObject.
355 * @param requiredClass Required DataObject class
356 * @param obj Object to check, may be null
357 * @return Object cast to required class, if its implemented class matches requirement, null otherwise
358 * @throws NullPointerException if {@code requiredClass} is null
360 public static <T extends DataObject> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
361 final @Nullable Object obj) {
362 return obj instanceof DataObject && requiredClass.equals(((DataObject) obj).implementedInterface())
363 ? requiredClass.cast(obj) : null;
367 * Utility method for checking whether a target object is compatible.
369 * @param requiredClass Required class
370 * @param fieldName name of the field being filled
371 * @param obj Object to check, may be null
372 * @return Object cast to required class, if its class matches requirement, or null
373 * @throws IllegalArgumentException if {@code obj} is not an instance of {@code requiredClass}
374 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
376 public static <T> @Nullable T checkFieldCast(final @NonNull Class<T> requiredClass, final @NonNull String fieldName,
377 final @Nullable Object obj) {
379 return requiredClass.cast(obj);
380 } catch (ClassCastException e) {
381 throw new IllegalArgumentException("Invalid input value for property \"" + fieldName + "\"", e);
386 * Utility method for checking whether the items of target list is compatible.
388 * @param requiredClass Required item class
389 * @param fieldName name of the field being filled
390 * @param list List, which items should be checked
391 * @return Type-checked List
392 * @throws IllegalArgumentException if a list item is not instance of {@code requiredItemClass}
393 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
395 @SuppressWarnings("unchecked")
396 public static <T> @Nullable List<T> checkListFieldCast(final @NonNull Class<?> requiredClass,
397 final @NonNull String fieldName, final @Nullable List<?> list) {
398 checkCollectionField(requiredClass, fieldName, list);
399 return (List<T>) list;
403 * Utility method for checking whether the items of target list is compatible.
405 * @param requiredClass Required item class
406 * @param fieldName name of the field being filled
407 * @param set Set, which items should be checked
408 * @return Type-checked Set
409 * @throws IllegalArgumentException if a set item is not instance of {@code requiredItemClass}
410 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
412 @SuppressWarnings("unchecked")
413 public static <T> @Nullable Set<T> checkSetFieldCast(final @NonNull Class<?> requiredClass,
414 final @NonNull String fieldName, final @Nullable Set<?> set) {
415 checkCollectionField(requiredClass, fieldName, set);
419 private static void checkCollectionField(final @NonNull Class<?> requiredClass,
420 final @NonNull String fieldName, final @Nullable Collection<?> collection) {
421 if (collection != null) {
423 collection.forEach(item -> requiredClass.cast(requireNonNull(item)));
424 } catch (ClassCastException | NullPointerException e) {
425 throw new IllegalArgumentException("Invalid input list item for property \"" + requireNonNull(fieldName)
432 * The constant '31' is the result of folding this code:
435 * final int prime = 31;
437 * result = result * prime + Objects.hashCode(obj);
441 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
443 * @param hash Wrapped object hash
444 * @return Wrapper object hash
446 private static int wrapHashCode(final int hash) {
447 return hash == 0 ? 31 : hash;