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.eclipse.jdt.annotation.NonNull;
27 import org.opendaylight.yangtools.yang.binding.Augmentable;
28 import org.opendaylight.yangtools.yang.binding.DataContainer;
29 import org.opendaylight.yangtools.yang.binding.Identifiable;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.QNameModule;
32 import org.opendaylight.yangtools.yang.common.Revision;
35 public final class BindingMapping {
37 public static final @NonNull String VERSION = "0.6";
39 public static final Set<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
48 // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.7
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";
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('.');
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";
69 * Name of {@link Augmentable#augmentation(Class)}.
71 public static final @NonNull String AUGMENTABLE_AUGMENTATION_NAME = "augmentation";
74 * Name of {@link Identifiable#key()}.
76 public static final @NonNull String IDENTIFIABLE_KEY_NAME = "key";
79 * Name of {@link DataContainer#implementedInterface()}.
81 public static final @NonNull String DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME = "implementedInterface";
84 * Prefix for getter methods working on top of boolean.
86 public static final @NonNull String BOOLEAN_GETTER_PREFIX = "is";
89 * Prefix for normal getter methods.
91 public static final @NonNull String GETTER_PREFIX = "get";
94 * Prefix for non-null default wrapper methods. These methods always wrap a corresponding normal getter.
96 public static final @NonNull String NONNULL_PREFIX = "nonnull";
98 public static final @NonNull String RPC_INPUT_SUFFIX = "Input";
99 public static final @NonNull String RPC_OUTPUT_SUFFIX = "Output";
101 private static final Interner<String> PACKAGE_INTERNER = Interners.newWeakInterner();
103 private BindingMapping() {
104 throw new UnsupportedOperationException("Utility class should not be instantiated");
107 public static @NonNull String getRootPackageName(final QName module) {
108 return getRootPackageName(module.getModule());
111 public static @NonNull String getRootPackageName(final QNameModule module) {
112 final StringBuilder packageNameBuilder = new StringBuilder().append(BindingMapping.PACKAGE_PREFIX).append('.');
114 String namespace = module.getNamespace().toString();
115 namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
117 final char[] chars = namespace.toCharArray();
118 for (int i = 0; i < chars.length; ++i) {
139 packageNameBuilder.append(chars);
140 if (chars[chars.length - 1] != '.') {
141 packageNameBuilder.append('.');
144 final Optional<Revision> optRev = module.getRevision();
145 if (optRev.isPresent()) {
146 // Revision is in format 2017-10-26, we want the output to be 171026, which is a matter of picking the
148 final String rev = optRev.get().toString();
149 checkArgument(rev.length() == 10, "Unsupported revision %s", rev);
150 packageNameBuilder.append("rev").append(rev, 2, 4).append(rev, 5, 7).append(rev.substring(8));
152 // No-revision packages are special
153 packageNameBuilder.append("norev");
156 return normalizePackageName(packageNameBuilder.toString());
159 public static @NonNull String normalizePackageName(final String packageName) {
160 final StringBuilder builder = new StringBuilder();
161 boolean first = true;
163 for (String p : DOT_SPLITTER.split(packageName.toLowerCase(Locale.ENGLISH))) {
170 if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
176 // Prevent duplication of input string
177 return PACKAGE_INTERNER.intern(builder.toString());
180 public static @NonNull String getClassName(final String localName) {
181 return toFirstUpper(toCamelCase(localName));
184 public static @NonNull String getClassName(final QName name) {
185 return toFirstUpper(toCamelCase(name.getLocalName()));
188 public static @NonNull String getMethodName(final String yangIdentifier) {
189 return toFirstLower(toCamelCase(yangIdentifier));
192 public static @NonNull String getMethodName(final QName name) {
193 return getMethodName(name.getLocalName());
196 public static @NonNull String getGetterPrefix(final boolean isBoolean) {
197 return isBoolean ? BOOLEAN_GETTER_PREFIX : GETTER_PREFIX;
200 public static @NonNull String getGetterMethodName(final String localName, final boolean isBoolean) {
201 return getGetterPrefix(isBoolean) + toFirstUpper(getPropertyName(localName));
204 public static @NonNull String getGetterMethodName(final QName name, final boolean isBoolean) {
205 return getGetterPrefix(isBoolean) + getGetterSuffix(name);
208 public static boolean isGetterMethodName(final String methodName) {
209 return methodName.startsWith(GETTER_PREFIX) || methodName.startsWith(BOOLEAN_GETTER_PREFIX);
212 public static @NonNull String getGetterMethodForNonnull(final String methodName) {
213 checkArgument(isNonnullMethodName(methodName));
214 return GETTER_PREFIX + methodName.substring(NONNULL_PREFIX.length());
217 public static @NonNull String getNonnullMethodName(final String localName) {
218 return NONNULL_PREFIX + toFirstUpper(getPropertyName(localName));
221 public static boolean isNonnullMethodName(final String methodName) {
222 return methodName.startsWith(NONNULL_PREFIX);
225 public static @NonNull String getGetterSuffix(final QName name) {
226 final String candidate = toFirstUpper(toCamelCase(name.getLocalName()));
227 return "Class".equals(candidate) ? "XmlClass" : candidate;
230 public static @NonNull String getPropertyName(final String yangIdentifier) {
231 final String potential = toFirstLower(toCamelCase(yangIdentifier));
232 if ("class".equals(potential)) {
238 private static @NonNull String toCamelCase(final String rawString) {
239 StringBuilder builder = new StringBuilder();
240 for (String comp : CAMEL_SPLITTER.split(rawString)) {
241 builder.append(toFirstUpper(comp));
243 return checkNumericPrefix(builder.toString());
246 private static @NonNull String checkNumericPrefix(final String rawString) {
247 if (rawString.isEmpty()) {
250 final char firstChar = rawString.charAt(0);
251 return firstChar >= '0' && firstChar <= '9' ? "_" + rawString : rawString;
255 * Returns the {@link String} {@code s} with an {@link Character#isUpperCase(char) upper case} first character.
257 * @param str the string that should get an upper case first character.
258 * @return the {@link String} {@code str} with an upper case first character.
260 private static @NonNull String toFirstUpper(final @NonNull String str) {
264 if (Character.isUpperCase(str.charAt(0))) {
267 if (str.length() == 1) {
268 return str.toUpperCase(Locale.ENGLISH);
270 return str.substring(0, 1).toUpperCase(Locale.ENGLISH) + str.substring(1);
274 * Returns the {@link String} {@code s} with a {@link Character#isLowerCase(char) lower case} first character. This
275 * function is null-safe.
277 * @param str the string that should get an lower case first character. May be <code>null</code>.
278 * @return the {@link String} {@code str} with an lower case first character or <code>null</code> if the input
279 * {@link String} {@code str} was empty.
281 private static @NonNull String toFirstLower(final @NonNull String str) {
285 if (Character.isLowerCase(str.charAt(0))) {
288 if (str.length() == 1) {
289 return str.toLowerCase(Locale.ENGLISH);
291 return str.substring(0, 1).toLowerCase(Locale.ENGLISH) + str.substring(1);
295 * Returns Java identifiers, conforming to JLS9 Section 3.8 to use for specified YANG assigned names
296 * (RFC7950 Section 9.6.4). This method considers two distinct encodings: one the pre-Fluorine mapping, which is
297 * okay and convenient for sane strings, and an escaping-based bijective mapping which works for all possible
300 * @param assignedNames Collection of assigned names
301 * @return A BiMap keyed by assigned name, with Java identifiers as values
302 * @throws NullPointerException if assignedNames is null or contains null items
303 * @throws IllegalArgumentException if any of the names is empty
305 public static BiMap<String, String> mapEnumAssignedNames(final Collection<String> assignedNames) {
307 * Original mapping assumed strings encountered are identifiers, hence it used getClassName to map the names
308 * and that function is not an injection -- this is evidenced in MDSAL-208 and results in a failure to compile
309 * generated code. If we encounter such a conflict or if the result is not a valid identifier (like '*'), we
310 * abort and switch the mapping schema to mapEnumAssignedName(), which is a bijection.
312 * Note that assignedNames can contain duplicates, which must not trigger a duplication fallback.
314 final BiMap<String, String> javaToYang = HashBiMap.create(assignedNames.size());
315 boolean valid = true;
316 for (String name : assignedNames) {
317 checkArgument(!name.isEmpty());
318 if (!javaToYang.containsValue(name)) {
319 final String mappedName = getClassName(name);
320 if (!isValidJavaIdentifier(mappedName) || javaToYang.forcePut(mappedName, name) != null) {
328 // Fall back to bijective mapping
330 for (String name : assignedNames) {
331 javaToYang.put(mapEnumAssignedName(name), name);
335 return javaToYang.inverse();
338 // See https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.8
339 private static boolean isValidJavaIdentifier(final String str) {
340 return !str.isEmpty() && !JAVA_RESERVED_WORDS.contains(str)
341 && Character.isJavaIdentifierStart(str.codePointAt(0))
342 && str.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart);
345 private static String mapEnumAssignedName(final String assignedName) {
346 checkArgument(!assignedName.isEmpty());
349 // - if the string is a valid java identifier and does not contain '$', use it as-is
350 if (assignedName.indexOf('$') == -1 && isValidJavaIdentifier(assignedName)) {
354 // - otherwise prefix it with '$' and replace any invalid character (including '$') with '$XX$', where XX is
355 // hex-encoded unicode codepoint (including plane, stripping leading zeroes)
356 final StringBuilder sb = new StringBuilder().append('$');
357 assignedName.codePoints().forEachOrdered(codePoint -> {
358 if (codePoint == '$' || !Character.isJavaIdentifierPart(codePoint)) {
359 sb.append('$').append(Integer.toHexString(codePoint).toUpperCase(Locale.ROOT)).append('$');
361 sb.appendCodePoint(codePoint);
364 return sb.toString();