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 Objects.requireNonNull(value, "Supplied value may not be null")}.
59 * @param value Value itself
60 * @throws NullPointerException if value is null
62 public static void requireValue(@Nullable final Object value) {
63 requireNonNull(value, "Supplied value may not be null");
67 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
69 * @param helper Helper to append to
70 * @param name Name of the value
71 * @param value Value to append
72 * @throws NullPointerException if the name or helper is null
74 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
75 final @Nullable Object value) {
77 helper.add(name, value);
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 String name, final byte[] value) {
91 helper.add(name, Arrays.toString(value));
96 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
99 * @param patterns Patterns to compile
100 * @return Compiled patterns in an array
101 * @throws NullPointerException if the list or any of its elements is null
102 * @throws VerifyException if the list has fewer than two elements
104 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
105 final int size = patterns.size();
106 verify(size > 1, "Patterns has to have at least 2 elements");
107 final Pattern[] result = new Pattern[size];
108 for (int i = 0; i < size; ++i) {
109 result[i] = Pattern.compile(patterns.get(i));
115 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
116 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
118 * @param value Value to be checked.
119 * @param pattern Enforcement pattern
120 * @param regex Source regular expression, as defined in YANG model
121 * @throws IllegalArgumentException if the value does not match the pattern
122 * @throws NullPointerException if any of the arguments are null
124 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
125 if (!pattern.matcher(value).matches()) {
126 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
127 : "does not match required";
128 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
134 * Check whether a specified string value matches specified patterns. 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 patterns Enforcement patterns
139 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
140 * @throws IllegalArgumentException if the value does not match the pattern
141 * @throws NullPointerException if any of the arguments are null
142 * @throws VerifyException if the size of patterns and regexes does not match
144 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
145 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
146 for (int i = 0; i < patterns.length; ++i) {
147 checkPattern(value, patterns[i], regexes[i]);
152 * Throw an IllegalArgument exception describing a length violation.
154 * @param expected String describing expected lengths
155 * @param actual Actual observed object
156 * @throws IllegalArgumentException always
158 public static void throwInvalidLength(final String expected, final Object actual) {
159 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
163 * Throw an IllegalArgument exception describing a length violation.
165 * @param expected String describing expected lengths
166 * @param actual Actual observed byte array
167 * @throws IllegalArgumentException always
169 public static void throwInvalidLength(final String expected, final byte[] actual) {
170 throwInvalidLength(expected, Arrays.toString(actual));
174 * Throw an IllegalArgument exception describing a range violation.
176 * @param expected String describing expected ranges
177 * @param actual Actual observed object
178 * @throws IllegalArgumentException always
180 public static void throwInvalidRange(final String expected, final Object actual) {
181 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
185 * Throw an IllegalArgument exception describing a range violation.
187 * @param expected String describing expected ranges
188 * @param actual Actual observed value
189 * @throws IllegalArgumentException always
191 public static void throwInvalidRange(final String expected, final int actual) {
192 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
193 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
197 * Throw an IllegalArgument exception describing a range violation.
199 * @param expected String describing expected ranges
200 * @param actual Actual observed value
201 * @throws IllegalArgumentException always
203 public static void throwInvalidRange(final String expected, final long actual) {
204 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
205 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
209 * Throw an IllegalArgument exception describing a range violation.
211 * @param expected Objects describing expected ranges
212 * @param actual Actual observed byte array
213 * @throws IllegalArgumentException always
215 public static void throwInvalidRange(final Object[] expected, final Object actual) {
216 throwInvalidRange(Arrays.toString(expected), actual);
220 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
222 * @param expected String describing expected ranges
223 * @param actual Actual observed value
224 * @throws IllegalArgumentException always
226 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
227 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
232 * Check whether specified List is null and if so return an immutable list instead. This method supports
233 * non-null default getter methods.
235 * @param <T> list element type
236 * @param input input list, may be null
237 * @return Input list or an empty list.
239 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
240 return input != null ? input : ImmutableList.of();
244 * Check whether specified Map is null and if so return an immutable map instead. This method supports
245 * non-null default getter methods.
247 * @param <K> key type
248 * @param <V> value type
249 * @param input input map, may be null
250 * @return Input map or an empty map.
252 public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
253 return input != null ? input : ImmutableMap.of();
257 * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
258 * Builder/implementation list handover.
260 * @param <T> list element type
261 * @param input input list, may be null
262 * @return Input list or null.
264 public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
265 return input != null && input.isEmpty() ? null : input;
269 * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
270 * Builder/implementation list handover.
272 * @param <K> key type
273 * @param <V> value type
274 * @param input input map, may be null
275 * @return Input map or null.
277 public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
278 return input != null && input.isEmpty() ? null : input;
282 * Compatibility utility for turning a List of identifiable objects to an indexed map.
284 * @param <K> key type
285 * @param <V> identifiable type
286 * @param list legacy list
287 * @return Indexed map
288 * @throws IllegalArgumentException if the list contains entries with the same key
289 * @throws NullPointerException if the list contains a null entry
290 * @deprecated This method is a transitional helper used only in methods deprecated themselves.
292 // FIXME: MDSAL-540: remove this method
294 public static <K extends Identifier<V>, V extends Identifiable<K>> @Nullable Map<K, V> compatMap(
295 final @Nullable List<V> list) {
296 return list == null || list.isEmpty() ? null : Maps.uniqueIndex(list, Identifiable::key);
300 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
301 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
302 * for both non-present and present-with-null objects.
304 * @param obj Internal object to hash
305 * @return Wrapper object hash code
307 public static int wrapperHashCode(final @Nullable Object obj) {
308 return wrapHashCode(Objects.hashCode(obj));
312 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
313 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
314 * for both non-present and present-with-null objects.
316 * @param obj Internal object to hash
317 * @return Wrapper object hash code
319 public static int wrapperHashCode(final byte @Nullable[] obj) {
320 return wrapHashCode(Arrays.hashCode(obj));
324 * Compatibility utility for converting a legacy {@link Short} {@code uint8} value to its {@link Uint8}
327 * @param value Legacy value
328 * @return Converted value
329 * @throws IllegalArgumentException if the value does not fit an Uint8
330 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
331 * compatibility methods.
334 public static @Nullable Uint8 compatUint(final @Nullable Short value) {
335 return value == null ? null : Uint8.valueOf(value.shortValue());
339 * Compatibility utility for converting a legacy {@link Integer} {@code uint16} value to its {@link Uint16}
342 * @param value Legacy value
343 * @return Converted value
344 * @throws IllegalArgumentException if the value does not fit an Uint16
345 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
346 * compatibility methods.
349 public static @Nullable Uint16 compatUint(final @Nullable Integer value) {
350 return value == null ? null : Uint16.valueOf(value.intValue());
354 * Compatibility utility for converting a legacy {@link Long} {@code uint32} value to its {@link Uint32}
357 * @param value Legacy value
358 * @return Converted value
359 * @throws IllegalArgumentException if the value does not fit an Uint32
360 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
361 * compatibility methods.
364 public static @Nullable Uint32 compatUint(final @Nullable Long value) {
365 return value == null ? null : Uint32.valueOf(value.longValue());
369 * Compatibility utility for converting a legacy {@link BigInteger} {@code uint64} value to its {@link Uint64}
372 * @param value Legacy value
373 * @return Converted value
374 * @throws IllegalArgumentException if the value does not fit an Uint64
375 * @deprecated This method is provided for migration purposes only, do not use it outside of deprecated
376 * compatibility methods.
379 public static @Nullable Uint64 compatUint(final @Nullable BigInteger value) {
380 return value == null ? null : Uint64.valueOf(value);
384 * Utility method for checking whether a target object is a compatible DataObject.
386 * @param requiredClass Required DataObject class
387 * @param obj Object to check, may be null
388 * @return Object cast to required class, if its implemented class matches requirement, null otherwise
389 * @throws NullPointerException if {@code requiredClass} is null
391 public static <T extends DataObject> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
392 final @Nullable Object obj) {
393 return obj instanceof DataObject && requiredClass.equals(((DataObject) obj).implementedInterface())
394 ? requiredClass.cast(obj) : null;
398 * The constant '31' is the result of folding this code:
400 * final int prime = 31;
402 * result = result * prime + Objects.hashCode(obj);
405 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
407 * @param hash Wrapped object hash
408 * @return Wrapper object hash
410 private static int wrapHashCode(final int hash) {
411 return hash == 0 ? 31 : hash;