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.util.Arrays;
20 import java.util.List;
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 * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
54 * @param value Value itself
55 * @throws NullPointerException if value is null
57 public static void requireValue(@Nullable final Object value) {
58 requireNonNull(value, "Supplied value may not be null");
62 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
64 * @param helper Helper to append to
65 * @param name Name of the value
66 * @param value Value to append
67 * @throws NullPointerException if the name or helper is null
69 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
70 final @Nullable Object value) {
72 helper.add(name, value);
77 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
79 * @param helper Helper to append to
80 * @param name Name of the value
81 * @param value Value to append
82 * @throws NullPointerException if the name or helper is null
84 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
86 helper.add(name, Arrays.toString(value));
91 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
94 * @param patterns Patterns to compile
95 * @return Compiled patterns in an array
96 * @throws NullPointerException if the list or any of its elements is null
97 * @throws VerifyException if the list has fewer than two elements
99 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
100 final int size = patterns.size();
101 verify(size > 1, "Patterns has to have at least 2 elements");
102 final Pattern[] result = new Pattern[size];
103 for (int i = 0; i < size; ++i) {
104 result[i] = Pattern.compile(patterns.get(i));
110 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
111 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
113 * @param value Value to be checked.
114 * @param pattern Enforcement pattern
115 * @param regex Source regular expression, as defined in YANG model
116 * @throws IllegalArgumentException if the value does not match the pattern
117 * @throws NullPointerException if any of the arguments are null
119 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
120 if (!pattern.matcher(value).matches()) {
121 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
122 : "does not match required";
123 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
129 * Check whether a specified string value matches specified patterns. This method handles the distinction between
130 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
132 * @param value Value to be checked.
133 * @param patterns Enforcement patterns
134 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
135 * @throws IllegalArgumentException if the value does not match the pattern
136 * @throws NullPointerException if any of the arguments are null
137 * @throws VerifyException if the size of patterns and regexes does not match
139 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
140 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
141 for (int i = 0; i < patterns.length; ++i) {
142 checkPattern(value, patterns[i], regexes[i]);
147 * Throw an IllegalArgument exception describing a length violation.
149 * @param expected String describing expected lengths
150 * @param actual Actual observed object
151 * @throws IllegalArgumentException always
153 public static void throwInvalidLength(final String expected, final Object actual) {
154 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
158 * Throw an IllegalArgument exception describing a length violation.
160 * @param expected String describing expected lengths
161 * @param actual Actual observed byte array
162 * @throws IllegalArgumentException always
164 public static void throwInvalidLength(final String expected, final byte[] actual) {
165 throwInvalidLength(expected, Arrays.toString(actual));
169 * Throw an IllegalArgument exception describing a range violation.
171 * @param expected String describing expected ranges
172 * @param actual Actual observed object
173 * @throws IllegalArgumentException always
175 public static void throwInvalidRange(final String expected, final Object actual) {
176 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
180 * Throw an IllegalArgument exception describing a range violation.
182 * @param expected String describing expected ranges
183 * @param actual Actual observed value
184 * @throws IllegalArgumentException always
186 public static void throwInvalidRange(final String expected, final int actual) {
187 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
188 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
192 * Throw an IllegalArgument exception describing a range violation.
194 * @param expected String describing expected ranges
195 * @param actual Actual observed value
196 * @throws IllegalArgumentException always
198 public static void throwInvalidRange(final String expected, final long actual) {
199 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
200 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
204 * Throw an IllegalArgument exception describing a range violation.
206 * @param expected Objects describing expected ranges
207 * @param actual Actual observed byte array
208 * @throws IllegalArgumentException always
210 public static void throwInvalidRange(final Object[] expected, final Object actual) {
211 throwInvalidRange(Arrays.toString(expected), actual);
215 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
217 * @param expected String describing expected ranges
218 * @param actual Actual observed value
219 * @throws IllegalArgumentException always
221 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
222 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
227 * Check whether specified List is null and if so return an immutable list instead. This method supports
228 * non-null default getter methods.
230 * @param <T> list element type
231 * @param input input list, may be null
232 * @return Input list or an empty list.
234 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
235 return input != null ? input : ImmutableList.of();
239 * Check whether specified Map is null and if so return an immutable map instead. This method supports
240 * non-null default getter methods.
242 * @param <K> key type
243 * @param <V> value type
244 * @param input input map, may be null
245 * @return Input map or an empty map.
247 public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
248 return input != null ? input : ImmutableMap.of();
252 * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
253 * Builder/implementation list handover.
255 * @param <T> list element type
256 * @param input input list, may be null
257 * @return Input list or null.
259 public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
260 return input != null && input.isEmpty() ? null : input;
264 * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
265 * Builder/implementation list handover.
267 * @param <K> key type
268 * @param <V> value type
269 * @param input input map, may be null
270 * @return Input map or null.
272 public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
273 return input != null && input.isEmpty() ? null : input;
277 * Compatibility utility for turning a List of identifiable objects to an indexed map.
279 * @param <K> key type
280 * @param <V> identifiable type
281 * @param list legacy list
282 * @return Indexed map
283 * @throws IllegalArgumentException if the list contains entries with the same key
284 * @throws NullPointerException if the list contains a null entry
285 * @deprecated This method is a transitional helper used only in methods deprecated themselves.
287 // FIXME: MDSAL-540: remove this method
289 public static <K extends Identifier<V>, V extends Identifiable<K>> @Nullable Map<K, V> compatMap(
290 final @Nullable List<V> list) {
291 return list == null || list.isEmpty() ? null : Maps.uniqueIndex(list, Identifiable::key);
295 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
296 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
297 * for both non-present and present-with-null objects.
299 * @param obj Internal object to hash
300 * @return Wrapper object hash code
302 public static int wrapperHashCode(final @Nullable Object obj) {
303 return wrapHashCode(Objects.hashCode(obj));
307 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
308 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
309 * for both non-present and present-with-null objects.
311 * @param obj Internal object to hash
312 * @return Wrapper object hash code
314 public static int wrapperHashCode(final byte @Nullable[] obj) {
315 return wrapHashCode(Arrays.hashCode(obj));
319 * The constant '31' is the result of folding this code:
321 * final int prime = 31;
323 * result = result * prime + Objects.hashCode(obj);
326 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
328 * @param hash Wrapped object hash
329 * @return Wrapper object hash
331 private static int wrapHashCode(final int hash) {
332 return hash == 0 ? 31 : hash;