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.Objects;
22 import java.util.regex.Pattern;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
27 * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
28 * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
29 * general API stability requirements of the Binding Specification.
31 * @author Robert Varga
33 public final class CodeHelpers {
34 private CodeHelpers() {
39 * Require that an a value-related expression is true.
41 * @param expression Expression to evaluate
42 * @param value Value being validated
43 * @param options Valid value options checked
44 * @throws IllegalArgumentException if expression is false
46 public static void validValue(final boolean expression, final Object value, final String options) {
47 checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
51 * A shortcut for {@code Preconditions.checkNotNull(value, "Key component \"%s\" must not be null", name)}.
53 * @param value Value itself
54 * @param name Name of the value
55 * @return Non-null value
56 * @throws NullPointerException if value is null
58 public static <T> @NonNull T requireKeyProp(final @Nullable T value, final @NonNull String name) {
60 throw new NullPointerException("Key component \"" + name + "\" may not be null");
66 * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
68 * @param value Value itself
69 * @throws NullPointerException if value is null
71 public static void requireValue(final @Nullable Object value) {
72 requireNonNull(value, "Supplied value may not be null");
76 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
78 * @param helper Helper to append to
79 * @param name Name of the value
80 * @param value Value to append
81 * @throws NullPointerException if the name or helper is null
83 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
84 final @Nullable Object value) {
86 helper.add(name, value);
91 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
93 * @param helper Helper to append to
94 * @param name Name of the value
95 * @param value Value to append
96 * @throws NullPointerException if the name or helper is null
98 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
100 helper.add(name, Arrays.toString(value));
105 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
108 * @param patterns Patterns to compile
109 * @return Compiled patterns in an array
110 * @throws NullPointerException if the list or any of its elements is null
111 * @throws VerifyException if the list has fewer than two elements
113 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
114 final int size = patterns.size();
115 verify(size > 1, "Patterns has to have at least 2 elements");
116 final Pattern[] result = new Pattern[size];
117 for (int i = 0; i < size; ++i) {
118 result[i] = Pattern.compile(patterns.get(i));
124 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
125 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
127 * @param value Value to be checked.
128 * @param pattern Enforcement pattern
129 * @param regex Source regular expression, as defined in YANG model
130 * @throws IllegalArgumentException if the value does not match the pattern
131 * @throws NullPointerException if any of the arguments are null
133 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
134 if (!pattern.matcher(value).matches()) {
135 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
136 : "does not match required";
137 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
143 * Check whether a specified string value matches specified patterns. This method handles the distinction between
144 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
146 * @param value Value to be checked.
147 * @param patterns Enforcement patterns
148 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
149 * @throws IllegalArgumentException if the value does not match the pattern
150 * @throws NullPointerException if any of the arguments are null
151 * @throws VerifyException if the size of patterns and regexes does not match
153 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
154 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
155 for (int i = 0; i < patterns.length; ++i) {
156 checkPattern(value, patterns[i], regexes[i]);
161 * Throw an IllegalArgument exception describing a length violation.
163 * @param expected String describing expected lengths
164 * @param actual Actual observed object
165 * @throws IllegalArgumentException always
167 public static void throwInvalidLength(final String expected, final Object actual) {
168 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
172 * Throw an IllegalArgument exception describing a length violation.
174 * @param expected String describing expected lengths
175 * @param actual Actual observed byte array
176 * @throws IllegalArgumentException always
178 public static void throwInvalidLength(final String expected, final byte[] actual) {
179 throwInvalidLength(expected, Arrays.toString(actual));
183 * Throw an IllegalArgument exception describing a range violation.
185 * @param expected String describing expected ranges
186 * @param actual Actual observed object
187 * @throws IllegalArgumentException always
189 public static void throwInvalidRange(final String expected, final Object actual) {
190 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
194 * Throw an IllegalArgument exception describing a range violation.
196 * @param expected String describing expected ranges
197 * @param actual Actual observed value
198 * @throws IllegalArgumentException always
200 public static void throwInvalidRange(final String expected, final int actual) {
201 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
202 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
206 * Throw an IllegalArgument exception describing a range violation.
208 * @param expected String describing expected ranges
209 * @param actual Actual observed value
210 * @throws IllegalArgumentException always
212 public static void throwInvalidRange(final String expected, final long actual) {
213 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
214 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
218 * Throw an IllegalArgument exception describing a range violation.
220 * @param expected Objects describing expected ranges
221 * @param actual Actual observed byte array
222 * @throws IllegalArgumentException always
224 public static void throwInvalidRange(final Object[] expected, final Object actual) {
225 throwInvalidRange(Arrays.toString(expected), actual);
229 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
231 * @param expected String describing expected ranges
232 * @param actual Actual observed value
233 * @throws IllegalArgumentException always
235 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
236 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
241 * Check whether specified List is null and if so return an immutable list instead. This method supports
242 * non-null default getter methods.
244 * @param <T> list element type
245 * @param input input list, may be null
246 * @return Input list or an empty list.
248 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
249 return input != null ? input : ImmutableList.of();
253 * Check whether specified Map is null and if so return an immutable map instead. This method supports
254 * non-null default getter methods.
256 * @param <K> key type
257 * @param <V> value type
258 * @param input input map, may be null
259 * @return Input map or an empty map.
261 public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
262 return input != null ? input : ImmutableMap.of();
266 * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
267 * Builder/implementation list handover.
269 * @param <T> list element type
270 * @param input input list, may be null
271 * @return Input list or null.
273 public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
274 return input != null && input.isEmpty() ? null : input;
278 * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
279 * Builder/implementation list handover.
281 * @param <K> key type
282 * @param <V> value type
283 * @param input input map, may be null
284 * @return Input map or null.
286 public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
287 return input != null && input.isEmpty() ? null : input;
291 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
292 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
293 * for both non-present and present-with-null objects.
295 * @param obj Internal object to hash
296 * @return Wrapper object hash code
298 public static int wrapperHashCode(final @Nullable Object obj) {
299 return wrapHashCode(Objects.hashCode(obj));
303 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
304 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
305 * for both non-present and present-with-null objects.
307 * @param obj Internal object to hash
308 * @return Wrapper object hash code
310 public static int wrapperHashCode(final byte @Nullable[] obj) {
311 return wrapHashCode(Arrays.hashCode(obj));
315 * Utility method for checking whether a target object is a compatible DataObject.
317 * @param requiredClass Required DataObject class
318 * @param obj Object to check, may be null
319 * @return Object cast to required class, if its implemented class matches requirement, null otherwise
320 * @throws NullPointerException if {@code requiredClass} is null
322 public static <T extends DataObject> @Nullable T checkCast(final @NonNull Class<T> requiredClass,
323 final @Nullable Object obj) {
324 return obj instanceof DataObject && requiredClass.equals(((DataObject) obj).implementedInterface())
325 ? requiredClass.cast(obj) : null;
329 * Utility method for checking whether a target object is compatible.
331 * @param requiredClass Required class
332 * @param fieldName name of the field being filled
333 * @param obj Object to check, may be null
334 * @return Object cast to required class, if its class matches requirement, or null
335 * @throws IllegalArgumentException if {@code obj} is not an instance of {@code requiredClass}
336 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
338 public static <T> @Nullable T checkFieldCast(final @NonNull Class<T> requiredClass, final @NonNull String fieldName,
339 final @Nullable Object obj) {
341 return requiredClass.cast(obj);
342 } catch (ClassCastException e) {
343 throw new IllegalArgumentException("Invalid input value for property \"" + fieldName + "\"", e);
348 * Utility method for checking whether the items of target list is compatible.
350 * @param requiredClass Required item class
351 * @param fieldName name of the field being filled
352 * @param list List, which items should be checked
353 * @throws IllegalArgumentException if a list item is not instance of {@code requiredItemClass}
354 * @throws NullPointerException if {@code requiredClass} or {@code fieldName} is null
356 @SuppressWarnings("unchecked")
357 public static <T> @Nullable List<T> checkListFieldCast(final @NonNull Class<?> requiredClass,
358 final @NonNull String fieldName, final @Nullable List<?> list) {
361 list.forEach(item -> requiredClass.cast(requireNonNull(item)));
362 } catch (ClassCastException | NullPointerException e) {
363 throw new IllegalArgumentException("Invalid input list item for property \"" + requireNonNull(fieldName)
367 return (List<T>) list;
371 * The constant '31' is the result of folding this code:
374 * final int prime = 31;
376 * result = result * prime + Objects.hashCode(obj);
380 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
382 * @param hash Wrapped object hash
383 * @return Wrapper object hash
385 private static int wrapHashCode(final int hash) {
386 return hash == 0 ? 31 : hash;