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 Objects.requireNonNull(value, "Supplied value may not be null")}.
53 * @param value Value itself
54 * @throws NullPointerException if value is null
56 public static void requireValue(@Nullable final Object value) {
57 requireNonNull(value, "Supplied value may not be null");
61 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
63 * @param helper Helper to append to
64 * @param name Name of the value
65 * @param value Value to append
66 * @throws NullPointerException if the name or helper is null
68 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
69 final @Nullable Object value) {
71 helper.add(name, value);
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 String name, final byte[] value) {
85 helper.add(name, Arrays.toString(value));
90 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
93 * @param patterns Patterns to compile
94 * @return Compiled patterns in an array
95 * @throws NullPointerException if the list or any of its elements is null
96 * @throws VerifyException if the list has fewer than two elements
98 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
99 final int size = patterns.size();
100 verify(size > 1, "Patterns has to have at least 2 elements");
101 final Pattern[] result = new Pattern[size];
102 for (int i = 0; i < size; ++i) {
103 result[i] = Pattern.compile(patterns.get(i));
109 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
110 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
112 * @param value Value to be checked.
113 * @param pattern Enforcement pattern
114 * @param regex Source regular expression, as defined in YANG model
115 * @throws IllegalArgumentException if the value does not match the pattern
116 * @throws NullPointerException if any of the arguments are null
118 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
119 if (!pattern.matcher(value).matches()) {
120 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
121 : "does not match required";
122 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
128 * Check whether a specified string value matches specified patterns. This method handles the distinction between
129 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
131 * @param value Value to be checked.
132 * @param patterns Enforcement patterns
133 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
134 * @throws IllegalArgumentException if the value does not match the pattern
135 * @throws NullPointerException if any of the arguments are null
136 * @throws VerifyException if the size of patterns and regexes does not match
138 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
139 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
140 for (int i = 0; i < patterns.length; ++i) {
141 checkPattern(value, patterns[i], regexes[i]);
146 * Throw an IllegalArgument exception describing a length violation.
148 * @param expected String describing expected lengths
149 * @param actual Actual observed object
150 * @throws IllegalArgumentException always
152 public static void throwInvalidLength(final String expected, final Object actual) {
153 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
157 * Throw an IllegalArgument exception describing a length violation.
159 * @param expected String describing expected lengths
160 * @param actual Actual observed byte array
161 * @throws IllegalArgumentException always
163 public static void throwInvalidLength(final String expected, final byte[] actual) {
164 throwInvalidLength(expected, Arrays.toString(actual));
168 * Throw an IllegalArgument exception describing a range violation.
170 * @param expected String describing expected ranges
171 * @param actual Actual observed object
172 * @throws IllegalArgumentException always
174 public static void throwInvalidRange(final String expected, final Object actual) {
175 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
179 * Throw an IllegalArgument exception describing a range violation.
181 * @param expected String describing expected ranges
182 * @param actual Actual observed value
183 * @throws IllegalArgumentException always
185 public static void throwInvalidRange(final String expected, final int actual) {
186 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
187 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
191 * Throw an IllegalArgument exception describing a range violation.
193 * @param expected String describing expected ranges
194 * @param actual Actual observed value
195 * @throws IllegalArgumentException always
197 public static void throwInvalidRange(final String expected, final long actual) {
198 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
199 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
203 * Throw an IllegalArgument exception describing a range violation.
205 * @param expected Objects describing expected ranges
206 * @param actual Actual observed byte array
207 * @throws IllegalArgumentException always
209 public static void throwInvalidRange(final Object[] expected, final Object actual) {
210 throwInvalidRange(Arrays.toString(expected), actual);
214 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
216 * @param expected String describing expected ranges
217 * @param actual Actual observed value
218 * @throws IllegalArgumentException always
220 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
221 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
226 * Check whether specified List is null and if so return an immutable list instead. This method supports
227 * non-null default getter methods.
229 * @param <T> list element type
230 * @param input input list, may be null
231 * @return Input list or an empty list.
233 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
234 return input != null ? input : ImmutableList.of();
238 * Check whether specified Map is null and if so return an immutable map instead. This method supports
239 * non-null default getter methods.
241 * @param <K> key type
242 * @param <V> value type
243 * @param input input map, may be null
244 * @return Input map or an empty map.
246 public static <K, V> @NonNull Map<K, V> nonnull(final @Nullable Map<K, V> input) {
247 return input != null ? input : ImmutableMap.of();
251 * Check whether specified List is empty and if so return null, otherwise return input list. This method supports
252 * Builder/implementation list handover.
254 * @param <T> list element type
255 * @param input input list, may be null
256 * @return Input list or null.
258 public static <T> @Nullable List<T> emptyToNull(final @Nullable List<T> input) {
259 return input != null && input.isEmpty() ? null : input;
263 * Check whether specified Map is empty and if so return null, otherwise return input map. This method supports
264 * Builder/implementation list handover.
266 * @param <K> key type
267 * @param <V> value type
268 * @param input input map, may be null
269 * @return Input map or null.
271 public static <K, V> @Nullable Map<K, V> emptyToNull(final @Nullable Map<K, V> input) {
272 return input != null && input.isEmpty() ? null : input;
276 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
277 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
278 * for both non-present and present-with-null objects.
280 * @param obj Internal object to hash
281 * @return Wrapper object hash code
283 public static int wrapperHashCode(final @Nullable Object obj) {
284 return wrapHashCode(Objects.hashCode(obj));
288 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
289 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
290 * for both non-present and present-with-null objects.
292 * @param obj Internal object to hash
293 * @return Wrapper object hash code
295 public static int wrapperHashCode(final byte @Nullable[] obj) {
296 return wrapHashCode(Arrays.hashCode(obj));
300 * The constant '31' is the result of folding this code:
302 * final int prime = 31;
304 * result = result * prime + Objects.hashCode(obj);
307 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
309 * @param hash Wrapped object hash
310 * @return Wrapper object hash
312 private static int wrapHashCode(final int hash) {
313 return hash == 0 ? 31 : hash;