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.spec.naming.BindingMapping.getGetterMethodForNonnull
11 import static extension org.opendaylight.mdsal.binding.spec.naming.BindingMapping.getGetterMethodForRequire
12 import static extension org.opendaylight.mdsal.binding.spec.naming.BindingMapping.isGetterMethodName
13 import static extension org.opendaylight.mdsal.binding.spec.naming.BindingMapping.isNonnullMethodName
14 import static extension org.opendaylight.mdsal.binding.spec.naming.BindingMapping.isRequireMethodName
15 import static org.opendaylight.mdsal.binding.model.ri.Types.BOOLEAN
16 import static org.opendaylight.mdsal.binding.model.ri.Types.STRING
17 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.REQUIRE_PREFIX
18 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTATION_FIELD
19 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME
20 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.BINDING_EQUALS_NAME
21 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.BINDING_HASHCODE_NAME
22 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.BINDING_TO_STRING_NAME
24 import com.google.common.annotations.VisibleForTesting;
26 import java.util.Locale
27 import java.util.Map.Entry
29 import org.gaul.modernizer_maven_annotations.SuppressModernizer
30 import org.opendaylight.mdsal.binding.model.api.AnnotationType
31 import org.opendaylight.mdsal.binding.model.api.Constant
32 import org.opendaylight.mdsal.binding.model.api.Enumeration
33 import org.opendaylight.mdsal.binding.model.api.GeneratedType
34 import org.opendaylight.mdsal.binding.model.api.JavaTypeName
35 import org.opendaylight.mdsal.binding.model.api.MethodSignature
36 import org.opendaylight.mdsal.binding.model.api.ParameterizedType
37 import org.opendaylight.mdsal.binding.model.api.Type
38 import org.opendaylight.mdsal.binding.model.ri.Types
39 import org.opendaylight.mdsal.binding.model.ri.TypeConstants
42 * Template for generating JAVA interfaces.
44 class InterfaceTemplate extends BaseTemplate {
46 * List of constant instances which are generated as JAVA public static final attributes.
48 val List<Constant> consts
51 * List of method signatures which are generated as method declarations.
53 val List<MethodSignature> methods
56 * List of enumeration which are generated as JAVA enum type.
58 val List<Enumeration> enums
61 * List of generated types which are enclosed inside <code>genType</code>
63 val List<GeneratedType> enclosedGeneratedTypes
65 var Entry<Type, Set<BuilderGeneratedProperty>> typeAnalysis
68 * Creates the instance of this class which is used for generating the interface file source
69 * code from <code>genType</code>.
71 * @throws NullPointerException if <code>genType</code> is <code>null</code>
73 new(GeneratedType genType) {
75 consts = genType.constantDefinitions
76 methods = genType.methodDefinitions
77 enums = genType.enumerations
78 enclosedGeneratedTypes = genType.enclosedTypes
82 * Template method which generate the whole body of the interface.
84 * @return string with code for interface body in JAVA format
87 «type.formatDataForJavaDoc.wrapToDocumentation»
88 «type.annotations.generateAnnotations»
90 public interface «type.name»
94 «generateInnerClasses»
106 def private generateAnnotations(List<AnnotationType> annotations) '''
107 «IF annotations !== null && !annotations.empty»
108 «FOR annotation : annotations»
109 «annotation.generateAnnotation»
114 def private generateAccessorAnnotations(MethodSignature method) '''
115 «val annotations = method.annotations»
116 «IF annotations !== null && !annotations.empty»
117 «FOR annotation : annotations»
118 «IF !BOOLEAN.equals(method.returnType) || !OVERRIDE.equals(annotation.identifier)»
119 «annotation.generateAnnotation»
126 * Template method which generates the interface name declaration.
128 * @return string with the code for the interface declaration in JAVA format
130 def private superInterfaces()
132 «IF (!type.implements.empty)»
134 «FOR type : type.implements SEPARATOR ","»
141 * Template method which generates inner classes inside this interface.
143 * @return string with the source code for inner classes in JAVA format
145 def private generateInnerClasses() '''
146 «IF !enclosedGeneratedTypes.empty»
147 «FOR innerClass : enclosedGeneratedTypes SEPARATOR "\n"»
148 «generateInnerClass(innerClass)»
154 * Template method which generates JAVA enum type.
156 * @return string with inner enum source code in JAVA format
158 def private generateEnums() '''
160 «FOR e : enums SEPARATOR "\n"»
161 «val enumTemplate = new EnumTemplate(javaType.getEnclosedType(e.identifier), e)»
162 «enumTemplate.generateAsInnerClass»
168 * Template method which generates JAVA constants.
170 * @return string with constants in JAVA format
172 def private generateConstants() '''
175 «IF !c.name.startsWith(TypeConstants.PATTERN_CONSTANT_NAME)»
183 * Template method which generates the declaration of the methods.
185 * @return string with the declaration of methods source code in JAVA format
187 def private generateMethods() '''
189 «FOR m : methods SEPARATOR "\n"»
191 «generateDefaultMethod(m)»
193 «generateStaticMethod(m)»
194 «ELSEIF m.parameters.empty && m.name.isGetterMethodName»
195 «generateAccessorMethod(m)»
196 «ELSEIF m.parameters.empty && m.name.isNonnullMethodName»
197 «generateNonnullAccessorMethod(m)»
206 def private generateDefaultMethod(MethodSignature method) {
207 if (method.name.isNonnullMethodName) {
208 generateNonnullMethod(method)
209 } else if (method.name.isRequireMethodName) {
210 generateRequireMethod(method)
213 case BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME : generateDefaultImplementedInterface
215 if (VOID.equals(method.returnType.identifier)) {
216 generateNoopVoidInterfaceMethod(method)
223 def private generateStaticMethod(MethodSignature method) {
225 case BINDING_EQUALS_NAME : generateBindingEquals
226 case BINDING_HASHCODE_NAME : generateBindingHashCode
227 case BINDING_TO_STRING_NAME : generateBindingToString
232 def private generateMethod(MethodSignature method) '''
233 «method.comment.asJavadoc»
234 «method.annotations.generateAnnotations»
235 «method.returnType.importedName» «method.name»(«method.parameters.generateParameters»);
238 def private generateNoopVoidInterfaceMethod(MethodSignature method) '''
239 «method.comment.asJavadoc»
240 «method.annotations.generateAnnotations»
241 default «VOID.importedName» «method.name»(«method.parameters.generateParameters») {
246 def private accessorJavadoc(MethodSignature method, String orString) {
247 accessorJavadoc(method, orString, null)
250 def private accessorJavadoc(MethodSignature method, String orString, JavaTypeName exception) {
251 val propName = method.propertyNameFromGetter
252 val propReturn = propName + orString
254 return wrapToDocumentation('''
257 «method.comment?.referenceDescription.formatReference»
258 @return {@code «method.returnType.importedName»} «propReturn»
259 «IF exception !== null»
260 @throws «exception.importedName» if «propName» is not present
265 def private generateAccessorMethod(MethodSignature method) {
267 «accessorJavadoc(method, ", or {@code null} if it is not present.")»
268 «method.generateAccessorAnnotations»
269 «method.returnType.nullableType» «method.name»();
273 def private generateNonnullAccessorMethod(MethodSignature method) {
275 «accessorJavadoc(method, ", or an empty instance if it is not present.")»
276 «method.annotations.generateAnnotations»
277 «method.returnType.importedNonNull» «method.name»();
281 def private generateDefaultImplementedInterface() '''
282 @«OVERRIDE.importedName»
283 default «CLASS.importedName»<«type.fullyQualifiedName»> «BINDING_CONTRACT_IMPLEMENTED_INTERFACE_NAME»() {
284 return «type.fullyQualifiedName».class;
289 def generateBindingHashCode() '''
290 «val augmentable = analyzeType»
291 «IF augmentable || !typeAnalysis.value.empty»
293 * Default implementation of {@link «Object.importedName»#hashCode()} contract for this interface.
294 * Implementations of this interface are encouraged to defer to this method to get consistent hashing
295 * results across all implementations.
297 * @param obj Object for which to generate hashCode() result.
298 * @return Hash code value of data modeled by this interface.
299 * @throws «NPE.importedName» if {@code obj} is {@code null}
301 static int «BINDING_HASHCODE_NAME»(final «type.fullyQualifiedNonNull» obj) {
302 final int prime = 31;
304 «FOR property : typeAnalysis.value»
305 result = prime * result + «property.importedUtilClass».hashCode(obj.«property.getterMethodName»());
308 for (var augmentation : obj.augmentations().values()) {
309 result += augmentation.hashCode();
317 def private generateBindingEquals() '''
318 «val augmentable = analyzeType»
319 «IF augmentable || !typeAnalysis.value.isEmpty»
321 * Default implementation of {@link «Object.importedName»#equals(«Object.importedName»)} contract for this interface.
322 * Implementations of this interface are encouraged to defer to this method to get consistent equality
323 * results across all implementations.
325 * @param thisObj Object acting as the receiver of equals invocation
326 * @param obj Object acting as argument to equals invocation
327 * @return True if thisObj and obj are considered equal
328 * @throws «NPE.importedName» if {@code thisObj} is {@code null}
330 static boolean «BINDING_EQUALS_NAME»(final «type.fullyQualifiedNonNull» thisObj, final «Types.objectType().importedName» obj) {
331 if (thisObj == obj) {
334 final «type.fullyQualifiedName» other = «CODEHELPERS.importedName».checkCast(«type.fullyQualifiedName».class, obj);
338 «FOR property : ByTypeMemberComparator.sort(typeAnalysis.value)»
339 if (!«property.importedUtilClass».equals(thisObj.«property.getterName»(), other.«property.getterName»())) {
343 return «IF augmentable»thisObj.augmentations().equals(other.augmentations())«ELSE»true«ENDIF»;
348 def generateBindingToString() '''
349 «val augmentable = analyzeType»
351 * Default implementation of {@link «Object.importedName»#toString()} contract for this interface.
352 * Implementations of this interface are encouraged to defer to this method to get consistent string
353 * representations across all implementations.
355 * @param obj Object for which to generate toString() result.
356 * @return {@link «STRING.importedName»} value of data modeled by this interface.
357 * @throws «NPE.importedName» if {@code obj} is {@code null}
359 static «STRING.importedName» «BINDING_TO_STRING_NAME»(final «type.fullyQualifiedNonNull» obj) {
360 final var helper = «MOREOBJECTS.importedName».toStringHelper("«type.name»");
361 «FOR property : typeAnalysis.value»
362 «CODEHELPERS.importedName».appendValue(helper, "«property.name»", obj.«property.getterName»());
365 «CODEHELPERS.importedName».appendAugmentations(helper, "«AUGMENTATION_FIELD»", obj);
367 return helper.toString();
371 def private generateNonnullMethod(MethodSignature method) '''
372 «val ret = method.returnType»
373 «val name = method.name»
374 «accessorJavadoc(method, ", or an empty list if it is not present.")»
375 «method.annotations.generateAnnotations»
376 default «ret.importedNonNull» «name»() {
377 return «CODEHELPERS.importedName».nonnull(«name.getGetterMethodForNonnull»());
381 def private generateRequireMethod(MethodSignature method) '''
382 «val ret = method.returnType»
383 «val name = method.name»
384 «val fieldName = name.toLowerCase(Locale.ROOT).replace(REQUIRE_PREFIX, "")»
385 «accessorJavadoc(method, ", guaranteed to be non-null.", NSEE)»
386 default «ret.importedNonNull» «name»() {
387 return «CODEHELPERS.importedName».require(«getGetterMethodForRequire(name)»(), "«fieldName»");
391 def private String nullableType(Type type) {
392 if (type.isObject && type instanceof ParameterizedType) {
393 val param = type as ParameterizedType
394 if (Types.isMapType(param) || Types.isListType(param) || Types.isSetType(param)) {
395 return type.importedNullable
398 return type.importedName
401 def private static boolean isObject(Type type) {
402 // The return type has a package, so it's not a primitive type
403 return !type.getPackageName().isEmpty()
406 private def boolean analyzeType() {
407 if (typeAnalysis === null) {
408 typeAnalysis = analyzeTypeHierarchy(type)
410 typeAnalysis.key !== null