39cf3754c63f39dc2acb17886ee2c20807a03a4a
[mdsal.git] / binding2 / prototype / yang-binding2 / src / main / java / org / opendaylight / yangtools / yang / binding / BindingMapping.java
1 /*
2  * Copyright (c) 2016 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             }
106         }
107
108         packageNameBuilder.append(chars);
109         packageNameBuilder.append(".rev");
110         packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
111         return normalizePackageName(packageNameBuilder.toString());
112     }
113
114     public static String normalizePackageName(final String packageName) {
115         if (packageName == null) {
116             return null;
117         }
118
119         final StringBuilder builder = new StringBuilder();
120         boolean first = true;
121
122         for (String p : DOT_SPLITTER.split(packageName.toLowerCase())) {
123             if (first) {
124                 first = false;
125             } else {
126                 builder.append('.');
127             }
128
129             if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
130                 builder.append('_');
131             }
132             builder.append(p);
133         }
134
135         // Prevent duplication of input string
136         return PACKAGE_INTERNER.intern(builder.toString());
137     }
138
139     public static String getMethodName(final QName name) {
140         checkArgument(name != null, "Name should not be null.");
141         return getMethodName(name.getLocalName());
142     }
143
144     public static String getClassName(final String localName) {
145         checkArgument(localName != null, "Name should not be null.");
146         return toFirstUpper(toCamelCase(localName));
147     }
148
149     public static String getMethodName(final String yangIdentifier) {
150         checkArgument(yangIdentifier != null,"Identifier should not be null");
151         return toFirstLower(toCamelCase(yangIdentifier));
152     }
153
154     public static String getClassName(final QName name) {
155         checkArgument(name != null, "Name should not be null.");
156         return toFirstUpper(toCamelCase(name.getLocalName()));
157     }
158
159     public static String getGetterSuffix(final QName name) {
160         checkArgument(name != null, "Name should not be null.");
161         final String candidate = toFirstUpper(toCamelCase(name.getLocalName()));
162         return ("Class".equals(candidate) ? "XmlClass" : candidate);
163     }
164
165     public static String getPropertyName(final String yangIdentifier) {
166         final String potential = toFirstLower(toCamelCase(yangIdentifier));
167         if ("class".equals(potential)) {
168             return "xmlClass";
169         }
170         return potential;
171     }
172
173     private static String toCamelCase(final String rawString) {
174         checkArgument(rawString != null, "String should not be null");
175         Iterable<String> components = CAMEL_SPLITTER.split(rawString);
176         StringBuilder builder = new StringBuilder();
177         for (String comp : components) {
178             builder.append(toFirstUpper(comp));
179         }
180         return checkNumericPrefix(builder.toString());
181     }
182
183     private static String checkNumericPrefix(final String rawString) {
184         if (rawString == null || rawString.isEmpty()) {
185             return rawString;
186         }
187         char firstChar = rawString.charAt(0);
188         if (firstChar >= '0' && firstChar <= '9') {
189             return "_" + rawString;
190         } else {
191             return rawString;
192         }
193     }
194
195     /**
196      * Returns the {@link String} {@code s} with an
197      * {@link Character#isUpperCase(char) upper case} first character. This
198      * function is null-safe.
199      *
200      * @param s
201      *            the string that should get an upper case first character. May
202      *            be <code>null</code>.
203      * @return the {@link String} {@code s} with an upper case first character
204      *         or <code>null</code> if the input {@link String} {@code s} was
205      *         <code>null</code>.
206      */
207     public static String toFirstUpper(final String s) {
208         if (s == null || s.length() == 0) {
209             return s;
210         }
211         if (Character.isUpperCase(s.charAt(0))) {
212             return s;
213         }
214         if (s.length() == 1) {
215             return s.toUpperCase();
216         }
217         return s.substring(0, 1).toUpperCase() + s.substring(1);
218     }
219
220     /**
221      * Returns the {@link String} {@code s} with an
222      * {@link Character#isLowerCase(char) lower case} first character. This
223      * function is null-safe.
224      *
225      * @param s
226      *            the string that should get an lower case first character. May
227      *            be <code>null</code>.
228      * @return the {@link String} {@code s} with an lower case first character
229      *         or <code>null</code> if the input {@link String} {@code s} was
230      *         <code>null</code>.
231      */
232     private static String toFirstLower(final String s) {
233         if (s == null || s.length() == 0) {
234             return s;
235         }
236         if (Character.isLowerCase(s.charAt(0))) {
237             return s;
238         }
239         if (s.length() == 1) {
240             return s.toLowerCase();
241         }
242         return s.substring(0, 1).toLowerCase() + s.substring(1);
243     }
244 }