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