Remove explicit UOE throws
[mdsal.git] / binding / mdsal-binding-spec-util / src / main / java / org / opendaylight / mdsal / binding / spec / naming / BindingMapping.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  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.mdsal.binding.spec.naming;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.CharMatcher;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.BiMap;
16 import com.google.common.collect.HashBiMap;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.Interner;
19 import com.google.common.collect.Interners;
20 import java.util.Collection;
21 import java.util.Locale;
22 import java.util.Optional;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.yangtools.yang.binding.Augmentable;
27 import org.opendaylight.yangtools.yang.binding.DataContainer;
28 import org.opendaylight.yangtools.yang.binding.Identifiable;
29 import org.opendaylight.yangtools.yang.binding.ScalarTypeObject;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.QNameModule;
32 import org.opendaylight.yangtools.yang.common.Revision;
33
34 @Beta
35 public final class BindingMapping {
36
37     public static final @NonNull String VERSION = "0.6";
38
39     public static final ImmutableSet<String> JAVA_RESERVED_WORDS = ImmutableSet.of(
40         // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.9
41         "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue",
42         "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if",
43         "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private",
44         "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this",
45         "throw", "throws", "transient", "try", "void", "volatile", "while", "_",
46         // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.3
47         "false", "true",
48         // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.7
49         "null");
50
51     public static final @NonNull String DATA_ROOT_SUFFIX = "Data";
52     public static final @NonNull String RPC_SERVICE_SUFFIX = "Service";
53     public static final @NonNull String NOTIFICATION_LISTENER_SUFFIX = "Listener";
54     public static final @NonNull String QNAME_STATIC_FIELD_NAME = "QNAME";
55     public static final @NonNull String PACKAGE_PREFIX = "org.opendaylight.yang.gen.v1";
56     public static final @NonNull String AUGMENTATION_FIELD = "augmentation";
57
58     private static final Splitter CAMEL_SPLITTER = Splitter.on(CharMatcher.anyOf(" _.-/").precomputed())
59             .omitEmptyStrings().trimResults();
60     private static final Pattern COLON_SLASH_SLASH = Pattern.compile("://", Pattern.LITERAL);
61     private static final String QUOTED_DOT = Matcher.quoteReplacement(".");
62     private static final Splitter DOT_SPLITTER = Splitter.on('.');
63
64     public static final @NonNull String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl";
65     public static final @NonNull String MODULE_INFO_QNAMEOF_METHOD_NAME = "qnameOf";
66     public static final @NonNull String MODEL_BINDING_PROVIDER_CLASS_NAME = "$YangModelBindingProvider";
67
68     /**
69      * Name of {@link Augmentable#augmentation(Class)}.
70      */
71     public static final @NonNull String AUGMENTABLE_AUGMENTATION_NAME = "augmentation";
72
73     /**
74      * Name of {@link Identifiable#key()}.
75      */
76     public static final @NonNull String IDENTIFIABLE_KEY_NAME = "key";
77
78     /**
79      * Name of {@link DataContainer#implementedInterface()}.
80      */
81     public static final @NonNull String DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME = "implementedInterface";
82
83     /**
84      * Name of {@link ScalarTypeObject#getValue()}.
85      */
86     public static final @NonNull String SCALAR_TYPE_OBJECT_GET_VALUE_NAME = "getValue";
87
88     /**
89      * Prefix for getter methods working on top of boolean.
90      */
91     public static final @NonNull String BOOLEAN_GETTER_PREFIX = "is";
92
93     /**
94      * Prefix for normal getter methods.
95      */
96     public static final @NonNull String GETTER_PREFIX = "get";
97
98     /**
99      * Prefix for non-null default wrapper methods. These methods always wrap a corresponding normal getter.
100      */
101     public static final @NonNull String NONNULL_PREFIX = "nonnull";
102
103     public static final @NonNull String RPC_INPUT_SUFFIX = "Input";
104     public static final @NonNull String RPC_OUTPUT_SUFFIX = "Output";
105
106     private static final Interner<String> PACKAGE_INTERNER = Interners.newWeakInterner();
107
108     private BindingMapping() {
109         // Hidden on purpose
110     }
111
112     public static @NonNull String getRootPackageName(final QName module) {
113         return getRootPackageName(module.getModule());
114     }
115
116     public static @NonNull String getRootPackageName(final QNameModule module) {
117         final StringBuilder packageNameBuilder = new StringBuilder().append(BindingMapping.PACKAGE_PREFIX).append('.');
118
119         String namespace = module.getNamespace().toString();
120         namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
121
122         final char[] chars = namespace.toCharArray();
123         for (int i = 0; i < chars.length; ++i) {
124             switch (chars[i]) {
125                 case '/':
126                 case ':':
127                 case '-':
128                 case '@':
129                 case '$':
130                 case '#':
131                 case '\'':
132                 case '*':
133                 case '+':
134                 case ',':
135                 case ';':
136                 case '=':
137                     chars[i] = '.';
138                     break;
139                 default:
140                     // no-op
141             }
142         }
143
144         packageNameBuilder.append(chars);
145         if (chars[chars.length - 1] != '.') {
146             packageNameBuilder.append('.');
147         }
148
149         final Optional<Revision> optRev = module.getRevision();
150         if (optRev.isPresent()) {
151             // Revision is in format 2017-10-26, we want the output to be 171026, which is a matter of picking the
152             // right characters.
153             final String rev = optRev.get().toString();
154             checkArgument(rev.length() == 10, "Unsupported revision %s", rev);
155             packageNameBuilder.append("rev").append(rev, 2, 4).append(rev, 5, 7).append(rev.substring(8));
156         } else {
157             // No-revision packages are special
158             packageNameBuilder.append("norev");
159         }
160
161         return normalizePackageName(packageNameBuilder.toString());
162     }
163
164     public static @NonNull String normalizePackageName(final String packageName) {
165         final StringBuilder builder = new StringBuilder();
166         boolean first = true;
167
168         for (String p : DOT_SPLITTER.split(packageName.toLowerCase(Locale.ENGLISH))) {
169             if (first) {
170                 first = false;
171             } else {
172                 builder.append('.');
173             }
174
175             if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
176                 builder.append('_');
177             }
178             builder.append(p);
179         }
180
181         // Prevent duplication of input string
182         return PACKAGE_INTERNER.intern(builder.toString());
183     }
184
185     public static @NonNull String getClassName(final String localName) {
186         return toFirstUpper(toCamelCase(localName));
187     }
188
189     public static @NonNull String getClassName(final QName name) {
190         return toFirstUpper(toCamelCase(name.getLocalName()));
191     }
192
193     public static @NonNull String getMethodName(final String yangIdentifier) {
194         return toFirstLower(toCamelCase(yangIdentifier));
195     }
196
197     public static @NonNull String getMethodName(final QName name) {
198         return getMethodName(name.getLocalName());
199     }
200
201     public static @NonNull String getGetterPrefix(final boolean isBoolean) {
202         return isBoolean ? BOOLEAN_GETTER_PREFIX : GETTER_PREFIX;
203     }
204
205     public static @NonNull String getGetterMethodName(final String localName, final boolean isBoolean) {
206         return getGetterPrefix(isBoolean) + toFirstUpper(getPropertyName(localName));
207     }
208
209     public static @NonNull String getGetterMethodName(final QName name, final boolean isBoolean) {
210         return getGetterPrefix(isBoolean) + getGetterSuffix(name);
211     }
212
213     public static boolean isGetterMethodName(final String methodName) {
214         return methodName.startsWith(GETTER_PREFIX) || methodName.startsWith(BOOLEAN_GETTER_PREFIX);
215     }
216
217     public static @NonNull String getGetterMethodForNonnull(final String methodName) {
218         checkArgument(isNonnullMethodName(methodName));
219         return GETTER_PREFIX + methodName.substring(NONNULL_PREFIX.length());
220     }
221
222     public static @NonNull String getNonnullMethodName(final String localName) {
223         return NONNULL_PREFIX + toFirstUpper(getPropertyName(localName));
224     }
225
226     public static boolean isNonnullMethodName(final String methodName) {
227         return methodName.startsWith(NONNULL_PREFIX);
228     }
229
230     public static @NonNull String getGetterSuffix(final QName name) {
231         final String candidate = toFirstUpper(toCamelCase(name.getLocalName()));
232         return "Class".equals(candidate) ? "XmlClass" : candidate;
233     }
234
235     public static @NonNull String getPropertyName(final String yangIdentifier) {
236         final String potential = toFirstLower(toCamelCase(yangIdentifier));
237         if ("class".equals(potential)) {
238             return "xmlClass";
239         }
240         return potential;
241     }
242
243     private static @NonNull String toCamelCase(final String rawString) {
244         StringBuilder builder = new StringBuilder();
245         for (String comp : CAMEL_SPLITTER.split(rawString)) {
246             builder.append(toFirstUpper(comp));
247         }
248         return checkNumericPrefix(builder.toString());
249     }
250
251     private static @NonNull String checkNumericPrefix(final String rawString) {
252         if (rawString.isEmpty()) {
253             return rawString;
254         }
255         final char firstChar = rawString.charAt(0);
256         return firstChar >= '0' && firstChar <= '9' ? "_" + rawString : rawString;
257     }
258
259     /**
260      * Returns the {@link String} {@code s} with an {@link Character#isUpperCase(char) upper case} first character.
261      *
262      * @param str the string that should get an upper case first character.
263      * @return the {@link String} {@code str} with an upper case first character.
264      */
265     private static @NonNull String toFirstUpper(final @NonNull String str) {
266         if (str.isEmpty()) {
267             return str;
268         }
269         if (Character.isUpperCase(str.charAt(0))) {
270             return str;
271         }
272         if (str.length() == 1) {
273             return str.toUpperCase(Locale.ENGLISH);
274         }
275         return str.substring(0, 1).toUpperCase(Locale.ENGLISH) + str.substring(1);
276     }
277
278     /**
279      * Returns the {@link String} {@code s} with a {@link Character#isLowerCase(char) lower case} first character. This
280      * function is null-safe.
281      *
282      * @param str the string that should get an lower case first character. May be <code>null</code>.
283      * @return the {@link String} {@code str} with an lower case first character or <code>null</code> if the input
284      *         {@link String} {@code str} was empty.
285      */
286     private static @NonNull String toFirstLower(final @NonNull String str) {
287         if (str.isEmpty()) {
288             return str;
289         }
290         if (Character.isLowerCase(str.charAt(0))) {
291             return str;
292         }
293         if (str.length() == 1) {
294             return str.toLowerCase(Locale.ENGLISH);
295         }
296         return str.substring(0, 1).toLowerCase(Locale.ENGLISH) + str.substring(1);
297     }
298
299     /**
300      * Returns the {@link String} {@code s} with a '$' character as suffix.
301      *
302      * @param qname RPC QName
303      * @return The RPC method name as determined by considering the localname against the JLS.
304      * @throws NullPointerException if {@code qname} is null
305      */
306     public static @NonNull String getRpcMethodName(final @NonNull QName qname) {
307         final String methodName = getMethodName(qname);
308         return JAVA_RESERVED_WORDS.contains(methodName) ? methodName + "$" : methodName;
309     }
310
311     /**
312      * Returns Java identifiers, conforming to JLS9 Section 3.8 to use for specified YANG assigned names
313      * (RFC7950 Section 9.6.4). This method considers two distinct encodings: one the pre-Fluorine mapping, which is
314      * okay and convenient for sane strings, and an escaping-based bijective mapping which works for all possible
315      * Unicode strings.
316      *
317      * @param assignedNames Collection of assigned names
318      * @return A BiMap keyed by assigned name, with Java identifiers as values
319      * @throws NullPointerException if assignedNames is null or contains null items
320      * @throws IllegalArgumentException if any of the names is empty
321      */
322     public static BiMap<String, String> mapEnumAssignedNames(final Collection<String> assignedNames) {
323         /*
324          * Original mapping assumed strings encountered are identifiers, hence it used getClassName to map the names
325          * and that function is not an injection -- this is evidenced in MDSAL-208 and results in a failure to compile
326          * generated code. If we encounter such a conflict or if the result is not a valid identifier (like '*'), we
327          * abort and switch the mapping schema to mapEnumAssignedName(), which is a bijection.
328          *
329          * Note that assignedNames can contain duplicates, which must not trigger a duplication fallback.
330          */
331         final BiMap<String, String> javaToYang = HashBiMap.create(assignedNames.size());
332         boolean valid = true;
333         for (String name : assignedNames) {
334             checkArgument(!name.isEmpty());
335             if (!javaToYang.containsValue(name)) {
336                 final String mappedName = getClassName(name);
337                 if (!isValidJavaIdentifier(mappedName) || javaToYang.forcePut(mappedName, name) != null) {
338                     valid = false;
339                     break;
340                 }
341             }
342         }
343
344         if (!valid) {
345             // Fall back to bijective mapping
346             javaToYang.clear();
347             for (String name : assignedNames) {
348                 javaToYang.put(mapEnumAssignedName(name), name);
349             }
350         }
351
352         return javaToYang.inverse();
353     }
354
355     // See https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.8
356     private static boolean isValidJavaIdentifier(final String str) {
357         return !str.isEmpty() && !JAVA_RESERVED_WORDS.contains(str)
358                 && Character.isJavaIdentifierStart(str.codePointAt(0))
359                 && str.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart);
360     }
361
362     private static String mapEnumAssignedName(final String assignedName) {
363         checkArgument(!assignedName.isEmpty());
364
365         // Mapping rules:
366         // - if the string is a valid java identifier and does not contain '$', use it as-is
367         if (assignedName.indexOf('$') == -1 && isValidJavaIdentifier(assignedName)) {
368             return assignedName;
369         }
370
371         // - otherwise prefix it with '$' and replace any invalid character (including '$') with '$XX$', where XX is
372         //   hex-encoded unicode codepoint (including plane, stripping leading zeroes)
373         final StringBuilder sb = new StringBuilder().append('$');
374         assignedName.codePoints().forEachOrdered(codePoint -> {
375             if (codePoint == '$' || !Character.isJavaIdentifierPart(codePoint)) {
376                 sb.append('$').append(Integer.toHexString(codePoint).toUpperCase(Locale.ROOT)).append('$');
377             } else {
378                 sb.appendCodePoint(codePoint);
379             }
380         });
381         return sb.toString();
382     }
383 }