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