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.List;
21 import java.util.NoSuchElementException;
22 import java.util.Objects;
23 import java.util.regex.Pattern;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.eclipse.jdt.annotation.Nullable;
28 * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
29 * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
30 * general API stability requirements of the Binding Specification.
32 * @author Robert Varga
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 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 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 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 null
88 public static void requireValue(final @Nullable Object value) {
89 requireNonNull(value, "Supplied value may not be null");
93 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
95 * @param helper Helper to append to
96 * @param name Name of the value
97 * @param value Value to append
98 * @throws NullPointerException if the name or helper is null
100 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
101 final @Nullable Object value) {
103 helper.add(name, value);
108 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
110 * @param helper Helper to append to
111 * @param name Name of the value
112 * @param value Value to append
113 * @throws NullPointerException if the name or helper is null
115 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
117 helper.add(name, Arrays.toString(value));
122 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
125 * @param patterns Patterns to compile
126 * @return Compiled patterns in an array
127 * @throws NullPointerException if the list or any of its elements is null
128 * @throws VerifyException if the list has fewer than two elements
130 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
131 final int size = patterns.size();
132 verify(size > 1, "Patterns has to have at least 2 elements");
133 final Pattern[] result = new Pattern[size];
134 for (int i = 0; i < size; ++i) {
135 result[i] = Pattern.compile(patterns.get(i));
141 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
142 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
144 * @param value Value to be checked.
145 * @param pattern Enforcement pattern
146 * @param regex Source regular expression, as defined in YANG model
147 * @throws IllegalArgumentException if the value does not match the pattern
148 * @throws NullPointerException if any of the arguments are null
150 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
151 if (!pattern.matcher(value).matches()) {
152 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
153 : "does not match required";
154 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
160 * Check whether a specified string value matches specified patterns. This method handles the distinction between
161 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
163 * @param value Value to be checked.
164 * @param patterns Enforcement patterns
165 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
166 * @throws IllegalArgumentException if the value does not match the pattern
167 * @throws NullPointerException if any of the arguments are null
168 * @throws VerifyException if the size of patterns and regexes does not match
170 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
171 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
172 for (int i = 0; i < patterns.length; ++i) {
173 checkPattern(value, patterns[i], regexes[i]);
178 * Throw an IllegalArgument exception describing a length violation.
180 * @param expected String describing expected lengths
181 * @param actual Actual observed object
182 * @throws IllegalArgumentException always
184 public static void throwInvalidLength(final String expected, final Object actual) {
185 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
189 * Throw an IllegalArgument exception describing a length violation.
191 * @param expected String describing expected lengths
192 * @param actual Actual observed byte array
193 * @throws IllegalArgumentException always
195 public static void throwInvalidLength(final String expected, final byte[] actual) {
196 throwInvalidLength(expected, Arrays.toString(actual));
200 * Throw an IllegalArgument exception describing a range violation.
202 * @param expected String describing expected ranges
203 * @param actual Actual observed object
204 * @throws IllegalArgumentException always
206 public static void throwInvalidRange(final String expected, final Object actual) {
207 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
211 * Throw an IllegalArgument exception describing a range violation.
213 * @param expected String describing expected ranges
214 * @param actual Actual observed value
215 * @throws IllegalArgumentException always
217 public static void throwInvalidRange(final String expected, final int actual) {
218 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
219 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
223 * Throw an IllegalArgument exception describing a range violation.
225 * @param expected String describing expected ranges
226 * @param actual Actual observed value
227 * @throws IllegalArgumentException always
229 public static void throwInvalidRange(final String expected, final long actual) {
230 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
231 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
235 * Throw an IllegalArgument exception describing a range violation.
237 * @param expected Objects describing expected ranges
238 * @param actual Actual observed byte array
239 * @throws IllegalArgumentException always
241 public static void throwInvalidRange(final Object[] expected, final Object actual) {
242 throwInvalidRange(Arrays.toString(expected), actual);
246 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
248 * @param expected String describing expected ranges
249 * @param actual Actual observed value
250 * @throws IllegalArgumentException always
252 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
253 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
258 * Check whether specified List is null and if so return an immutable list instead. This method supports
259 * non-null default getter methods.
261 * @param <T> list element type
262 * @param input input list, may be null
263 * @return Input list or an empty list.
265 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
266 return input != null ? input : ImmutableList.of();
270 * Check whether specified Map is null and if so return an immutable map instead. This method supports
271 * non-null default getter methods.
273 * @param <K> key type
274 * @param <V> value type
275 * @param input input map, may be null
276 * @return Input map or an empty map.
278 public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
279 return input != null ? input : ImmutableMap.of();
283 * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
284 * Builder/implementation list handover.
286 * @param <T> list element type
287 * @param input input list, may be null
288 * @return Input list or null.
290 public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
291 return input != null && input.isEmpty() ? null : input;
295 * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
296 * Builder/implementation list handover.
298 * @param <K> key type
299 * @param <V> value type
300 * @param input input map, may be null
301 * @return Input map or null.
303 public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
304 return input != null && input.isEmpty() ? null : input;
308 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
309 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
310 * for both non-present and present-with-null objects.
312 * @param obj Internal object to hash
313 * @return Wrapper object hash code
315 public static int wrapperHashCode(final @Nullable Object obj) {
316 return wrapHashCode(Objects.hashCode(obj));
320 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
321 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
322 * for both non-present and present-with-null objects.
324 * @param obj Internal object to hash
325 * @return Wrapper object hash code
327 public static int wrapperHashCode(final byte @Nullable[] obj) {
328 return wrapHashCode(Arrays.hashCode(obj));
332 * Utility method for checking whether a target object is a compatible DataObject.
334 * @param requiredClass Required DataObject class
335 * @param obj Object to check, may be null
336 * @return Object cast to required class, if its implemented class matches requirement, null otherwise
337 * @throws NullPointerException if {@code requiredClass} is null
339 public static <T extends DataObject> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
340 final @Nullable Object obj) {
341 return obj instanceof DataObject && requiredClass.equals(((DataObject) obj).implementedInterface())
342 ? requiredClass.cast(obj) : null;
346 * Utility method for checking whether a target object is compatible.
348 * @param requiredClass Required class
349 * @param fieldName name of the field being filled
350 * @param obj Object to check, may be null
351 * @return Object cast to required class, if its class matches requirement, or null
352 * @throws IllegalArgumentException if {@code obj} is not an instance of {@code requiredClass}
353 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
355 public static <T> @Nullable T checkFieldCast(final @NonNull Class<T> requiredClass, final @NonNull String fieldName,
356 final @Nullable Object obj) {
358 return requiredClass.cast(obj);
359 } catch (ClassCastException e) {
360 throw new IllegalArgumentException("Invalid input value for property \"" + fieldName + "\"", e);
365 * Utility method for checking whether the items of target list is compatible.
367 * @param requiredClass Required item class
368 * @param fieldName name of the field being filled
369 * @param list List, which items should be checked
370 * @throws IllegalArgumentException if a list item is not instance of {@code requiredItemClass}
371 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
373 @SuppressWarnings("unchecked")
374 public static <T> @Nullable List<T> checkListFieldCast(final @NonNull Class<?> requiredClass,
375 final @NonNull String fieldName, final @Nullable List<?> list) {
378 list.forEach(item -> requiredClass.cast(requireNonNull(item)));
379 } catch (ClassCastException | NullPointerException e) {
380 throw new IllegalArgumentException("Invalid input list item for property \"" + requireNonNull(fieldName)
384 return (List<T>) list;
388 * The constant '31' is the result of folding this code:
391 * final int prime = 31;
393 * result = result * prime + Objects.hashCode(obj);
397 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
399 * @param hash Wrapped object hash
400 * @return Wrapper object hash
402 private static int wrapHashCode(final int hash) {
403 return hash == 0 ? 31 : hash;