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.yangtools.yang.binding;
10 import static com.google.common.base.Preconditions.checkArgument;
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.BiMap;
15 import com.google.common.collect.HashBiMap;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Interner;
18 import com.google.common.collect.Interners;
19 import java.text.SimpleDateFormat;
20 import java.util.Collection;
21 import java.util.Locale;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.QNameModule;
28 public final class BindingMapping {
30 public static final String VERSION = "0.6";
32 public static final Set<String> JAVA_RESERVED_WORDS = ImmutableSet.of(
33 // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.9
34 "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue",
35 "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if",
36 "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private",
37 "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this",
38 "throw", "throws", "transient", "try", "void", "volatile", "while",
39 // FIXME: _ is excluded to retain compatibility with previous releases
41 // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.3
43 // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.7
46 public static final String DATA_ROOT_SUFFIX = "Data";
47 public static final String RPC_SERVICE_SUFFIX = "Service";
48 public static final String NOTIFICATION_LISTENER_SUFFIX = "Listener";
49 public static final String QNAME_STATIC_FIELD_NAME = "QNAME";
50 public static final String PACKAGE_PREFIX = "org.opendaylight.yang.gen.v1";
51 public static final String AUGMENTATION_FIELD = "augmentation";
53 private static final Splitter CAMEL_SPLITTER = Splitter.on(CharMatcher.anyOf(" _.-/").precomputed())
54 .omitEmptyStrings().trimResults();
55 private static final Pattern COLON_SLASH_SLASH = Pattern.compile("://", Pattern.LITERAL);
56 private static final String QUOTED_DOT = Matcher.quoteReplacement(".");
57 private static final Splitter DOT_SPLITTER = Splitter.on('.');
59 public static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl";
60 public static final String MODEL_BINDING_PROVIDER_CLASS_NAME = "$YangModelBindingProvider";
62 public static final String RPC_INPUT_SUFFIX = "Input";
63 public static final String RPC_OUTPUT_SUFFIX = "Output";
65 private static final ThreadLocal<SimpleDateFormat> PACKAGE_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
68 protected SimpleDateFormat initialValue() {
69 return new SimpleDateFormat("yyMMdd");
73 public void set(final SimpleDateFormat value) {
74 throw new UnsupportedOperationException();
78 private static final Interner<String> PACKAGE_INTERNER = Interners.newWeakInterner();
80 private BindingMapping() {
81 throw new UnsupportedOperationException("Utility class should not be instantiated");
84 public static String getRootPackageName(final QName module) {
85 return getRootPackageName(module.getModule());
88 public static String getRootPackageName(final QNameModule module) {
89 checkArgument(module != null, "Module must not be null");
90 checkArgument(module.getRevision() != null, "Revision must not be null");
91 checkArgument(module.getNamespace() != null, "Namespace must not be null");
92 final StringBuilder packageNameBuilder = new StringBuilder();
94 packageNameBuilder.append(BindingMapping.PACKAGE_PREFIX);
95 packageNameBuilder.append('.');
97 String namespace = module.getNamespace().toString();
98 namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
100 final char[] chars = namespace.toCharArray();
101 for (int i = 0; i < chars.length; ++i) {
119 packageNameBuilder.append(chars);
120 if (chars[chars.length - 1] != '.') {
121 packageNameBuilder.append('.');
123 packageNameBuilder.append("rev");
124 packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
125 return normalizePackageName(packageNameBuilder.toString());
128 public static String normalizePackageName(final String packageName) {
129 if (packageName == null) {
133 final StringBuilder builder = new StringBuilder();
134 boolean first = true;
136 for (String p : DOT_SPLITTER.split(packageName.toLowerCase())) {
143 if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
149 // Prevent duplication of input string
150 return PACKAGE_INTERNER.intern(builder.toString());
153 public static String getMethodName(final QName name) {
154 checkArgument(name != null, "Name should not be null.");
155 return getMethodName(name.getLocalName());
158 public static String getClassName(final String localName) {
159 checkArgument(localName != null, "Name should not be null.");
160 return toFirstUpper(toCamelCase(localName));
163 public static String getMethodName(final String yangIdentifier) {
164 checkArgument(yangIdentifier != null,"Identifier should not be null");
165 return toFirstLower(toCamelCase(yangIdentifier));
168 public static String getClassName(final QName name) {
169 checkArgument(name != null, "Name should not be null.");
170 return toFirstUpper(toCamelCase(name.getLocalName()));
173 public static String getGetterSuffix(final QName name) {
174 checkArgument(name != null, "Name should not be null.");
175 final String candidate = toFirstUpper(toCamelCase(name.getLocalName()));
176 return "Class".equals(candidate) ? "XmlClass" : candidate;
179 public static String getPropertyName(final String yangIdentifier) {
180 final String potential = toFirstLower(toCamelCase(yangIdentifier));
181 if ("class".equals(potential)) {
187 private static String toCamelCase(final String rawString) {
188 checkArgument(rawString != null, "String should not be null");
189 Iterable<String> components = CAMEL_SPLITTER.split(rawString);
190 StringBuilder builder = new StringBuilder();
191 for (String comp : components) {
192 builder.append(toFirstUpper(comp));
194 return checkNumericPrefix(builder.toString());
197 private static String checkNumericPrefix(final String rawString) {
198 if (rawString == null || rawString.isEmpty()) {
201 char firstChar = rawString.charAt(0);
202 if (firstChar >= '0' && firstChar <= '9') {
203 return "_" + rawString;
210 * Returns the {@link String} {@code s} with an
211 * {@link Character#isUpperCase(char) upper case} first character. This
212 * function is null-safe.
215 * the string that should get an upper case first character. May
216 * be <code>null</code>.
217 * @return the {@link String} {@code s} with an upper case first character
218 * or <code>null</code> if the input {@link String} {@code s} was
221 public static String toFirstUpper(final String s) {
222 if (s == null || s.length() == 0) {
225 if (Character.isUpperCase(s.charAt(0))) {
228 if (s.length() == 1) {
229 return s.toUpperCase();
231 return s.substring(0, 1).toUpperCase() + s.substring(1);
235 * Returns the {@link String} {@code s} with an
236 * {@link Character#isLowerCase(char) lower case} first character. This
237 * function is null-safe.
240 * the string that should get an lower case first character. May
241 * be <code>null</code>.
242 * @return the {@link String} {@code s} with an lower case first character
243 * or <code>null</code> if the input {@link String} {@code s} was
246 private static String toFirstLower(final String s) {
247 if (s == null || s.length() == 0) {
250 if (Character.isLowerCase(s.charAt(0))) {
253 if (s.length() == 1) {
254 return s.toLowerCase();
256 return s.substring(0, 1).toLowerCase() + s.substring(1);
260 * Returns Java identifiers, conforming to JLS8 Section 3.8 to use for specified YANG assigned names
261 * (RFC7950 Section 9.6.4). This method considers two distinct encodings: one the pre-Fluorine mapping, which is
262 * okay and convenient for sane strings, and an escaping-based bijective mapping which works for all possible
265 * @param assignedNames Collection of assigned names
266 * @return A BiMap keyed by assigned name, with Java identifiers as values
267 * @throws NullPointerException if assignedNames is null or contains null items
268 * @throws IllegalArgumentException if any of the names is empty
270 public static BiMap<String, String> mapEnumAssignedNames(final Collection<String> assignedNames) {
272 * Original mapping assumed strings encountered are identifiers, hence it used getClassName to map the names
273 * and that function is not an injection -- this is evidenced in MDSAL-208 and results in a failure to compile
274 * generated code. If we encounter such a conflict or if the result is not a valid identifier (like '*'), we
275 * abort and switch the mapping schema to mapEnumAssignedName(), which is a bijection.
277 * Note that assignedNames can contain duplicates, which must not trigger a duplication fallback.
279 final BiMap<String, String> javaToYang = HashBiMap.create(assignedNames.size());
280 boolean valid = true;
281 for (String name : assignedNames) {
282 checkArgument(!name.isEmpty());
283 if (!javaToYang.containsValue(name)) {
284 final String mappedName = getClassName(name);
285 if (!isValidJavaIdentifier(mappedName) || javaToYang.forcePut(mappedName, name) != null) {
293 // Fall back to bijective mapping
295 for (String name : assignedNames) {
296 javaToYang.put(mapEnumAssignedName(name), name);
300 return javaToYang.inverse();
303 // See https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.8
304 private static boolean isValidJavaIdentifier(final String str) {
305 return !str.isEmpty() && !JAVA_RESERVED_WORDS.contains(str)
306 && Character.isJavaIdentifierStart(str.codePointAt(0))
307 && str.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart);
310 private static String mapEnumAssignedName(final String assignedName) {
311 checkArgument(!assignedName.isEmpty());
314 // - if the string is a valid java identifier and does not contain '$', use it as-is
315 if (assignedName.indexOf('$') == -1 && isValidJavaIdentifier(assignedName)) {
319 // - otherwise prefix it with '$' and replace any invalid character (including '$') with '$XX$', where XX is
320 // hex-encoded unicode codepoint (including plane, stripping leading zeroes)
321 final StringBuilder sb = new StringBuilder().append('$');
322 assignedName.codePoints().forEachOrdered(codePoint -> {
323 if (codePoint == '$' || !Character.isJavaIdentifierPart(codePoint)) {
324 sb.append('$').append(Integer.toHexString(codePoint).toUpperCase(Locale.ROOT)).append('$');
326 sb.appendCodePoint(codePoint);
329 return sb.toString();