Bug 1411-3: MDSAL Binding2 Generator Util
[mdsal.git] / binding2 / mdsal-binding2-generator-util / src / main / java / org / opendaylight / mdsal / binding2 / generator / util / Binding2Mapping.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
9 package org.opendaylight.mdsal.binding2.generator.util;
10
11 import static com.google.common.base.Preconditions.checkArgument;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.CharMatcher;
15 import com.google.common.base.Splitter;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Interner;
18 import com.google.common.collect.Interners;
19 import java.text.SimpleDateFormat;
20 import java.util.Set;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23 import org.opendaylight.yangtools.concepts.SemVer;
24 import org.opendaylight.yangtools.yang.model.api.Module;
25
26 /**
27  * Standard Util class that provides generated Java related functionality
28  */
29 @Beta
30 public final class Binding2Mapping {
31
32     private Binding2Mapping() {
33         throw new UnsupportedOperationException("Utility class");
34     }
35
36     public static final Set<String> JAVA_RESERVED_WORDS = ImmutableSet.of("abstract", "assert", "boolean", "break",
37             "byte", "case", "catch", "char", "class", "const", "continue", "default", "double", "do", "else", "enum",
38             "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof",
39             "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return",
40             "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient",
41             "true", "try", "void", "volatile", "while");
42
43     public static final String QNAME_STATIC_FIELD_NAME = "QNAME";
44     public static final String PACKAGE_PREFIX = "org.opendaylight.yang.gen.v2";
45
46     private static final Splitter DOT_SPLITTER = Splitter.on('.');
47     private static final Interner<String> PACKAGE_INTERNER = Interners.newWeakInterner();
48     private static final Splitter CAMEL_SPLITTER = Splitter.on(CharMatcher.anyOf(" _.-/").precomputed())
49             .omitEmptyStrings().trimResults();
50     private static final Pattern COLON_SLASH_SLASH = Pattern.compile("://", Pattern.LITERAL);
51     private static final String QUOTED_DOT = Matcher.quoteReplacement(".");
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     public static String getRootPackageName(final Module 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
71         final StringBuilder packageNameBuilder = new StringBuilder();
72         packageNameBuilder.append(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             }
95         }
96
97         packageNameBuilder.append(chars);
98         if (chars[chars.length - 1] != '.') {
99             packageNameBuilder.append('.');
100         }
101
102         final SemVer semVer = module.getSemanticVersion();
103         if (semVer != null) {
104             packageNameBuilder.append(semVer.toString());
105         } else {
106             packageNameBuilder.append("rev");
107             packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
108         }
109         return normalizePackageName(packageNameBuilder.toString());
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             //FIXME: don't use underscore in v2
128             if (Character.isDigit(p.charAt(0)) || Binding2Mapping.JAVA_RESERVED_WORDS.contains(p)) {
129                 builder.append('_');
130             }
131             builder.append(p);
132         }
133
134         // Prevent duplication of input string
135         return PACKAGE_INTERNER.intern(builder.toString());
136     }
137
138     public static String getClassName(final String localName) {
139         checkArgument(localName != null, "Name should not be null.");
140         return toFirstUpper(toCamelCase(localName));
141     }
142
143     private static String toCamelCase(final String rawString) {
144         checkArgument(rawString != null, "String should not be null");
145         Iterable<String> components = CAMEL_SPLITTER.split(rawString);
146         StringBuilder builder = new StringBuilder();
147         for (String comp : components) {
148             builder.append(toFirstUpper(comp));
149         }
150         return checkNumericPrefix(builder.toString());
151     }
152
153     private static String checkNumericPrefix(final String rawString) {
154         if (rawString == null || rawString.isEmpty()) {
155             return rawString;
156         }
157         char firstChar = rawString.charAt(0);
158         if (firstChar >= '0' && firstChar <= '9') {
159             return "_" + rawString;
160         } else {
161             return rawString;
162         }
163     }
164
165     /**
166      * Returns the {@link String} {@code s} with an
167      * {@link Character#isUpperCase(char) upper case} first character. This
168      * function is null-safe.
169      *
170      * @param s
171      *            the string that should get an upper case first character. May
172      *            be <code>null</code>.
173      * @return the {@link String} {@code s} with an upper case first character
174      *         or <code>null</code> if the input {@link String} {@code s} was
175      *         <code>null</code>.
176      */
177     public static String toFirstUpper(final String s) {
178         if (s == null || s.length() == 0) {
179             return s;
180         }
181         if (Character.isUpperCase(s.charAt(0))) {
182             return s;
183         }
184         if (s.length() == 1) {
185             return s.toUpperCase();
186         }
187         return s.substring(0, 1).toUpperCase() + s.substring(1);
188     }
189
190     //TODO: further implementation of static util methods...
191
192 }