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