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