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