Normalizing package names according to
[mdsal.git] / binding2 / mdsal-binding2-util / src / main / java / org / opendaylight / mdsal / binding / javav2 / util / BindingMapping.java
1 /*
2  * Copyright (c) 2017 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.mdsal.binding.javav2.util;
10
11 import com.google.common.annotations.Beta;
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.ImmutableSet;
16 import java.text.SimpleDateFormat;
17 import java.util.Set;
18 import java.util.regex.Matcher;
19 import java.util.regex.Pattern;
20 import org.opendaylight.yangtools.yang.model.api.Module;
21
22 /**
23  * Standard Util class that provides generated Java related functionality
24  */
25 @Beta
26 public final class BindingMapping {
27
28     public static final Set<String> JAVA_RESERVED_WORDS = ImmutableSet.of("abstract", "assert", "boolean", "break",
29             "byte", "case", "catch", "char", "class", "const", "continue", "default", "double", "do", "else", "enum",
30             "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof",
31             "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return",
32             "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient",
33             "true", "try", "void", "volatile", "while");
34
35     public static final Set<String> WINDOWS_RESERVED_WORDS = ImmutableSet.of("CON", "PRN", "AUX", "CLOCK$", "NUL",
36             "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2",
37             "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9");
38
39     public static final String QNAME_STATIC_FIELD_NAME = "QNAME";
40
41     /**
42      * Package prefix for Binding v2 generated Java code structures
43      */
44     public static final String PACKAGE_PREFIX = "org.opendaylight.mdsal.gen.javav2";
45
46     private static final Splitter CAMEL_SPLITTER = Splitter.on(CharMatcher.anyOf(" _.-/").precomputed())
47             .omitEmptyStrings().trimResults();
48     private static final Pattern COLON_SLASH_SLASH = Pattern.compile("://", Pattern.LITERAL);
49     private static final String QUOTED_DOT = Matcher.quoteReplacement(".");
50     public static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl";
51     public static final String MODEL_BINDING_PROVIDER_CLASS_NAME = "$YangModelBindingProvider";
52     public static final String PATTERN_CONSTANT_NAME = "PATTERN_CONSTANTS";
53     public static final String MEMBER_PATTERN_LIST = "patterns";
54
55     private static final ThreadLocal<SimpleDateFormat> PACKAGE_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
56
57         @Override
58         protected SimpleDateFormat initialValue() {
59             return new SimpleDateFormat("yyMMdd");
60         }
61
62         @Override
63         public void set(final SimpleDateFormat value) {
64             throw new UnsupportedOperationException();
65         }
66     };
67
68     private BindingMapping() {
69         throw new UnsupportedOperationException("Utility class");
70     }
71
72     public static String getRootPackageName(final Module module) {
73         Preconditions.checkArgument(module != null, "Module must not be null");
74         Preconditions.checkArgument(module.getRevision() != null, "Revision must not be null");
75         Preconditions.checkArgument(module.getNamespace() != null, "Namespace must not be null");
76
77         final StringBuilder packageNameBuilder = new StringBuilder();
78         packageNameBuilder.append(PACKAGE_PREFIX);
79         packageNameBuilder.append('.');
80
81         String namespace = module.getNamespace().toString();
82         namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
83
84         final char[] chars = namespace.toCharArray();
85         for (int i = 0; i < chars.length; ++i) {
86             switch (chars[i]) {
87                 case '/':
88                 case ':':
89                 case '-':
90                 case '@':
91                 case '$':
92                 case '#':
93                 case '\'':
94                 case '*':
95                 case '+':
96                 case ',':
97                 case ';':
98                 case '=':
99                     chars[i] = '.';
100                     break;
101                 default:
102                     // no-op, any other character is kept as it is
103             }
104         }
105
106         packageNameBuilder.append(chars);
107         if (chars[chars.length - 1] != '.') {
108             packageNameBuilder.append('.');
109         }
110
111         //TODO: per yangtools dev, semantic version not used yet
112 //        final SemVer semVer = module.getSemanticVersion();
113 //        if (semVer != null) {
114 //            packageNameBuilder.append(semVer.toString());
115 //        } else {
116 //            packageNameBuilder.append("rev");
117 //            packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
118 //        }
119
120         packageNameBuilder.append("rev");
121         packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
122         return packageNameBuilder.toString();
123     }
124
125     /**
126      * Prepares valid Java class name
127      * @param localName
128      * @return class name
129      */
130     public static String getClassName(final String localName) {
131         Preconditions.checkArgument(localName != null, "Name should not be null.");
132         return toFirstUpper(toCamelCase(localName));
133     }
134
135     private static String toCamelCase(final String rawString) {
136         Preconditions.checkArgument(rawString != null, "String should not be null");
137         final Iterable<String> components = CAMEL_SPLITTER.split(rawString);
138         final StringBuilder builder = new StringBuilder();
139         for (final String comp : components) {
140             builder.append(toFirstUpper(comp));
141         }
142         return checkNumericPrefix(builder.toString());
143     }
144
145     private static String checkNumericPrefix(final String rawString) {
146         if ((rawString == null) || rawString.isEmpty()) {
147             return rawString;
148         }
149         if (Character.isDigit(rawString.charAt(0))) {
150             return "_" + rawString;
151         } else {
152             return rawString;
153         }
154     }
155
156     /**
157      * Returns the {@link String} {@code s} with an
158      * {@link Character#isUpperCase(char) upper case} first character. This
159      * function is null-safe.
160      *
161      * @param s
162      *            the string that should get an upper case first character. May
163      *            be <code>null</code>.
164      * @return the {@link String} {@code s} with an upper case first character
165      *         or <code>null</code> if the input {@link String} {@code s} was
166      *         <code>null</code>.
167      */
168     public static String toFirstUpper(final String s) {
169         if (s == null || s.length() == 0) {
170             return s;
171         }
172         if (Character.isUpperCase(s.charAt(0))) {
173             return s;
174         }
175         if (s.length() == 1) {
176             return s.toUpperCase();
177         }
178         return s.substring(0, 1).toUpperCase() + s.substring(1);
179     }
180
181     /**
182      * Prepares Java property name for method getter code generation
183      * @param yangIdentifier given YANG element local name
184      * @return property name
185      */
186     public static String getPropertyName(final String yangIdentifier) {
187         final String potential = toFirstLower(toCamelCase(yangIdentifier));
188         if ("class".equals(potential)) {
189             return "xmlClass";
190         }
191         return potential;
192     }
193
194     /**
195      * Returns the {@link String} {@code s} with an
196      * {@link Character#isLowerCase(char) lower case} first character. This
197      * function is null-safe.
198      *
199      * @param s
200      *            the string that should get an lower case first character. May
201      *            be <code>null</code>.
202      * @return the {@link String} {@code s} with an lower case first character
203      *         or <code>null</code> if the input {@link String} {@code s} was
204      *         <code>null</code>.
205      */
206     private static String toFirstLower(final String s) {
207         if (s == null || s.length() == 0) {
208             return s;
209         }
210         if (Character.isLowerCase(s.charAt(0))) {
211             return s;
212         }
213         if (s.length() == 1) {
214             return s.toLowerCase();
215         }
216         return s.substring(0, 1).toLowerCase() + s.substring(1);
217     }
218
219     //TODO: further implementation of static util methods...
220
221 }