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.mdsal.binding.java.api.generator
10 import static extension org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil.encodeAngleBrackets
11 import static org.opendaylight.mdsal.binding.model.ri.Types.STRING;
12 import static org.opendaylight.mdsal.binding.model.ri.Types.objectType;
14 import com.google.common.base.CharMatcher
15 import com.google.common.base.Splitter
16 import java.util.Collection
18 import java.util.Locale
19 import java.util.Map.Entry
20 import java.util.StringTokenizer
21 import java.util.regex.Pattern
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.gaul.modernizer_maven_annotations.SuppressModernizer
24 import org.opendaylight.mdsal.binding.model.api.AnnotationType
25 import org.opendaylight.mdsal.binding.model.api.ConcreteType
26 import org.opendaylight.mdsal.binding.model.api.Constant
27 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty
28 import org.opendaylight.mdsal.binding.model.api.GeneratedType
29 import org.opendaylight.mdsal.binding.model.api.JavaTypeName
30 import org.opendaylight.mdsal.binding.model.api.MethodSignature
31 import org.opendaylight.mdsal.binding.model.api.Restrictions
32 import org.opendaylight.mdsal.binding.model.api.Type
33 import org.opendaylight.mdsal.binding.model.api.TypeMemberComment
34 import org.opendaylight.mdsal.binding.model.ri.TypeConstants
35 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping
36 import org.opendaylight.yangtools.yang.binding.BaseIdentity
39 abstract class BaseTemplate extends JavaFileTemplate {
40 static final char NEW_LINE = '\n'
41 static final char SPACE = ' '
42 static val WS_MATCHER = CharMatcher.anyOf("\n\t")
43 static val SPACES_PATTERN = Pattern.compile(" +")
44 static val NL_SPLITTER = Splitter.on(NEW_LINE)
46 new(GeneratedType type) {
50 new(AbstractJavaGeneratedType javaType, GeneratedType type) {
54 final def generate() {
57 package «type.packageName»;
64 protected abstract def CharSequence body();
67 final protected def fieldName(GeneratedProperty property) {
72 * Template method which generates the getter method for <code>field</code>
75 * generated property with data about field which is generated as the getter method
76 * @return string with the getter method source code in JAVA format
78 protected def getterMethod(GeneratedProperty field) '''
79 «val methodName = field.getterMethodName»
80 public «field.returnType.importedName» «methodName»() {
81 «val fieldName = field.fieldName»
82 «IF field.returnType.name.endsWith("[]")»
83 return «fieldName» == null ? null : «fieldName».clone();
90 final protected def getterMethodName(GeneratedProperty field) {
91 return '''«BindingMapping.GETTER_PREFIX»«field.name.toFirstUpper»'''
95 * Template method which generates the setter method for <code>field</code>
98 * generated property with data about field which is generated as the setter method
99 * @return string with the setter method source code in JAVA format
101 final protected def setterMethod(GeneratedProperty field) '''
102 «val returnType = field.returnType.importedName»
103 public «type.name» set«field.name.toFirstUpper»(«returnType» value) {
104 this.«field.fieldName» = value;
110 * Template method which generates method parameters with their types from <code>parameters</code>.
113 * group of generated property instances which are transformed to the method parameters
114 * @return string with the list of the method parameters with their types in JAVA format
116 def final protected asArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
117 returnType.importedName» «parameter.fieldName»«ENDFOR»«ENDIF»'''
120 * Template method which generates method parameters with their types from <code>parameters</code>, annotating them
121 * with {@link NonNull}.
123 * @param parameters group of generated property instances which are transformed to the method parameters
124 * @return string with the list of the method parameters with their types in JAVA format
126 def final protected asNonNullArgumentsDeclaration(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»
127 «FOR parameter : parameters SEPARATOR ", "»«parameter.returnType.importedNonNull» «parameter
128 .fieldName»«ENDFOR»«ENDIF»'''
131 * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
134 * group of generated property instances which are transformed to the sequence of parameter names
135 * @return string with the list of the parameter names of the <code>parameters</code>
137 def final protected asArguments(Collection<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
138 fieldName»«ENDFOR»«ENDIF»'''
141 * Template method which generates JAVA comments.
143 * @param comment string with the comment for whole JAVA class
144 * @return string with comment in JAVA format
146 def final protected asJavadoc(TypeMemberComment comment) {
147 if (comment === null) {
150 return wrapToDocumentation('''
151 «comment.contractDescription»
153 «comment.referenceDescription.formatReference»
155 «comment.typeSignature»
159 def static String wrapToDocumentation(String text) {
163 val StringBuilder sb = new StringBuilder().append("/**\n")
164 for (String t : NL_SPLITTER.split(text)) {
167 sb.append(SPACE).append(t)
176 def protected String formatDataForJavaDoc(GeneratedType type) {
177 val sb = new StringBuilder()
178 val comment = type.comment
179 if (comment !== null) {
180 sb.append(comment.javadoc)
183 appendSnippet(sb, type)
192 def protected String formatDataForJavaDoc(GeneratedType type, String additionalComment) {
193 val comment = type.comment
194 if (comment === null) {
200 val sb = new StringBuilder().append(comment.javadoc)
201 appendSnippet(sb, type)
206 .append(additionalComment)
213 def static formatReference(String reference) '''
214 «IF reference !== null»
217 «reference.encodeAngleBrackets.formatToParagraph»
224 def asLink(String text) {
225 val StringBuilder sb = new StringBuilder()
227 var char lastChar = SPACE
228 var boolean badEnding = false
230 if (text.endsWith('.') || text.endsWith(':') || text.endsWith(',')) {
231 tempText = text.substring(0, text.length - 1)
232 lastChar = text.charAt(text.length - 1)
235 sb.append("<a href = \"").append(tempText).append("\">").append(tempText).append("</a>")
243 protected static def formatToParagraph(String inputText) {
244 val StringBuilder sb = new StringBuilder();
245 var StringBuilder lineBuilder = new StringBuilder();
246 var boolean isFirstElementOnNewLineEmptyChar = false;
248 var formattedText = WS_MATCHER.replaceFrom(inputText.encodeJavadocSymbols, SPACE)
249 formattedText = SPACES_PATTERN.matcher(formattedText).replaceAll(" ")
251 val StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true)
252 while (tokenizer.hasMoreTokens) {
253 val nextElement = tokenizer.nextToken
255 if (lineBuilder.length != 0 && lineBuilder.length + nextElement.length > 80) {
256 if (lineBuilder.charAt(lineBuilder.length - 1) == SPACE) {
257 lineBuilder.setLength(lineBuilder.length - 1)
259 if (lineBuilder.length != 0 && lineBuilder.charAt(0) == SPACE) {
260 lineBuilder.deleteCharAt(0)
263 sb.append(lineBuilder).append(NEW_LINE)
264 lineBuilder.setLength(0)
266 if (nextElement == " ") {
267 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar;
270 if (isFirstElementOnNewLineEmptyChar) {
271 isFirstElementOnNewLineEmptyChar = !isFirstElementOnNewLineEmptyChar
273 lineBuilder.append(nextElement)
277 return sb.append(lineBuilder).append(NEW_LINE).toString
281 * Template method which generates method parameters with their types from <code>parameters</code>.
284 * list of parameter instances which are transformed to the method parameters
285 * @return string with the list of the method parameters with their types in JAVA format
287 def protected generateParameters(List<MethodSignature.Parameter> parameters) '''«
288 IF !parameters.empty»«
289 FOR parameter : parameters SEPARATOR ", "»«
290 parameter.type.importedName» «parameter.name»«
295 def protected emitConstant(Constant c) '''
296 «IF BindingMapping.QNAME_STATIC_FIELD_NAME.equals(c.name)»
297 «val entry = c.value as Entry<JavaTypeName, String>»
299 * YANG identifier of the statement represented by this class.
301 public static final «c.type.importedNonNull» «c.name» = «entry.key.importedName».«BindingMapping.MODULE_INFO_QNAMEOF_METHOD_NAME»("«entry.value»");
302 «ELSEIF BindingMapping.VALUE_STATIC_FIELD_NAME.equals(c.name) && BaseIdentity.equals(c.value)»
303 «val typeName = c.type.importedName»
304 «val override = OVERRIDE.importedName»
306 * Singleton value representing the {@link «typeName»} identity.
308 public static final «c.type.importedNonNull» «c.name» = new «typeName»() {
310 public «CLASS.importedName»<«typeName»> «BindingMapping.BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME»() {
311 return «typeName».class;
315 public int hashCode() {
316 return «typeName».class.hashCode();
320 public boolean equals(final «objectType.importedName» obj) {
321 return obj == this || obj instanceof «typeName»
322 && «typeName».class.equals(((«typeName») obj).«BindingMapping.BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME»());
326 public «STRING.importedName» toString() {
327 return «MOREOBJECTS.importedName».toStringHelper("«c.type.name»").add("qname", QNAME).toString();
331 public static final «c.type.importedName» «c.name» = «c.value»;
335 def protected generateCheckers(GeneratedProperty field, Restrictions restrictions, Type actualType) '''
336 «IF restrictions.rangeConstraint.present»
337 «AbstractRangeGenerator.forType(actualType).generateRangeChecker(field.name.toFirstUpper,
338 restrictions.rangeConstraint.get, this)»
340 «IF restrictions.lengthConstraint.present»
341 «LengthGenerator.generateLengthChecker(field.fieldName, actualType, restrictions.lengthConstraint.get, this)»
345 def protected checkArgument(GeneratedProperty property, Restrictions restrictions, Type actualType, String value) '''
346 «IF restrictions.getRangeConstraint.isPresent»
347 «IF actualType instanceof ConcreteType»
348 «AbstractRangeGenerator.forType(actualType).generateRangeCheckerCall(property.getName.toFirstUpper, value)»
350 «AbstractRangeGenerator.forType(actualType).generateRangeCheckerCall(property.getName.toFirstUpper, value + ".getValue()")»
353 «val fieldName = property.fieldName»
354 «IF restrictions.getLengthConstraint.isPresent»
355 «IF actualType instanceof ConcreteType»
356 «LengthGenerator.generateLengthCheckerCall(fieldName, value)»
358 «LengthGenerator.generateLengthCheckerCall(fieldName, value + ".getValue()")»
362 «val fieldUpperCase = fieldName.toUpperCase(Locale.ENGLISH)»
363 «FOR currentConstant : type.getConstantDefinitions»
364 «IF currentConstant.getName.startsWith(TypeConstants.PATTERN_CONSTANT_NAME)
365 && fieldUpperCase.equals(currentConstant.getName.substring(TypeConstants.PATTERN_CONSTANT_NAME.length))»
366 «CODEHELPERS.importedName».checkPattern(value, «Constants.MEMBER_PATTERN_LIST»«fieldName», «Constants.MEMBER_REGEX_LIST»«fieldName»);
371 def protected hashCodeResult(Collection<? extends GeneratedProperty> properties) '''
372 final int prime = 31;
374 «FOR property : properties»
375 result = prime * result + «property.importedUtilClass».hashCode(«property.fieldName»);
379 def protected final generateAnnotation(AnnotationType annotation) '''
380 @«annotation.importedName»
381 «IF annotation.parameters !== null && !annotation.parameters.empty»
383 «FOR param : annotation.parameters SEPARATOR ","»
384 «param.name»=«param.value»