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