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.collect.ArrayListMultimap;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.collect.ListMultimap;
14 import java.util.List;
16 import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration;
17 import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration.Pair;
18 import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
21 * This util class converts every non-java char in identifier to java char by
22 * its unicode name (<a href=
23 * "http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.8">JAVA SE
24 * SPECIFICATIONS - Identifiers</a>). There are special types of mapping
25 * non-java chars to original identifiers according to specific
26 * {@linkplain JavaIdentifier java type}:
28 * <li>class, enum, interface</li>
31 * <li>without special separator</li>
32 * <li>the first character of identifier, any other first character of
33 * identifier part mapped by non-Java char name from unicode and char in
34 * identifier behind non-java char name are converting to upper case</li>
38 * <li>example* - ExampleAsterisk</li>
39 * <li>example*example - ExampleAserisksExample</li>
40 * <li>\example - ReverseSolidusExample</li>
41 * <li>1example - DigitOneExample</li>
42 * <li>example1 - Example1</li>
43 * <li>int - IntReservedKeyword</li>
44 * <li>con - ConReservedKeyword</li>
49 * <li>enum value, constant</li>
52 * <li>used underscore as special separator</li>
53 * <li>converted identifier to upper case</li>
57 * <li>example* - EXAMPLE_ASTERISK</li>
58 * <li>example*example - EXAMPLE_ASTERISK_EXAMPLE</li>
59 * <li>\example - REVERSE_SOLIDUS_EXAMPLE</li>
60 * <li>1example - DIGIT_ONE_EXAMPLE</li>
61 * <li>example1 - EXAMPLE1</li>
62 * <li>int - INT_RESERVED_KEYWORD</li>
63 * <li>con - CON_RESERVED_KEYWORD</li>
68 * <li>method, variable</li>
72 * <li>without special separator</li>
73 * <li>the first character of identifier is converting to lower case</li>
74 * <li>any other first character of identifier part mapped by non-Java char name
75 * from unicode and char in identifier behind non-java char name are converting
80 * <li>example* - exampleAsterisk</li>
81 * <li>example*example - exampleAserisksExample</li>
82 * <li>\example - reverseSolidusExample</li>
83 * <li>1example - digitOneExample</li>
84 * <li>example1 - example1</li>
85 * <li>int - intReservedKeyword</li>
86 * <li>con - conReservedKeyword</li>
91 * <li>package - full package name (<a href=
92 * "https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html">
93 * Naming a package</a>)</li>
97 * <li>parts of package name are separated by dots</li>
98 * <li>parts of package name are converting to lower case</li>
99 * <li>if parts of package name are reserved Java or Windows keywords, such as
100 * 'int' the suggested convention is to add an underscore to keyword</li>
101 * <li>dash is parsed as underscore according to <a href=
102 * "https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html">
103 * Naming a package</a></li>
107 * <li>org.example* - org.exampleasterisk</li>
108 * <li>org.example*example - org.exampleasteriskexample</li>
109 * <li>org.\example - org.reversesolidusexample</li>
110 * <li>org.1example - org.digitoneexample</li>
111 * <li>org.example1 - org.example1</li>
112 * <li>org.int - org.int_</li>
113 * <li>org.con - org.con_</li>
114 * <li>org.foo-cont - org.foo_cont</li>
121 * There is special case in CLASS, INTERFACE, ENUM, ENUM VALUE, CONSTANT, METHOD
122 * and VARIABLE if identifier contains single dash - then the converter ignores
123 * the single dash in the way of the non-java chars. In other way, if dash is
124 * the first or the last char in the identifier or there is more dashes in a row
125 * in the identifier, then these dashes are converted as non-java chars.
128 * <li>class, enum, interface</li>
131 * <li>foo-cont - FooCont</li>
132 * <li>foo--cont - FooHyphenMinusHyphenMinusCont</li>
133 * <li>-foo - HyphenMinusFoo</li>
134 * <li>foo- - FooHyphenMinus</li>
137 * <li>enum value, constant
140 * <li>foo-cont - FOO_CONT</li>
141 * <li>foo--cont - FOO_HYPHEN_MINUS_HYPHEN_MINUS_CONT</li>
142 * <li>-foo - HYPHEN_MINUS_FOO</li>
143 * <li>foo- - FOO_HYPHEN_MINUS</li>
146 * <li>method, variable</li>
149 * <li>foo-cont - fooCont</li>
150 * <li>foo--cont - fooHyphenMinusHyphenMinusCont</li>
151 * <li>-foo - hyphenMinusFoo</li>
152 * <li>foo- - fooHyphenMinus</li>
157 * Next special case talks about normalizing class name which already exists in
158 * package - but with different camel cases (foo, Foo, fOo, ...). To every next
159 * classes with same names will by added their actual rank (serial number),
160 * except the first one. This working for CLASS, ENUM and INTEFACE java
161 * identifiers. If there exist the same ENUM VALUES in ENUM (with different
162 * camel cases), then it's parsed with same logic like CLASSES, ENUMS and
163 * INTERFACES but according to list of pairs of their ENUM parent. Example:
166 * <li>class, enum, interface</li>
169 * <li>package name org.example, class (or interface or enum) Foo - normalized
171 * <li>package name org.example, class (or interface or enum) fOo - normalized
175 * <li>enum value</li>
188 * <li>YANG enum values will be mapped to 'FOO' and 'FOO_1' Java enum
195 public final class JavaIdentifierNormalizer {
197 public static final Set<String> SPECIAL_RESERVED_PATHS = ImmutableSet.of(
198 "org.opendaylight.yangtools.concepts",
199 "org.opendaylight.yangtools.yang.common",
200 "org.opendaylight.yangtools.yang.model",
201 "org.opendaylight.mdsal.binding.javav2.spec",
205 private static final int FIRST_CHAR = 0;
206 private static final int FIRST_INDEX = 1;
207 private static final char UNDERSCORE = '_';
208 private static final char DASH = '-';
209 private static final String EMPTY_STRING = "";
210 private static final String RESERVED_KEYWORD = "reserved_keyword";
211 private static final ListMultimap<String, String> PACKAGES_MAP = ArrayListMultimap.create();
212 private static final Set<String> PRIMITIVE_TYPES = ImmutableSet.of("char[]", "byte[]");
214 private JavaIdentifierNormalizer() {
215 throw new UnsupportedOperationException("Util class");
220 * According to <a href="https://tools.ietf.org/html/rfc7950#section-9.6.4">YANG RFC 7950</a>,
221 * all assigned names in an enumeration MUST be unique. Created names are contained in the list
222 * of {@link Enumeration.Pair}. This method adds actual index with underscore behind name of new
223 * enum value only if this name already exists in one of the list of {@link Enumeration.Pair}.
224 * Then, the name will be converted to java chars according to {@link JavaIdentifier#ENUM_VALUE}
236 * YANG enum values will be mapped to 'FOO' and 'FOO_1' Java enum values.
239 * - name of new enum value
241 * - list of all actual enum values
242 * @return converted and fixed name of new enum value
244 public static String normalizeEnumValueIdentifier(final String name, final List<Pair> values) {
245 return convertIdentifierEnumValue(name, name, values, FIRST_INDEX);
249 * Normalizing full package name by non java chars and reserved keywords.
251 * @param fullPackageName
252 * - full package name
253 * @return normalized name
255 public static String normalizeFullPackageName(final String fullPackageName) {
256 final String[] packageNameParts = fullPackageName.split("\\.");
257 final StringBuilder sb = new StringBuilder();
258 for (int i = 0; i < packageNameParts.length; i++) {
259 String normalizedPartialPackageName = normalizePartialPackageName(packageNameParts[i]);
260 sb.append(normalizedPartialPackageName);
262 if (i != packageNameParts.length - 1) {
266 return sb.toString();
270 * Normalizing part of package name by non java chars.
272 * @param packageNamePart
273 * - part of package name
274 * @return normalized name
276 public static String normalizePartialPackageName(final String packageNamePart) {
277 // if part of package name consist from java or windows reserved word, return it with
278 // underscore at the end and in lower case
279 if (BindingMapping.JAVA_RESERVED_WORDS.contains(packageNamePart.toLowerCase())
280 || BindingMapping.WINDOWS_RESERVED_WORDS.contains(packageNamePart.toUpperCase())) {
281 return new StringBuilder(packageNamePart).append(UNDERSCORE).toString().toLowerCase();
283 String normalizedPackageNamePart = packageNamePart;
284 if (packageNamePart.contains(String.valueOf(DASH))) {
285 normalizedPackageNamePart = packageNamePart.replaceAll(String.valueOf(DASH), String.valueOf(UNDERSCORE));
287 final StringBuilder sb = new StringBuilder();
288 StringBuilder innserSb = new StringBuilder();
289 for (int i = 0; i < normalizedPackageNamePart.length(); i++) {
290 if (normalizedPackageNamePart.charAt(i) == UNDERSCORE) {
291 if (!innserSb.toString().isEmpty()) {
292 sb.append(normalizeSpecificIdentifier(innserSb.toString(), JavaIdentifier.PACKAGE));
293 innserSb = new StringBuilder();
295 sb.append(UNDERSCORE);
297 innserSb.append(normalizedPackageNamePart.charAt(i));
300 if (!innserSb.toString().isEmpty()) {
301 sb.append(normalizeSpecificIdentifier(innserSb.toString(), JavaIdentifier.PACKAGE));
303 // returned normalized part of package name
304 return sb.toString();
308 * Find and convert non Java chars in identifiers of generated transfer objects, initially
309 * derived from corresponding YANG according to
310 * <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.8"> Java
311 * Specifications - Identifiers</a>. If there is more same class names at the same package, then
312 * append rank (serial number) to the end of them. Works for class, enum, interface.
315 * - package of identifier
317 * - name of identifier
318 * @return - java acceptable identifier
320 public static String normalizeClassIdentifier(final String packageName, final String className) {
321 if (packageName.isEmpty() && PRIMITIVE_TYPES.contains(className)) {
324 for (final String reservedPath : SPECIAL_RESERVED_PATHS) {
325 if (packageName.startsWith(reservedPath)) {
329 final String convertedClassName = normalizeSpecificIdentifier(className, JavaIdentifier.CLASS);
330 // if packageName contains class name at the end, then the className is
331 // name of inner class
332 final String[] packageNameParts = packageName.split("\\.");
333 String suppInnerClassPackageName = packageName;
334 if (packageNameParts.length > 1) {
335 if (Character.isUpperCase(packageNameParts[packageNameParts.length - 1].charAt(FIRST_CHAR))) {
336 final StringBuilder sb = new StringBuilder();
337 // ignore class name in package name - inner class name has
338 // to be normalizing according to original package of parent
340 for (int i = 0; i < packageNameParts.length - 1; i++) {
341 if (!Character.isUpperCase(packageNameParts[i].charAt(FIRST_CHAR))) {
342 sb.append(packageNameParts[i]);
343 if (i != packageNameParts.length - 2 &&
344 !Character.isUpperCase(packageNameParts[i+1].charAt(FIRST_CHAR))) {
351 suppInnerClassPackageName = sb.toString();
355 return normalizeClassIdentifier(suppInnerClassPackageName, convertedClassName, convertedClassName, FIRST_INDEX);
359 * Find and convert non Java chars in identifiers of generated transfer objects, initially
360 * derived from corresponding YANG.
363 * - name of identifier
364 * @param javaIdentifier
365 * - java type of identifier
366 * @return - java acceptable identifier
368 public static String normalizeSpecificIdentifier(final String identifier, final JavaIdentifier javaIdentifier) {
369 final StringBuilder sb = new StringBuilder();
371 // if identifier isn't PACKAGE type then check it by reserved keywords
372 if(javaIdentifier != JavaIdentifier.PACKAGE) {
373 if (BindingMapping.JAVA_RESERVED_WORDS.contains(identifier.toLowerCase())
374 || BindingMapping.WINDOWS_RESERVED_WORDS.contains(identifier.toUpperCase())) {
375 return fixCasesByJavaType(
376 sb.append(identifier).append(UNDERSCORE).append(RESERVED_KEYWORD).toString().toLowerCase(),
381 // check and convert first char in identifier if there is non-java char
382 final char firstChar = identifier.charAt(FIRST_CHAR);
383 if (!Character.isJavaIdentifierStart(firstChar)) {
384 // converting first char of identifier
385 sb.append(convertFirst(firstChar, existNext(identifier, FIRST_CHAR)));
387 sb.append(firstChar);
389 // check and convert other chars in identifier, if there is non-java char
390 for (int i = 1; i < identifier.length(); i++) {
391 final char actualChar = identifier.charAt(i);
392 // ignore single dash as non java char - if there is more dashes in a row or dash is as
393 // the last char in identifier then parse these dashes as non java chars
394 if (actualChar == '-' && existNext(identifier, i)) {
395 if (identifier.charAt(i - 1) != DASH && identifier.charAt(i + 1) != DASH) {
396 sb.append(UNDERSCORE);
400 if (!Character.isJavaIdentifierPart(actualChar)) {
401 // prepare actual string of sb for checking if underscore exist on position of the
403 final String partialConvertedIdentifier = sb.toString();
404 sb.append(convert(actualChar, existNext(identifier, i),
405 partialConvertedIdentifier.charAt(partialConvertedIdentifier.length() - 1)));
407 sb.append(actualChar);
410 // apply camel case in appropriate way
411 return fixCasesByJavaType(sb.toString().replace("__", "_").toLowerCase(), javaIdentifier);
415 * Checking while there doesn't exist any class name with the same name
416 * (regardless of camel cases) in package.
419 * - package of class name
420 * @param origClassName
421 * - original class name
422 * @param actualClassName
423 * - actual class name with rank (serial number)
425 * - actual rank (serial number)
426 * @return converted identifier
428 private static String normalizeClassIdentifier(final String packageName, final String origClassName,
429 final String actualClassName, final int rank) {
430 if (PACKAGES_MAP.containsKey(packageName)) {
431 for (final String existingName : PACKAGES_MAP.get(packageName)) {
432 if (existingName.toLowerCase().equals(actualClassName.toLowerCase())) {
433 final int nextRank = rank + 1;
434 return normalizeClassIdentifier(packageName, origClassName,
435 new StringBuilder(origClassName).append(rank).toString(), nextRank);
439 PACKAGES_MAP.put(packageName, actualClassName);
440 return actualClassName;
444 * Fix cases of converted identifiers by Java type
447 * - converted identifier
448 * @param javaIdentifier
449 * - java type of identifier
450 * @return converted identifier with right cases according to java type
452 private static String fixCasesByJavaType(final String convertedIdentifier, final JavaIdentifier javaIdentifier) {
453 switch (javaIdentifier) {
457 return capitalize(fixCases(convertedIdentifier));
460 return convertedIdentifier.toUpperCase();
463 return fixCases(convertedIdentifier);
465 return convertedIdentifier.replaceAll(String.valueOf(UNDERSCORE), EMPTY_STRING);
467 throw new IllegalArgumentException("Unknown java type of identifier : " + javaIdentifier.toString());
472 * Delete unnecessary chars in converted identifier and apply camel case in appropriate way.
474 * @param convertedIdentifier
475 * - original converted identifier
476 * @return resolved identifier
478 private static String fixCases(final String convertedIdentifier) {
479 final StringBuilder sb = new StringBuilder();
480 if (convertedIdentifier.contains(String.valueOf(UNDERSCORE))) {
481 boolean isFirst = true;
482 for (final String part : convertedIdentifier.split(String.valueOf(UNDERSCORE))) {
487 sb.append(capitalize(part));
491 sb.append(convertedIdentifier);
493 return sb.toString();
497 * Check if there exist next char in identifier behind actual char position
500 * - original identifier
502 * - actual char position
503 * @return true if there is another char, false otherwise
505 private static boolean existNext(final String identifier, final int actual) {
506 return identifier.length() > actual + 1;
510 * Converting first char of identifier. This happen only if this char is
516 * - existing of next char behind actual char
517 * @return converted char
519 private static String convertFirst(final char c, final boolean existNext) {
520 String name = Character.getName(c);
521 if (name.contains(String.valueOf(DASH))) {
522 name = name.replaceAll(String.valueOf(DASH), String.valueOf(UNDERSCORE));
524 name = existNext ? name + "_" : name;
525 return name.contains(" ") ? name.replaceAll(" ", "_") : name;
529 * Converting any char in java identifier, This happen only if this char is
535 * - existing of next char behind actual char
536 * @param partialLastChar
537 * - last char of partial converted identifier
538 * @return converted char
540 private static String convert(final char c, final boolean existNext, final char partialLastChar) {
541 return partialLastChar == '_' ? convertFirst(c, existNext) : "_" + convertFirst(c, existNext);
545 * Capitalize input string
548 * - string to be capitalized
550 private static String capitalize(final String identifier) {
551 return identifier.substring(FIRST_CHAR, FIRST_CHAR + 1).toUpperCase() + identifier.substring(1);
554 private static String convertIdentifierEnumValue(final String name, final String origName, final List<Pair> values,
556 String newName = name;
557 for (final Pair pair : values) {
558 if (pair.getName().toLowerCase().equals(name.toLowerCase())
559 || pair.getMappedName().toLowerCase().equals(name.toLowerCase())) {
560 int actualRank = rank;
561 final StringBuilder actualNameBuilder =
562 new StringBuilder(origName).append(UNDERSCORE).append(actualRank);
563 newName = convertIdentifierEnumValue(actualNameBuilder.toString(), origName, values, ++actualRank);
566 return normalizeSpecificIdentifier(newName, JavaIdentifier.ENUM_VALUE);