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 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
73 * @param helper Helper to append to
74 * @param name Name of the value
75 * @param value Value to append
76 * @throws NullPointerException if the name or helper is null
78 public static void appendValue(final @NonNull ToStringHelper helper, final @NonNull String name,
79 final @Nullable Object value) {
81 helper.add(name, value);
86 * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
88 * @param helper Helper to append to
89 * @param name Name of the value
90 * @param value Value to append
91 * @throws NullPointerException if the name or helper is null
93 public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
95 helper.add(name, Arrays.toString(value));
100 * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
103 * @param patterns Patterns to compile
104 * @return Compiled patterns in an array
105 * @throws NullPointerException if the list or any of its elements is null
106 * @throws VerifyException if the list has fewer than two elements
108 public static @NonNull Pattern[] compilePatterns(final @NonNull List<String> patterns) {
109 final int size = patterns.size();
110 verify(size > 1, "Patterns has to have at least 2 elements");
111 final @NonNull Pattern[] result = new Pattern[size];
112 for (int i = 0; i < size; ++i) {
113 result[i] = Pattern.compile(patterns.get(i));
119 * Check whether a specified string value matches a specified pattern. This method handles the distinction between
120 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
122 * @param value Value to be checked.
123 * @param pattern Enforcement pattern
124 * @param regex Source regular expression, as defined in YANG model
125 * @throws IllegalArgumentException if the value does not match the pattern
126 * @throws NullPointerException if any of the arguments are null
128 public static void checkPattern(final String value, final Pattern pattern, final String regex) {
129 if (!pattern.matcher(value).matches()) {
130 final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
131 : "does not match required";
132 throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
138 * Check whether a specified string value matches specified patterns. This method handles the distinction between
139 * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
141 * @param value Value to be checked.
142 * @param patterns Enforcement patterns
143 * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
144 * @throws IllegalArgumentException if the value does not match the pattern
145 * @throws NullPointerException if any of the arguments are null
146 * @throws VerifyException if the size of patterns and regexes does not match
148 public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
149 verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
150 for (int i = 0; i < patterns.length; ++i) {
151 checkPattern(value, patterns[i], regexes[i]);
156 * Throw an IllegalArgument exception describing a length violation.
158 * @param expected String describing expected lengths
159 * @param actual Actual observed object
160 * @throws IllegalArgumentException always
162 public static void throwInvalidLength(final String expected, final Object actual) {
163 throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
167 * Throw an IllegalArgument exception describing a length violation.
169 * @param expected String describing expected lengths
170 * @param actual Actual observed byte array
171 * @throws IllegalArgumentException always
173 public static void throwInvalidLength(final String expected, final byte[] actual) {
174 throwInvalidLength(expected, Arrays.toString(actual));
178 * Throw an IllegalArgument exception describing a range violation.
180 * @param expected String describing expected ranges
181 * @param actual Actual observed object
182 * @throws IllegalArgumentException always
184 public static void throwInvalidRange(final String expected, final Object actual) {
185 throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
189 * Throw an IllegalArgument exception describing a range violation.
191 * @param expected Objects describing expected ranges
192 * @param actual Actual observed byte array
193 * @throws IllegalArgumentException always
195 public static void throwInvalidRange(final Object[] expected, final Object actual) {
196 throwInvalidRange(Arrays.toString(expected), actual);
200 * Check whether specified List is null and if so return an immutable list instead. This method supports
201 * non-null default getter methods.
203 * @param input input list, may be null
204 * @return Input list or an empty list.
206 public static <T> List<T> nonnull(final @Nullable List<T> input) {
207 return input != null ? input : ImmutableList.of();
211 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
212 * this object being present, hence {@link Objects#hashCode()} is not really useful we would end up with {@code 0}
213 * for both non-present and present-with-null objects.
215 * @param obj Internal object to hash
216 * @return Wrapper object hash code
218 public static int wrapperHashCode(final @Nullable Object obj) {
219 return wrapHashCode(Objects.hashCode(obj));
223 * Return hash code of a single-property wrapper class. Since the wrapper is not null, we really want to discern
224 * this object being present, hence {@link Arrays#hashCode()} is not really useful we would end up with {@code 0}
225 * for both non-present and present-with-null objects.
227 * @param obj Internal object to hash
228 * @return Wrapper object hash code
230 public static int wrapperHashCode(final byte @Nullable[] obj) {
231 return wrapHashCode(Arrays.hashCode(obj));
235 * The constant '31' is the result of folding this code:
237 * final int prime = 31;
239 * result = result * prime + Objects.hashCode(obj);
242 * when hashCode is returned as 0, such as due to obj being null or its hashCode being 0.
244 * @param hash Wrapped object hash
245 * @return Wrapper object hash
247 private static int wrapHashCode(int hash) {
248 return hash == 0 ? 31 : hash;