2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.sal.java.api.generator
10 import com.google.common.base.CharMatcher
11 import com.google.common.base.Splitter
12 import java.util.Arrays
13 import java.util.Collection
14 import java.util.HashMap
17 import java.util.StringTokenizer
18 import java.util.regex.Pattern
19 import org.opendaylight.yangtools.binding.generator.util.Types
20 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType
21 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty
22 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject
23 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
24 import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature
25 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions
26 import org.opendaylight.yangtools.sal.binding.model.api.Type
27 import org.opendaylight.yangtools.sal.binding.model.api.Constant
28 import org.opendaylight.yangtools.yang.common.QName
30 abstract class BaseTemplate {
31 protected val GeneratedType type;
32 protected val Map<String, String> importMap;
34 private static final char NEW_LINE = '\n'
35 private static final CharMatcher NL_MATCHER = CharMatcher.is(NEW_LINE)
36 private static final CharMatcher TAB_MATCHER = CharMatcher.is('\t')
37 private static final Pattern SPACES_PATTERN = Pattern.compile(" +")
38 private static final Splitter NL_SPLITTER = Splitter.on(NL_MATCHER)
40 new(GeneratedType _type) {
42 throw new IllegalArgumentException("Generated type reference cannot be NULL!")
45 this.importMap = new HashMap<String,String>()
48 def packageDefinition() '''package «type.packageName»;'''
50 final public def generate() {
60 protected def imports() '''
62 «FOR entry : importMap.entrySet»
63 «IF !hasSamePackage(entry.value)»
64 import «entry.value».«entry.key»;
72 * Checks if packages of generated type and imported type is the same
74 * @param importedTypePackageNam
75 * the package name of imported type
76 * @return true if the packages are the same false otherwise
78 final private def boolean hasSamePackage(String importedTypePackageName) {
79 return type.packageName.equals(importedTypePackageName);
82 protected abstract def CharSequence body();
85 final protected def fieldName(GeneratedProperty property) '''_«property.name»'''
87 final protected def propertyNameFromGetter(MethodSignature getter) {
89 if (getter.name.startsWith("is")) {
91 } else if (getter.name.startsWith("get")) {
94 throw new IllegalArgumentException("Not a getter")
96 return getter.name.substring(prefix).toFirstLower;
100 * Template method which generates the getter method for <code>field</code>
103 * generated property with data about field which is generated as the getter method
104 * @return string with the getter method source code in JAVA format
106 final protected def getterMethod(GeneratedProperty field) {
108 public «field.returnType.importedName» «field.getterMethodName»() {
109 «IF field.returnType.importedName.contains("[]")»
110 return «field.fieldName» == null ? null : «field.fieldName».clone();
112 return «field.fieldName»;
118 final protected def getterMethodName(GeneratedProperty field) {
119 val prefix = if(field.returnType.equals(Types.BOOLEAN)) "is" else "get"
120 return '''«prefix»«field.name.toFirstUpper»'''
124 * Template method which generates the setter method for <code>field</code>
127 * generated property with data about field which is generated as the setter method
128 * @return string with the setter method source code in JAVA format
130 final protected def setterMethod(GeneratedProperty field) '''
131 «val returnType = field.returnType.importedName»
132 public «type.name» set«field.name.toFirstUpper»(«returnType» value) {
133 this.«field.fieldName» = value;
138 final protected def importedName(Type intype) {
139 GeneratorUtil.putTypeIntoImports(type, intype, importMap);
140 GeneratorUtil.getExplicitType(type, intype, importMap)
143 final protected def importedName(Class<?> cls) {
144 importedName(Types.typeForClass(cls))
148 * Template method which generates method parameters with their types from <code>parameters</code>.
151 * group of generated property instances which are transformed to the method parameters
152 * @return string with the list of the method parameters with their types in JAVA format
154 def final protected asArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
155 returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»'''
158 * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
161 * group of generated property instances which are transformed to the sequence of parameter names
162 * @return string with the list of the parameter names of the <code>parameters</code>
164 def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
165 fieldName»«ENDFOR»«ENDIF»'''
168 * Template method which generates JAVA comments.
170 * @param comment string with the comment for whole JAVA class
171 * @return string with comment in JAVA format
173 def protected CharSequence asJavadoc(String comment) {
174 if(comment == null) return ''
178 txt = formatToParagraph(txt)
181 «wrapToDocumentation(txt)»
185 def String wrapToDocumentation(String text) {
189 val StringBuilder sb = new StringBuilder("/**")
192 for (String t : NL_SPLITTER.split(text)) {
205 def protected String formatDataForJavaDoc(GeneratedType type) {
206 val typeDescription = type.getDescription().encodeJavadocSymbols;
209 «IF !typeDescription.nullOrEmpty»
215 private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
217 def encodeJavadocSymbols(String description) {
218 if (description.nullOrEmpty) {
222 var ret = description.replace("*/", "*/");
223 ret = AMP_MATCHER.replaceFrom(ret, "&");
228 def protected String formatDataForJavaDoc(GeneratedType type, String additionalComment) {
229 val StringBuilder typeDescription = new StringBuilder();
230 if (!type.description.nullOrEmpty) {
231 typeDescription.append(type.description)
232 typeDescription.append(NEW_LINE)
233 typeDescription.append(NEW_LINE)
234 typeDescription.append(NEW_LINE)
235 typeDescription.append(additionalComment)
237 typeDescription.append(additionalComment)
241 «typeDescription.toString»
245 def asLink(String text) {
246 val StringBuilder sb = new StringBuilder()
248 var char lastChar = ' '
249 var boolean badEnding = false
251 if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
252 tempText = text.substring(0, text.length - 1)
253 lastChar = text.charAt(text.length - 1)
256 sb.append("<a href = \"")
268 protected def formatToParagraph(String text) {
269 if(text == null || text.isEmpty)
272 var formattedText = text
273 val StringBuilder sb = new StringBuilder();
274 var StringBuilder lineBuilder = new StringBuilder();
275 var boolean isFirstElementOnNewLineEmptyChar = false;
277 formattedText = encodeJavadocSymbols(formattedText)
278 formattedText = NL_MATCHER.removeFrom(formattedText)
279 formattedText = TAB_MATCHER.removeFrom(formattedText)
280 formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
282 val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true);
284 while(tokenizer.hasMoreElements) {
285 val nextElement = tokenizer.nextElement.toString
287 if(lineBuilder.length + nextElement.length > 80) {
288 if (lineBuilder.charAt(lineBuilder.length - 1) == ' ') {
289 lineBuilder.setLength(0)
290 lineBuilder.append(lineBuilder.substring(0, lineBuilder.length - 1))
292 if (lineBuilder.charAt(0) == ' ') {
293 lineBuilder.setLength(0)
294 lineBuilder.append(lineBuilder.substring(1))
297 sb.append(lineBuilder);
298 lineBuilder.setLength(0)
301 if(nextElement.toString == ' ') {
302 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
306 if(isFirstElementOnNewLineEmptyChar) {
307 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
311 lineBuilder.append(nextElement)
314 sb.append(lineBuilder)
320 def protected generateToString(Collection<GeneratedProperty> properties) '''
321 «IF !properties.empty»
323 public «String.importedName» toString() {
324 «StringBuilder.importedName» builder = new «StringBuilder.importedName»(«type.importedName».class.getSimpleName()).append(" [");
325 boolean first = true;
327 «FOR property : properties»
328 if («property.fieldName» != null) {
332 builder.append(", ");
334 builder.append("«property.fieldName»=");
335 «IF property.returnType.name.contains("[")»
336 builder.append(«Arrays.importedName».toString(«property.fieldName»));
338 builder.append(«property.fieldName»);
342 return builder.append(']').toString();
347 def getRestrictions(Type type) {
348 var Restrictions restrictions = null
349 if (type instanceof ConcreteType) {
350 restrictions = type.restrictions
351 } else if (type instanceof GeneratedTransferObject) {
352 restrictions = type.restrictions
358 * Template method which generates method parameters with their types from <code>parameters</code>.
361 * list of parameter instances which are transformed to the method parameters
362 * @return string with the list of the method parameters with their types in JAVA format
364 def protected generateParameters(List<MethodSignature.Parameter> parameters) '''«
365 IF !parameters.empty»«
366 FOR parameter : parameters SEPARATOR ", "»«
367 parameter.type.importedName» «parameter.name»«
372 def protected GeneratedProperty findProperty(GeneratedTransferObject gto, String name) {
373 val props = gto.properties
375 if (prop.name.equals(name)) {
379 val GeneratedTransferObject parent = gto.superType
380 if (parent != null) {
381 return findProperty(parent, name)
386 def protected emitConstant(Constant c) '''
387 «IF c.value instanceof QName»
388 «val qname = c.value as QName»
389 public static final «c.type.importedName» «c.name» = «QName.name».create("«qname.namespace.toString»",
390 "«qname.formattedRevision»", "«qname.localName»").intern();
392 public static final «c.type.importedName» «c.name» = «c.value»;