Move BindingMapping
[mdsal.git] / binding / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / CodeHelpers.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.binding;
9
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;
13
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.base.VerifyException;
16 import java.util.Arrays;
17 import java.util.List;
18 import java.util.regex.Pattern;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.Nullable;
21
22 /**
23  * Helper methods for generated binding code. This class concentrates useful primitives generated code may call
24  * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows
25  * general API stability requirements of the Binding Specification.
26  *
27  * @author Robert Varga
28  */
29 public final class CodeHelpers {
30     private CodeHelpers() {
31         // Hidden
32     }
33
34     /**
35      * Require that an a value-related expression is true.
36      *
37      * @param expression Expression to evaluate
38      * @param value Value being validated
39      * @param options Valid value options checked
40      * @throws IllegalArgumentException if expression is false
41      */
42     public static void validValue(final boolean expression, final Object value, final String options) {
43         checkArgument(expression, "expected one of: %s \n%but was: %s", options, value);
44     }
45
46     /**
47      * Require an argument being received. This is similar to {@link java.util.Objects#requireNonNull(Object)}, but
48      * throws an IllegalArgumentException.
49      *
50      * <p>
51      * Implementation note: we expect argName to be a string literal or a constant, so that it's non-nullness can be
52      *                      quickly discovered for a call site (where we are going to be inlined).
53      *
54      * @param value Value itself
55      * @param name Symbolic name
56      * @return non-null value
57      * @throws IllegalArgumentException if value is null
58      * @throws NullPointerException if name is null
59      */
60     // FIXME: another advantage is that it is JDT-annotated, but we could live without that. At some point we should
61     //        schedule a big ISE-to-NPE conversion and just use Objects.requireNonNull() instead.
62     public static <T> @NonNull T nonNullValue(@Nullable final T value, final @NonNull String name) {
63         requireNonNull(name);
64         checkArgument(value != null, "%s must not be null", name);
65         return value;
66     }
67
68     /**
69      * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
70      *
71      * @param helper Helper to append to
72      * @param name Name of the value
73      * @param value Value to append
74      * @throws NullPointerException if the name or helper is null
75      */
76     public static void appendValue(final @NonNull ToStringHelper helper, final @NonNull String name,
77             final @Nullable Object value) {
78         if (value != null) {
79             helper.add(name, value);
80         }
81     }
82
83     /**
84      * Append a named value to a ToStringHelper. If the value is null, this method does nothing.
85      *
86      * @param helper Helper to append to
87      * @param name Name of the value
88      * @param value Value to append
89      * @throws NullPointerException if the name or helper is null
90      */
91     public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) {
92         if (value != null) {
93             helper.add(name, Arrays.toString(value));
94         }
95     }
96
97     /**
98      * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two
99      * expressions.
100      *
101      * @param patterns Patterns to compile
102      * @return Compiled patterns in an array
103      * @throws NullPointerException if the list or any of its elements is null
104      * @throws VerifyException if the list has fewer than two elements
105      */
106     public static @NonNull Pattern[] compilePatterns(final @NonNull List<String> patterns) {
107         final int size = patterns.size();
108         verify(size > 1, "Patterns has to have at least 2 elements");
109         final @NonNull Pattern[] result = new Pattern[size];
110         for (int i = 0; i < size; ++i) {
111             result[i] = Pattern.compile(patterns.get(i));
112         }
113         return result;
114     }
115
116     /**
117      * Check whether a specified string value matches a specified pattern. This method handles the distinction between
118      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
119      *
120      * @param value Value to be checked.
121      * @param pattern Enforcement pattern
122      * @param regex Source regular expression, as defined in YANG model
123      * @throws IllegalArgumentException if the value does not match the pattern
124      * @throws NullPointerException if any of the arguments are null
125      */
126     public static void checkPattern(final String value, final Pattern pattern, final String regex) {
127         if (!pattern.matcher(value).matches()) {
128             final String match = RegexPatterns.isNegatedPattern(pattern) ? "matches forbidden"
129                 : "does not match required";
130             throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \""
131                     + regex + "\"");
132         }
133     }
134
135     /**
136      * Check whether a specified string value matches specified patterns. This method handles the distinction between
137      * modeled XSD expression and enforcement {@link Pattern} which may reflect negation.
138      *
139      * @param value Value to be checked.
140      * @param patterns Enforcement patterns
141      * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns.
142      * @throws IllegalArgumentException if the value does not match the pattern
143      * @throws NullPointerException if any of the arguments are null
144      * @throws VerifyException if the size of patterns and regexes does not match
145      */
146     public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) {
147         verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match");
148         for (int i = 0; i < patterns.length; ++i) {
149             checkPattern(value, patterns[i], regexes[i]);
150         }
151     }
152
153     /**
154      * Throw an IllegalArgument exception describing a length violation.
155      *
156      * @param expected String describing expected lengths
157      * @param actual Actual observed object
158      * @throws IllegalArgumentException always
159      */
160     public static void throwInvalidLength(final String expected, final Object actual) {
161         throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + ".");
162     }
163
164     /**
165      * Throw an IllegalArgument exception describing a length violation.
166      *
167      * @param expected String describing expected lengths
168      * @param actual Actual observed byte array
169      * @throws IllegalArgumentException always
170      */
171     public static void throwInvalidLength(final String expected, final byte[] actual) {
172         throwInvalidLength(expected, Arrays.toString(actual));
173     }
174
175     /**
176      * Throw an IllegalArgument exception describing a range violation.
177      *
178      * @param expected String describing expected ranges
179      * @param actual Actual observed object
180      * @throws IllegalArgumentException always
181      */
182     public static void throwInvalidRange(final String expected, final Object actual) {
183         throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + ".");
184     }
185
186     /**
187      * Throw an IllegalArgument exception describing a range violation.
188      *
189      * @param expected Objects describing expected ranges
190      * @param actual Actual observed byte array
191      * @throws IllegalArgumentException always
192      */
193     public static void throwInvalidRange(final Object[] expected, final Object actual) {
194         throwInvalidRange(Arrays.toString(expected), actual);
195     }
196 }