Merge "BUG-1276: fixed generated union constructor"
[yangtools.git] / yang / 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 java.text.SimpleDateFormat;
13 import java.util.Set;
14 import java.util.regex.Matcher;
15 import java.util.regex.Pattern;
16
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.common.QNameModule;
19
20 import com.google.common.base.CharMatcher;
21 import com.google.common.base.Splitter;
22 import com.google.common.collect.ImmutableSet;
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
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 BindingMapping() {
67         throw new UnsupportedOperationException("Utility class should not be instantiated");
68     }
69
70     public static final String getRootPackageName(final QName module) {
71         return getRootPackageName(module.getModule());
72     }
73
74     public static final String getRootPackageName(final QNameModule module) {
75         checkArgument(module != null, "Module must not be null");
76         checkArgument(module.getRevision() != null, "Revision must not be null");
77         checkArgument(module.getNamespace() != null, "Namespace must not be null");
78         final StringBuilder packageNameBuilder = new StringBuilder();
79
80         packageNameBuilder.append(BindingMapping.PACKAGE_PREFIX);
81         packageNameBuilder.append('.');
82
83         String namespace = module.getNamespace().toString();
84         namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
85
86         final char[] chars = namespace.toCharArray();
87         for (int i = 0; i < chars.length; ++i) {
88             switch (chars[i]) {
89             case '/':
90             case ':':
91             case '-':
92             case '@':
93             case '$':
94             case '#':
95             case '\'':
96             case '*':
97             case '+':
98             case ',':
99             case ';':
100             case '=':
101                 chars[i] = '.';
102             }
103         }
104
105         packageNameBuilder.append(chars);
106         packageNameBuilder.append(".rev");
107         packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
108         return normalizePackageName(packageNameBuilder.toString());
109
110     }
111
112     public static String normalizePackageName(final String packageName) {
113         if (packageName == null) {
114             return null;
115         }
116
117         final StringBuilder builder = new StringBuilder();
118         boolean first = true;
119
120         for (String p : DOT_SPLITTER.split(packageName.toLowerCase())) {
121             if (first) {
122                 first = false;
123             } else {
124                 builder.append('.');
125             }
126
127             if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
128                 builder.append('_');
129             }
130             builder.append(p);
131         }
132
133         return builder.toString();
134     }
135
136     public static final String getMethodName(final QName name) {
137         checkArgument(name != null, "Name should not be null.");
138         return getMethodName(name.getLocalName());
139     }
140
141     public static final String getClassName(final String localName) {
142         checkArgument(localName != null, "Name should not be null.");
143         return toFirstUpper(toCamelCase(localName));
144     }
145
146     public static final String getMethodName(final String yangIdentifier) {
147         checkArgument(yangIdentifier != null,"Identifier should not be null");
148         return toFirstLower(toCamelCase(yangIdentifier));
149     }
150
151     public static final String getClassName(final QName name) {
152         checkArgument(name != null, "Name should not be null.");
153         return toFirstUpper(toCamelCase(name.getLocalName()));
154     }
155
156     public static String getPropertyName(final String yangIdentifier) {
157         final String potential = toFirstLower(toCamelCase(yangIdentifier));
158         if("class".equals(potential)) {
159             return "xmlClass";
160         }
161         return potential;
162     }
163
164     private static final String toCamelCase(final String rawString) {
165         checkArgument(rawString != null, "String should not be null");
166         Iterable<String> components = CAMEL_SPLITTER.split(rawString);
167         StringBuilder builder = new StringBuilder();
168         for (String comp : components) {
169             builder.append(toFirstUpper(comp));
170         }
171         return checkNumericPrefix(builder.toString());
172     }
173
174     private static final String checkNumericPrefix(final String rawString) {
175         if (rawString == null || rawString.isEmpty()) {
176             return rawString;
177         }
178         char firstChar = rawString.charAt(0);
179         if (firstChar >= '0' && firstChar <= '9') {
180             return "_" + rawString;
181         } else {
182             return rawString;
183         }
184     }
185
186     /**
187      * Returns the {@link String} {@code s} with an
188      * {@link Character#isUpperCase(char) upper case} first character. This
189      * function is null-safe.
190      *
191      * @param s
192      *            the string that should get an upper case first character. May
193      *            be <code>null</code>.
194      * @return the {@link String} {@code s} with an upper case first character
195      *         or <code>null</code> if the input {@link String} {@code s} was
196      *         <code>null</code>.
197      */
198     public static String toFirstUpper(final String s) {
199         if (s == null || s.length() == 0) {
200             return s;
201         }
202         if (Character.isUpperCase(s.charAt(0))) {
203             return s;
204         }
205         if (s.length() == 1) {
206             return s.toUpperCase();
207         }
208         return s.substring(0, 1).toUpperCase() + s.substring(1);
209     }
210
211     /**
212      * Returns the {@link String} {@code s} with an
213      * {@link Character#isLowerCase(char) lower case} first character. This
214      * function is null-safe.
215      *
216      * @param s
217      *            the string that should get an lower case first character. May
218      *            be <code>null</code>.
219      * @return the {@link String} {@code s} with an lower case first character
220      *         or <code>null</code> if the input {@link String} {@code s} was
221      *         <code>null</code>.
222      */
223     private static String toFirstLower(final String s) {
224         if (s == null || s.length() == 0) {
225             return s;
226         }
227         if (Character.isLowerCase(s.charAt(0))) {
228             return s;
229         }
230         if (s.length() == 1) {
231             return s.toLowerCase();
232         }
233         return s.substring(0, 1).toLowerCase() + s.substring(1);
234     }
235 }