2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.spec.naming;
10 import static com.google.common.base.Preconditions.checkArgument;
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;
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;
33 public final class BindingMapping {
35 public static final String VERSION = "0.6";
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
46 // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.7
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";
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('.');
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";
67 * Name of {@link Augmentable#augmentation(Class)}.
69 public static final String AUGMENTABLE_AUGMENTATION_NAME = "augmentation";
72 * Name of {@link Identifiable#key()}.
74 public static final String IDENTIFIABLE_KEY_NAME = "key";
77 * Prefix for getter methods working on top of boolean.
79 public static final String BOOLEAN_GETTER_PREFIX = "is";
82 * Prefix for normal getter methods.
84 public static final String GETTER_PREFIX = "get";
86 public static final String RPC_INPUT_SUFFIX = "Input";
87 public static final String RPC_OUTPUT_SUFFIX = "Output";
89 private static final Interner<String> PACKAGE_INTERNER = Interners.newWeakInterner();
91 private BindingMapping() {
92 throw new UnsupportedOperationException("Utility class should not be instantiated");
95 public static String getRootPackageName(final QName module) {
96 return getRootPackageName(module.getModule());
99 public static String getRootPackageName(final QNameModule module) {
100 checkArgument(module != null, "Module must not be null");
101 checkArgument(module.getRevision() != null, "Revision must not be null");
102 checkArgument(module.getNamespace() != null, "Namespace must not be null");
103 final StringBuilder packageNameBuilder = new StringBuilder();
105 packageNameBuilder.append(BindingMapping.PACKAGE_PREFIX);
106 packageNameBuilder.append('.');
108 String namespace = module.getNamespace().toString();
109 namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
111 final char[] chars = namespace.toCharArray();
112 for (int i = 0; i < chars.length; ++i) {
133 packageNameBuilder.append(chars);
134 if (chars[chars.length - 1] != '.') {
135 packageNameBuilder.append('.');
138 final Optional<Revision> optRev = module.getRevision();
139 if (optRev.isPresent()) {
140 // Revision is in format 2017-10-26, we want the output to be 171026, which is a matter of picking the
142 final String rev = optRev.get().toString();
143 checkArgument(rev.length() == 10, "Unsupported revision %s", rev);
144 packageNameBuilder.append("rev").append(rev, 2, 4).append(rev, 5, 7).append(rev.substring(8));
146 // No-revision packages are special
147 packageNameBuilder.append("norev");
150 return normalizePackageName(packageNameBuilder.toString());
153 public static String normalizePackageName(final String packageName) {
154 if (packageName == null) {
158 final StringBuilder builder = new StringBuilder();
159 boolean first = true;
161 for (String p : DOT_SPLITTER.split(packageName.toLowerCase(Locale.ENGLISH))) {
168 if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
174 // Prevent duplication of input string
175 return PACKAGE_INTERNER.intern(builder.toString());
178 public static String getClassName(final String localName) {
179 checkArgument(localName != null, "Name should not be null.");
180 return toFirstUpper(toCamelCase(localName));
183 public static String getClassName(final QName name) {
184 checkArgument(name != null, "Name should not be null.");
185 return toFirstUpper(toCamelCase(name.getLocalName()));
188 public static String getMethodName(final String yangIdentifier) {
189 checkArgument(yangIdentifier != null,"Identifier should not be null");
190 return toFirstLower(toCamelCase(yangIdentifier));
193 public static String getMethodName(final QName name) {
194 checkArgument(name != null, "Name should not be null.");
195 return getMethodName(name.getLocalName());
198 public static String getGetterPrefix(final boolean isBoolean) {
199 return isBoolean ? BOOLEAN_GETTER_PREFIX : GETTER_PREFIX;
202 public static String getGetterMethodName(final String localName, final boolean isBoolean) {
203 return getGetterPrefix(isBoolean) + toFirstUpper(getPropertyName(localName));
206 public static String getGetterMethodName(final QName name, final boolean isBoolean) {
207 return getGetterPrefix(isBoolean) + getGetterSuffix(name);
210 public static boolean isGetterMethodName(final String methodName) {
211 return methodName.startsWith(GETTER_PREFIX) || methodName.startsWith(BOOLEAN_GETTER_PREFIX);
214 public static String getGetterSuffix(final QName name) {
215 checkArgument(name != null, "Name should not be null.");
216 final String candidate = toFirstUpper(toCamelCase(name.getLocalName()));
217 return "Class".equals(candidate) ? "XmlClass" : candidate;
220 public static String getPropertyName(final String yangIdentifier) {
221 final String potential = toFirstLower(toCamelCase(yangIdentifier));
222 if ("class".equals(potential)) {
228 private static String toCamelCase(final String rawString) {
229 checkArgument(rawString != null, "String should not be null");
230 Iterable<String> components = CAMEL_SPLITTER.split(rawString);
231 StringBuilder builder = new StringBuilder();
232 for (String comp : components) {
233 builder.append(toFirstUpper(comp));
235 return checkNumericPrefix(builder.toString());
238 private static String checkNumericPrefix(final String rawString) {
239 if (rawString == null || rawString.isEmpty()) {
242 final char firstChar = rawString.charAt(0);
243 return firstChar >= '0' && firstChar <= '9' ? "_" + rawString : rawString;
247 * Returns the {@link String} {@code s} with an {@link Character#isUpperCase(char) upper case} first character. This
248 * function is null-safe.
250 * @param str the string that should get an upper case first character. May be <code>null</code>.
251 * @return the {@link String} {@code str} with an upper case first character or <code>null</code> if the input
252 * {@link String} {@code str} was <code>null</code>.
254 public static String toFirstUpper(final String str) {
255 if (str == null || str.length() == 0) {
258 if (Character.isUpperCase(str.charAt(0))) {
261 if (str.length() == 1) {
262 return str.toUpperCase(Locale.ENGLISH);
264 return str.substring(0, 1).toUpperCase(Locale.ENGLISH) + str.substring(1);
268 * Returns the {@link String} {@code s} with a {@link Character#isLowerCase(char) lower case} first character. This
269 * function is null-safe.
271 * @param str the string that should get an lower case first character. May be <code>null</code>.
272 * @return the {@link String} {@code str} with an lower case first character or <code>null</code> if the input
273 * {@link String} {@code str} was <code>null</code>.
275 private static String toFirstLower(final String str) {
276 if (str == null || str.length() == 0) {
279 if (Character.isLowerCase(str.charAt(0))) {
282 if (str.length() == 1) {
283 return str.toLowerCase(Locale.ENGLISH);
285 return str.substring(0, 1).toLowerCase(Locale.ENGLISH) + str.substring(1);
289 * Returns Java identifiers, conforming to JLS9 Section 3.8 to use for specified YANG assigned names
290 * (RFC7950 Section 9.6.4). This method considers two distinct encodings: one the pre-Fluorine mapping, which is
291 * okay and convenient for sane strings, and an escaping-based bijective mapping which works for all possible
294 * @param assignedNames Collection of assigned names
295 * @return A BiMap keyed by assigned name, with Java identifiers as values
296 * @throws NullPointerException if assignedNames is null or contains null items
297 * @throws IllegalArgumentException if any of the names is empty
299 public static BiMap<String, String> mapEnumAssignedNames(final Collection<String> assignedNames) {
301 * Original mapping assumed strings encountered are identifiers, hence it used getClassName to map the names
302 * and that function is not an injection -- this is evidenced in MDSAL-208 and results in a failure to compile
303 * generated code. If we encounter such a conflict or if the result is not a valid identifier (like '*'), we
304 * abort and switch the mapping schema to mapEnumAssignedName(), which is a bijection.
306 * Note that assignedNames can contain duplicates, which must not trigger a duplication fallback.
308 final BiMap<String, String> javaToYang = HashBiMap.create(assignedNames.size());
309 boolean valid = true;
310 for (String name : assignedNames) {
311 checkArgument(!name.isEmpty());
312 if (!javaToYang.containsValue(name)) {
313 final String mappedName = getClassName(name);
314 if (!isValidJavaIdentifier(mappedName) || javaToYang.forcePut(mappedName, name) != null) {
322 // Fall back to bijective mapping
324 for (String name : assignedNames) {
325 javaToYang.put(mapEnumAssignedName(name), name);
329 return javaToYang.inverse();
332 // See https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.8
333 private static boolean isValidJavaIdentifier(final String str) {
334 return !str.isEmpty() && !JAVA_RESERVED_WORDS.contains(str)
335 && Character.isJavaIdentifierStart(str.codePointAt(0))
336 && str.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart);
339 private static String mapEnumAssignedName(final String assignedName) {
340 checkArgument(!assignedName.isEmpty());
343 // - if the string is a valid java identifier and does not contain '$', use it as-is
344 if (assignedName.indexOf('$') == -1 && isValidJavaIdentifier(assignedName)) {
348 // - otherwise prefix it with '$' and replace any invalid character (including '$') with '$XX$', where XX is
349 // hex-encoded unicode codepoint (including plane, stripping leading zeroes)
350 final StringBuilder sb = new StringBuilder().append('$');
351 assignedName.codePoints().forEachOrdered(codePoint -> {
352 if (codePoint == '$' || !Character.isJavaIdentifierPart(codePoint)) {
353 sb.append('$').append(Integer.toHexString(codePoint).toUpperCase(Locale.ROOT)).append('$');
355 sb.appendCodePoint(codePoint);
358 return sb.toString();