Removed sonar warnings.
[mdsal.git] / binding / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / BindingMapping.java
1 /*
2  * Copyright (c) 2013 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 package org.opendaylight.yangtools.yang.binding;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import com.google.common.base.CharMatcher;
12 import com.google.common.base.Splitter;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.collect.Interner;
15 import com.google.common.collect.Interners;
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.common.QName;
21 import org.opendaylight.yangtools.yang.common.QNameModule;
22
23 public final class BindingMapping {
24
25     public static final String VERSION = "0.6";
26
27     public static final Set<String> JAVA_RESERVED_WORDS = ImmutableSet.of("abstract", "assert", "boolean", "break",
28             "byte", "case", "catch", "char", "class", "const", "continue", "default", "double", "do", "else", "enum",
29             "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof",
30             "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return",
31             "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient",
32             "true", "try", "void", "volatile", "while");
33
34     public static final String DATA_ROOT_SUFFIX = "Data";
35     public static final String RPC_SERVICE_SUFFIX = "Service";
36     public static final String NOTIFICATION_LISTENER_SUFFIX = "Listener";
37     public static final String QNAME_STATIC_FIELD_NAME = "QNAME";
38     public static final String PACKAGE_PREFIX = "org.opendaylight.yang.gen.v1";
39     public static final String AUGMENTATION_FIELD = "augmentation";
40
41     private static final Splitter CAMEL_SPLITTER = Splitter.on(CharMatcher.anyOf(" _.-/").precomputed())
42             .omitEmptyStrings().trimResults();
43     private static final Pattern COLON_SLASH_SLASH = Pattern.compile("://", Pattern.LITERAL);
44     private static final String QUOTED_DOT = Matcher.quoteReplacement(".");
45     private static final Splitter DOT_SPLITTER = Splitter.on('.');
46
47     public static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl";
48     public static final String MODEL_BINDING_PROVIDER_CLASS_NAME = "$YangModelBindingProvider";
49
50     public static final String RPC_INPUT_SUFFIX = "Input";
51     public static final String RPC_OUTPUT_SUFFIX = "Output";
52
53     private static final ThreadLocal<SimpleDateFormat> PACKAGE_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
54
55         @Override
56         protected SimpleDateFormat initialValue() {
57             return new SimpleDateFormat("yyMMdd");
58         }
59
60         @Override
61         public void set(final SimpleDateFormat value) {
62             throw new UnsupportedOperationException();
63         }
64     };
65
66     private static final Interner<String> PACKAGE_INTERNER = Interners.newWeakInterner();
67
68     private BindingMapping() {
69         throw new UnsupportedOperationException("Utility class should not be instantiated");
70     }
71
72     public static String getRootPackageName(final QName module) {
73         return getRootPackageName(module.getModule());
74     }
75
76     public static String getRootPackageName(final QNameModule module) {
77         checkArgument(module != null, "Module must not be null");
78         checkArgument(module.getRevision() != null, "Revision must not be null");
79         checkArgument(module.getNamespace() != null, "Namespace must not be null");
80         final StringBuilder packageNameBuilder = new StringBuilder();
81
82         packageNameBuilder.append(BindingMapping.PACKAGE_PREFIX);
83         packageNameBuilder.append('.');
84
85         String namespace = module.getNamespace().toString();
86         namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
87
88         final char[] chars = namespace.toCharArray();
89         for (int i = 0; i < chars.length; ++i) {
90             switch (chars[i]) {
91             case '/':
92             case ':':
93             case '-':
94             case '@':
95             case '$':
96             case '#':
97             case '\'':
98             case '*':
99             case '+':
100             case ',':
101             case ';':
102             case '=':
103                 chars[i] = '.';
104             }
105         }
106
107         packageNameBuilder.append(chars);
108         if (chars[chars.length - 1] != '.') {
109             packageNameBuilder.append('.');
110         }
111         packageNameBuilder.append("rev");
112         packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
113         return normalizePackageName(packageNameBuilder.toString());
114     }
115
116     public static String normalizePackageName(final String packageName) {
117         if (packageName == null) {
118             return null;
119         }
120
121         final StringBuilder builder = new StringBuilder();
122         boolean first = true;
123
124         for (String p : DOT_SPLITTER.split(packageName.toLowerCase())) {
125             if (first) {
126                 first = false;
127             } else {
128                 builder.append('.');
129             }
130
131             if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
132                 builder.append('_');
133             }
134             builder.append(p);
135         }
136
137         // Prevent duplication of input string
138         return PACKAGE_INTERNER.intern(builder.toString());
139     }
140
141     public static String getMethodName(final QName name) {
142         checkArgument(name != null, "Name should not be null.");
143         return getMethodName(name.getLocalName());
144     }
145
146     public static String getClassName(final String localName) {
147         checkArgument(localName != null, "Name should not be null.");
148         return toFirstUpper(toCamelCase(localName));
149     }
150
151     public static String getMethodName(final String yangIdentifier) {
152         checkArgument(yangIdentifier != null,"Identifier should not be null");
153         return toFirstLower(toCamelCase(yangIdentifier));
154     }
155
156     public static String getClassName(final QName name) {
157         checkArgument(name != null, "Name should not be null.");
158         return toFirstUpper(toCamelCase(name.getLocalName()));
159     }
160
161     public static String getGetterSuffix(final QName name) {
162         checkArgument(name != null, "Name should not be null.");
163         final String candidate = toFirstUpper(toCamelCase(name.getLocalName()));
164         return "Class".equals(candidate) ? "XmlClass" : candidate;
165     }
166
167     public static String getPropertyName(final String yangIdentifier) {
168         final String potential = toFirstLower(toCamelCase(yangIdentifier));
169         if ("class".equals(potential)) {
170             return "xmlClass";
171         }
172         return potential;
173     }
174
175     private static String toCamelCase(final String rawString) {
176         checkArgument(rawString != null, "String should not be null");
177         Iterable<String> components = CAMEL_SPLITTER.split(rawString);
178         StringBuilder builder = new StringBuilder();
179         for (String comp : components) {
180             builder.append(toFirstUpper(comp));
181         }
182         return checkNumericPrefix(builder.toString());
183     }
184
185     private static String checkNumericPrefix(final String rawString) {
186         if (rawString == null || rawString.isEmpty()) {
187             return rawString;
188         }
189         char firstChar = rawString.charAt(0);
190         if (firstChar >= '0' && firstChar <= '9') {
191             return "_" + rawString;
192         } else {
193             return rawString;
194         }
195     }
196
197     /**
198      * Returns the {@link String} {@code s} with an
199      * {@link Character#isUpperCase(char) upper case} first character. This
200      * function is null-safe.
201      *
202      * @param s
203      *            the string that should get an upper case first character. May
204      *            be <code>null</code>.
205      * @return the {@link String} {@code s} with an upper case first character
206      *         or <code>null</code> if the input {@link String} {@code s} was
207      *         <code>null</code>.
208      */
209     public static String toFirstUpper(final String s) {
210         if (s == null || s.length() == 0) {
211             return s;
212         }
213         if (Character.isUpperCase(s.charAt(0))) {
214             return s;
215         }
216         if (s.length() == 1) {
217             return s.toUpperCase();
218         }
219         return s.substring(0, 1).toUpperCase() + s.substring(1);
220     }
221
222     /**
223      * Returns the {@link String} {@code s} with an
224      * {@link Character#isLowerCase(char) lower case} first character. This
225      * function is null-safe.
226      *
227      * @param s
228      *            the string that should get an lower case first character. May
229      *            be <code>null</code>.
230      * @return the {@link String} {@code s} with an lower case first character
231      *         or <code>null</code> if the input {@link String} {@code s} was
232      *         <code>null</code>.
233      */
234     private static String toFirstLower(final String s) {
235         if (s == null || s.length() == 0) {
236             return s;
237         }
238         if (Character.isLowerCase(s.charAt(0))) {
239             return s;
240         }
241         if (s.length() == 1) {
242             return s.toLowerCase();
243         }
244         return s.substring(0, 1).toLowerCase() + s.substring(1);
245     }
246 }