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 java.util.Arrays;
18 import java.util.List;
19 import java.util.Objects;
20 import java.util.regex.Pattern;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.eclipse.jdt.annotation.Nullable;
25 * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
26 * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
27 * general API stability requirements of the Binding Specification.
29 * @author Robert Varga
31 public final class CodeHelpers {
32 private CodeHelpers() {
37 * Require that an a value-related expression is true.
39 * @param expression Expression to evaluate
40 * @param value Value being validated
41 * @param options Valid value options checked
42 * @throws IllegalArgumentException if expression is false
44 public static void validValue(final boolean expression, final Object value, final String options) {
45 checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
49 * Require an argument being received. This is similar to {@link java.util.Objects#requireNonNull(Object)}, but
50 * throws an IllegalArgumentException.
53 * Implementation note: we expect argName to be a string literal or a constant, so that it's non-nullness can be
54 * quickly discovered for a call site (where we are going to be inlined).
56 * @param value Value itself
57 * @param name Symbolic name
58 * @return non-null value
59 * @throws IllegalArgumentException if value is null
60 * @throws NullPointerException if name is null
62 // FIXME: another advantage is that it is JDT-annotated, but we could live without that. At some point we should
63 // schedule a big ISE-to-NPE conversion and just use Objects.requireNonNull() instead.
64 public static <T> @NonNull T nonNullValue(@Nullable final T value, final @NonNull String name) {
66 checkArgument(value != null, "%s must not be null", name);
71 * A shortcut for {@code Objects.requireNonNull(value, "Supplied value may not be null")}.
73 * @param value Value itself
74 * @throws NullPointerException if value is null
76 public static void requireValue(@Nullable final Object value) {
77 requireNonNull(value, "Supplied value may not be null");
81 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
83 * @param helper Helper to append to
84 * @param name Name of the value
85 * @param value Value to append
86 * @throws NullPointerException if the name or helper is null
88 public static void appendValue(final ToStringHelper helper, final @NonNull String name,
89 final @Nullable Object value) {
91 helper.add(name, value);
96 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
98 * @param helper Helper to append to
99 * @param name Name of the value
100 * @param value Value to append
101 * @throws NullPointerException if the name or helper is null
103 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
105 helper.add(name, Arrays.toString(value));
110 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
113 * @param patterns Patterns to compile
114 * @return Compiled patterns in an array
115 * @throws NullPointerException if the list or any of its elements is null
116 * @throws VerifyException if the list has fewer than two elements
118 public static Pattern @NonNull[] compilePatterns(final @NonNull List<String> patterns) {
119 final int size = patterns.size();
120 verify(size > 1, "Patterns has to have at least 2 elements");
121 final Pattern[] result = new Pattern[size];
122 for (int i = 0; i < size; ++i) {
123 result[i] = Pattern.compile(patterns.get(i));
129 * Check whether a specified string value matches a specified pattern. 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 pattern Enforcement pattern
134 * @param regex Source regular expression, as defined in YANG model
135 * @throws IllegalArgumentException if the value does not match the pattern
136 * @throws NullPointerException if any of the arguments are null
138 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
139 if (!pattern.matcher(value).matches()) {
140 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
141 : "does not match required";
142 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
148 * Check whether a specified string value matches specified patterns. This method handles the distinction between
149 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
151 * @param value Value to be checked.
152 * @param patterns Enforcement patterns
153 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
154 * @throws IllegalArgumentException if the value does not match the pattern
155 * @throws NullPointerException if any of the arguments are null
156 * @throws VerifyException if the size of patterns and regexes does not match
158 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
159 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
160 for (int i = 0; i < patterns.length; ++i) {
161 checkPattern(value, patterns[i], regexes[i]);
166 * Throw an IllegalArgument exception describing a length violation.
168 * @param expected String describing expected lengths
169 * @param actual Actual observed object
170 * @throws IllegalArgumentException always
172 public static void throwInvalidLength(final String expected, final Object actual) {
173 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
177 * Throw an IllegalArgument exception describing a length violation.
179 * @param expected String describing expected lengths
180 * @param actual Actual observed byte array
181 * @throws IllegalArgumentException always
183 public static void throwInvalidLength(final String expected, final byte[] actual) {
184 throwInvalidLength(expected, Arrays.toString(actual));
188 * Throw an IllegalArgument exception describing a range violation.
190 * @param expected String describing expected ranges
191 * @param actual Actual observed object
192 * @throws IllegalArgumentException always
194 public static void throwInvalidRange(final String expected, final Object actual) {
195 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
199 * Throw an IllegalArgument exception describing a range violation.
201 * @param expected String describing expected ranges
202 * @param actual Actual observed value
203 * @throws IllegalArgumentException always
205 public static void throwInvalidRange(final String expected, final int actual) {
206 // Not a code duplication: provides faster string concat via StringBuilder.append(int)
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 long actual) {
218 // Not a code duplication: provides faster string concat via StringBuilder.append(long)
219 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
223 * Throw an IllegalArgument exception describing a range violation.
225 * @param expected Objects describing expected ranges
226 * @param actual Actual observed byte array
227 * @throws IllegalArgumentException always
229 public static void throwInvalidRange(final Object[] expected, final Object actual) {
230 throwInvalidRange(Arrays.toString(expected), actual);
234 * Throw an IllegalArgument exception describing a range violation of an Uint64 type.
236 * @param expected String describing expected ranges
237 * @param actual Actual observed value
238 * @throws IllegalArgumentException always
240 public static void throwInvalidRangeUnsigned(final String expected, final long actual) {
241 throw new IllegalArgumentException("Invalid range: " + Long.toUnsignedString(actual) + ", expected: " + expected
246 * Check whether specified List is null and if so return an immutable list instead. This method supports
247 * non-null default getter methods.
249 * @param input input list, may be null
250 * @return Input list or an empty list.
252 public static <T> @NonNull List<T> nonnull(final @Nullable List<T> input) {
253 return input != null ? input : ImmutableList.of();
257 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
258 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
259 * for both non-present and present-with-null objects.
261 * @param obj Internal object to hash
262 * @return Wrapper object hash code
264 public static int wrapperHashCode(final @Nullable Object obj) {
265 return wrapHashCode(Objects.hashCode(obj));
269 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
270 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
271 * for both non-present and present-with-null objects.
273 * @param obj Internal object to hash
274 * @return Wrapper object hash code
276 public static int wrapperHashCode(final byte @Nullable[] obj) {
277 return wrapHashCode(Arrays.hashCode(obj));
281 * The constant '31' is the result of folding this code:
283 * final int prime = 31;
285 * result = result * prime + Objects.hashCode(obj);
288 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
290 * @param hash Wrapped object hash
291 * @return Wrapper object hash
293 private static int wrapHashCode(final int hash) {
294 return hash == 0 ? 31 : hash;