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