2 * Copyright (c) 2017 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.javav2.generator.util;
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.CharMatcher;
12 import com.google.common.base.Splitter;
13 import com.google.common.collect.ArrayListMultimap;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.collect.ListMultimap;
16 import java.util.Iterator;
17 import java.util.List;
19 import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration;
20 import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration.Pair;
21 import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
24 * This util class converts every non-java char in identifier to java char by
25 * its unicode name (<a href=
26 * "http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.8">JAVA SE
27 * SPECIFICATIONS - Identifiers</a>). There are special types of mapping
28 * non-java chars to original identifiers according to specific
29 * {@linkplain JavaIdentifier java type}:
31 * <li>class, enum, interface</li>
34 * <li>without special separator</li>
35 * <li>the first character of identifier, any other first character of
36 * identifier part mapped by non-Java char name from unicode and char in
37 * identifier behind non-java char name are converting to upper case</li>
41 * <li>example* - ExampleAsterisk</li>
42 * <li>example*example - ExampleAserisksExample</li>
43 * <li>\example - ReverseSolidusExample</li>
44 * <li>1example - DigitOneExample</li>
45 * <li>example1 - Example1</li>
46 * <li>int - IntReservedKeyword</li>
47 * <li>con - ConReservedKeyword</li>
52 * <li>enum value, constant</li>
55 * <li>used underscore as special separator</li>
56 * <li>converted identifier to upper case</li>
60 * <li>example* - EXAMPLE_ASTERISK</li>
61 * <li>example*example - EXAMPLE_ASTERISK_EXAMPLE</li>
62 * <li>\example - REVERSE_SOLIDUS_EXAMPLE</li>
63 * <li>1example - DIGIT_ONE_EXAMPLE</li>
64 * <li>example1 - EXAMPLE1</li>
65 * <li>int - INT_RESERVED_KEYWORD</li>
66 * <li>con - CON_RESERVED_KEYWORD</li>
71 * <li>method, variable</li>
75 * <li>without special separator</li>
76 * <li>the first character of identifier is converting to lower case</li>
77 * <li>any other first character of identifier part mapped by non-Java char name
78 * from unicode and char in identifier behind non-java char name are converting
83 * <li>example* - exampleAsterisk</li>
84 * <li>example*example - exampleAserisksExample</li>
85 * <li>\example - reverseSolidusExample</li>
86 * <li>1example - digitOneExample</li>
87 * <li>example1 - example1</li>
88 * <li>int - intReservedKeyword</li>
89 * <li>con - conReservedKeyword</li>
94 * <li>package - full package name (<a href=
95 * "https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html">
96 * Naming a package</a>)</li>
100 * <li>parts of package name are separated by dots</li>
101 * <li>parts of package name are converting to lower case</li>
102 * <li>if parts of package name are reserved Java or Windows keywords, such as
103 * 'int' the suggested convention is to add an underscore to keyword</li>
104 * <li>dash is parsed as underscore according to <a href=
105 * "https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html">
106 * Naming a package</a></li>
110 * <li>org.example* - org.exampleasterisk</li>
111 * <li>org.example*example - org.exampleasteriskexample</li>
112 * <li>org.\example - org.reversesolidusexample</li>
113 * <li>org.1example - org.digitoneexample</li>
114 * <li>org.example1 - org.example1</li>
115 * <li>org.int - org.int_</li>
116 * <li>org.con - org.con_</li>
117 * <li>org.foo-cont - org.foo_cont</li>
124 * There is special case in CLASS, INTERFACE, ENUM, ENUM VALUE, CONSTANT, METHOD
125 * and VARIABLE if identifier contains single dash - then the converter ignores
126 * the single dash in the way of the non-java chars. In other way, if dash is
127 * the first or the last char in the identifier or there is more dashes in a row
128 * in the identifier, then these dashes are converted as non-java chars.
131 * <li>class, enum, interface</li>
134 * <li>foo-cont - FooCont</li>
135 * <li>foo--cont - FooHyphenMinusHyphenMinusCont</li>
136 * <li>-foo - HyphenMinusFoo</li>
137 * <li>foo- - FooHyphenMinus</li>
140 * <li>enum value, constant
143 * <li>foo-cont - FOO_CONT</li>
144 * <li>foo--cont - FOO_HYPHEN_MINUS_HYPHEN_MINUS_CONT</li>
145 * <li>-foo - HYPHEN_MINUS_FOO</li>
146 * <li>foo- - FOO_HYPHEN_MINUS</li>
149 * <li>method, variable</li>
152 * <li>foo-cont - fooCont</li>
153 * <li>foo--cont - fooHyphenMinusHyphenMinusCont</li>
154 * <li>-foo - hyphenMinusFoo</li>
155 * <li>foo- - fooHyphenMinus</li>
160 * Next special case talks about normalizing class name which already exists in
161 * package - but with different camel cases (foo, Foo, fOo, ...). To every next
162 * classes with same names will by added their actual rank (serial number),
163 * except the first one. This working for CLASS, ENUM and INTEFACE java
164 * identifiers. If there exist the same ENUM VALUES in ENUM (with different
165 * camel cases), then it's parsed with same logic like CLASSES, ENUMS and
166 * INTERFACES but according to list of pairs of their ENUM parent. Example:
169 * <li>class, enum, interface</li>
172 * <li>package name org.example, class (or interface or enum) Foo - normalized
174 * <li>package name org.example, class (or interface or enum) fOo - normalized
178 * <li>enum value</li>
191 * <li>YANG enum values will be mapped to 'FOO' and 'FOO_1' Java enum
198 public final class JavaIdentifierNormalizer {
200 public static final Set<String> SPECIAL_RESERVED_PATHS = ImmutableSet.of(
201 "org.opendaylight.yangtools.concepts",
202 "org.opendaylight.yangtools.yang.common",
203 "org.opendaylight.yangtools.yang.model",
204 "org.opendaylight.mdsal.binding.javav2.spec",
208 private static final int FIRST_CHAR = 0;
209 private static final int FIRST_INDEX = 1;
210 private static final char UNDERSCORE = '_';
211 private static final char DASH = '-';
212 private static final String EMPTY_STRING = "";
213 private static final String RESERVED_KEYWORD = "reserved_keyword";
214 private static final ListMultimap<String, String> PACKAGES_MAP = ArrayListMultimap.create();
215 private static final Set<String> PRIMITIVE_TYPES = ImmutableSet.of("char[]", "byte[]");
217 private static final CharMatcher DASH_MATCHER = CharMatcher.is(DASH);
218 private static final Splitter DOT_SPLITTER = Splitter.on('.');
220 private JavaIdentifierNormalizer() {
221 throw new UnsupportedOperationException("Util class");
226 * According to <a href="https://tools.ietf.org/html/rfc7950#section-9.6.4">YANG RFC 7950</a>,
227 * all assigned names in an enumeration MUST be unique. Created names are contained in the list
228 * of {@link Enumeration.Pair}. This method adds actual index with underscore behind name of new
229 * enum value only if this name already exists in one of the list of {@link Enumeration.Pair}.
230 * Then, the name will be converted to java chars according to {@link JavaIdentifier#ENUM_VALUE}
242 * YANG enum values will be mapped to 'FOO' and 'FOO_1' Java enum values.
245 * - name of new enum value
247 * - list of all actual enum values
248 * @return converted and fixed name of new enum value
250 public static String normalizeEnumValueIdentifier(final String name, final List<Pair> values) {
251 return convertIdentifierEnumValue(name, name, values, FIRST_INDEX);
255 * Normalizing full package name by non java chars and reserved keywords.
257 * @param fullPackageName
258 * - full package name
259 * @return normalized name
261 public static String normalizeFullPackageName(final String fullPackageName) {
262 final Iterator<String> it = DOT_SPLITTER.split(fullPackageName).iterator();
264 return fullPackageName;
267 final StringBuilder sb = new StringBuilder(fullPackageName.length());
269 sb.append(normalizePartialPackageName(it.next()));
271 return sb.toString();
278 * Normalizing part of package name by non java chars.
280 * @param packageNamePart
281 * - part of package name
282 * @return normalized name
284 public static String normalizePartialPackageName(final String packageNamePart) {
285 // if part of package name consist from java or windows reserved word, return it with
286 // underscore at the end and in lower case
287 final String lowerPart = packageNamePart.toLowerCase();
288 if (BindingMapping.JAVA_RESERVED_WORDS.contains(lowerPart)
289 || BindingMapping.WINDOWS_RESERVED_WORDS.contains(packageNamePart.toUpperCase())) {
290 return lowerPart + UNDERSCORE;
293 final String normalizedPart = DASH_MATCHER.replaceFrom(packageNamePart, UNDERSCORE);
295 final StringBuilder sb = new StringBuilder();
296 final StringBuilder innerSb = new StringBuilder();
297 for (int i = 0; i < normalizedPart.length(); i++) {
298 final char c = normalizedPart.charAt(i);
299 if (c == UNDERSCORE) {
300 if (innerSb.length() != 0) {
301 sb.append(normalizeSpecificIdentifier(innerSb.toString(), JavaIdentifier.PACKAGE));
302 innerSb.setLength(0);
304 sb.append(UNDERSCORE);
309 if (innerSb.length() != 0) {
310 sb.append(normalizeSpecificIdentifier(innerSb.toString(), JavaIdentifier.PACKAGE));
312 // returned normalized part of package name
313 return sb.toString();
317 * Find and convert non Java chars in identifiers of generated transfer objects, initially
318 * derived from corresponding YANG according to
319 * <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.8"> Java
320 * Specifications - Identifiers</a>. If there is more same class names at the same package, then
321 * append rank (serial number) to the end of them. Works for class, enum, interface.
324 * - package of identifier
326 * - name of identifier
327 * @return - java acceptable identifier
329 public static String normalizeClassIdentifier(final String packageName, final String className) {
330 if (packageName.isEmpty() && PRIMITIVE_TYPES.contains(className)) {
333 for (final String reservedPath : SPECIAL_RESERVED_PATHS) {
334 if (packageName.startsWith(reservedPath)) {
338 final String convertedClassName = normalizeSpecificIdentifier(className, JavaIdentifier.CLASS);
339 // if packageName contains class name at the end, then the className is
340 // name of inner class
341 final String[] packageNameParts = packageName.split("\\.");
342 String suppInnerClassPackageName = packageName;
343 if (packageNameParts.length > 1) {
344 if (Character.isUpperCase(packageNameParts[packageNameParts.length - 1].charAt(FIRST_CHAR))) {
345 final StringBuilder sb = new StringBuilder();
346 // ignore class name in package name - inner class name has
347 // to be normalizing according to original package of parent
349 for (int i = 0; i < packageNameParts.length - 1; i++) {
350 if (!Character.isUpperCase(packageNameParts[i].charAt(FIRST_CHAR))) {
351 sb.append(packageNameParts[i]);
352 if (i != packageNameParts.length - 2 &&
353 !Character.isUpperCase(packageNameParts[i+1].charAt(FIRST_CHAR))) {
360 suppInnerClassPackageName = sb.toString();
364 return normalizeClassIdentifier(suppInnerClassPackageName, convertedClassName, convertedClassName, FIRST_INDEX);
368 * Find and convert non Java chars in identifiers of generated transfer objects, initially
369 * derived from corresponding YANG.
372 * - name of identifier
373 * @param javaIdentifier
374 * - java type of identifier
375 * @return - java acceptable identifier
377 public static String normalizeSpecificIdentifier(final String identifier, final JavaIdentifier javaIdentifier) {
378 final StringBuilder sb = new StringBuilder();
380 // if identifier isn't PACKAGE type then check it by reserved keywords
381 if(javaIdentifier != JavaIdentifier.PACKAGE) {
382 if (BindingMapping.JAVA_RESERVED_WORDS.contains(identifier.toLowerCase())
383 || BindingMapping.WINDOWS_RESERVED_WORDS.contains(identifier.toUpperCase())) {
384 return fixCasesByJavaType(
385 sb.append(identifier).append(UNDERSCORE).append(RESERVED_KEYWORD).toString().toLowerCase(),
390 // check and convert first char in identifier if there is non-java char
391 final char firstChar = identifier.charAt(FIRST_CHAR);
392 if (!Character.isJavaIdentifierStart(firstChar)) {
393 // converting first char of identifier
394 sb.append(convertFirst(firstChar, existNext(identifier, FIRST_CHAR)));
396 sb.append(firstChar);
398 // check and convert other chars in identifier, if there is non-java char
399 for (int i = 1; i < identifier.length(); i++) {
400 final char actualChar = identifier.charAt(i);
401 // ignore single dash as non java char - if there is more dashes in a row or dash is as
402 // the last char in identifier then parse these dashes as non java chars
403 if (actualChar == '-' && existNext(identifier, i)) {
404 if (identifier.charAt(i - 1) != DASH && identifier.charAt(i + 1) != DASH) {
405 sb.append(UNDERSCORE);
409 if (!Character.isJavaIdentifierPart(actualChar)) {
410 // prepare actual string of sb for checking if underscore exist on position of the
412 final String partialConvertedIdentifier = sb.toString();
413 sb.append(convert(actualChar, existNext(identifier, i),
414 partialConvertedIdentifier.charAt(partialConvertedIdentifier.length() - 1)));
416 sb.append(actualChar);
419 // apply camel case in appropriate way
420 return fixCasesByJavaType(sb.toString().replace("__", "_").toLowerCase(), javaIdentifier);
424 * Checking while there doesn't exist any class name with the same name
425 * (regardless of camel cases) in package.
428 * - package of class name
429 * @param origClassName
430 * - original class name
431 * @param actualClassName
432 * - actual class name with rank (serial number)
434 * - actual rank (serial number)
435 * @return converted identifier
437 private static String normalizeClassIdentifier(final String packageName, final String origClassName,
438 final String actualClassName, final int rank) {
439 if (PACKAGES_MAP.containsKey(packageName)) {
440 for (final String existingName : PACKAGES_MAP.get(packageName)) {
441 if (existingName.toLowerCase().equals(actualClassName.toLowerCase())) {
442 final int nextRank = rank + 1;
443 return normalizeClassIdentifier(packageName, origClassName,
444 new StringBuilder(origClassName).append(rank).toString(), nextRank);
448 PACKAGES_MAP.put(packageName, actualClassName);
449 return actualClassName;
453 * Fix cases of converted identifiers by Java type
456 * - converted identifier
457 * @param javaIdentifier
458 * - java type of identifier
459 * @return converted identifier with right cases according to java type
461 private static String fixCasesByJavaType(final String convertedIdentifier, final JavaIdentifier javaIdentifier) {
462 switch (javaIdentifier) {
466 return capitalize(fixCases(convertedIdentifier));
469 return convertedIdentifier.toUpperCase();
472 return fixCases(convertedIdentifier);
474 return convertedIdentifier.replaceAll(String.valueOf(UNDERSCORE), EMPTY_STRING);
476 throw new IllegalArgumentException("Unknown java type of identifier : " + javaIdentifier.toString());
481 * Delete unnecessary chars in converted identifier and apply camel case in appropriate way.
483 * @param convertedIdentifier
484 * - original converted identifier
485 * @return resolved identifier
487 private static String fixCases(final String convertedIdentifier) {
488 final StringBuilder sb = new StringBuilder();
489 if (convertedIdentifier.contains(String.valueOf(UNDERSCORE))) {
490 boolean isFirst = true;
491 for (final String part : convertedIdentifier.split(String.valueOf(UNDERSCORE))) {
496 sb.append(capitalize(part));
500 sb.append(convertedIdentifier);
502 return sb.toString();
506 * Check if there exist next char in identifier behind actual char position
509 * - original identifier
511 * - actual char position
512 * @return true if there is another char, false otherwise
514 private static boolean existNext(final String identifier, final int actual) {
515 return identifier.length() > actual + 1;
519 * Converting first char of identifier. This happen only if this char is
525 * - existing of next char behind actual char
526 * @return converted char
528 private static String convertFirst(final char c, final boolean existNext) {
529 String name = Character.getName(c);
530 if (name.contains(String.valueOf(DASH))) {
531 name = name.replaceAll(String.valueOf(DASH), String.valueOf(UNDERSCORE));
533 name = existNext ? name + "_" : name;
534 return name.contains(" ") ? name.replaceAll(" ", "_") : name;
538 * Converting any char in java identifier, This happen only if this char is
544 * - existing of next char behind actual char
545 * @param partialLastChar
546 * - last char of partial converted identifier
547 * @return converted char
549 private static String convert(final char c, final boolean existNext, final char partialLastChar) {
550 return partialLastChar == '_' ? convertFirst(c, existNext) : "_" + convertFirst(c, existNext);
554 * Capitalize input string
557 * - string to be capitalized
559 private static String capitalize(final String identifier) {
560 return identifier.substring(FIRST_CHAR, FIRST_CHAR + 1).toUpperCase() + identifier.substring(1);
563 private static String convertIdentifierEnumValue(final String name, final String origName, final List<Pair> values,
565 String newName = name;
566 for (final Pair pair : values) {
567 if (pair.getName().toLowerCase().equals(name.toLowerCase())
568 || pair.getMappedName().toLowerCase().equals(name.toLowerCase())) {
569 int actualRank = rank;
570 final StringBuilder actualNameBuilder =
571 new StringBuilder(origName).append(UNDERSCORE).append(actualRank);
572 newName = convertIdentifierEnumValue(actualNameBuilder.toString(), origName, values, ++actualRank);
575 return normalizeSpecificIdentifier(newName, JavaIdentifier.ENUM_VALUE);