75d2cc069de8bd77170a51dc69e287321e7ca2bd
[mdsal.git] / binding2 / mdsal-binding2-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / javav2 / java / api / generator / renderers / BuilderRenderer.java
1 /*
2  * Copyright (c) 2017 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.binding.javav2.java.api.generator.renderers;
10
11 import static org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.DOT;
12 import static org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.getPropertyList;
13 import static org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.toFirstLower;
14
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ClassToInstanceMap;
18 import com.google.common.collect.Collections2;
19 import com.google.common.collect.ImmutableSortedSet;
20 import java.lang.reflect.Method;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.LinkedHashSet;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Objects;
32 import java.util.Set;
33 import org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes;
34 import org.opendaylight.mdsal.binding.javav2.generator.util.ReferencedTypeImpl;
35 import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
36 import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
37 import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.builderConstructorHelperTemplate;
38 import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.builderTemplate;
39 import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.AlphabeticallyTypeMemberComparator;
40 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty;
41 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject;
42 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType;
43 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTypeForBuilder;
44 import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature;
45 import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType;
46 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
47 import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable;
48 import org.opendaylight.mdsal.binding.javav2.spec.base.Item;
49 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
50 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable;
51 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
52 import org.opendaylight.mdsal.binding.javav2.spec.structural.AugmentationHolder;
53 import org.opendaylight.yangtools.concepts.Builder;
54 import org.opendaylight.yangtools.concepts.Identifiable;
55
56 public class BuilderRenderer extends BaseRenderer {
57
58     /**
59      * Set of class attributes (fields) which are derived from the getter methods names
60      */
61     private final Set<GeneratedProperty> properties;
62
63     /**
64      * Set of name from properties
65      */
66     private final Map<GeneratedProperty, String> importedNamesForProperties = new HashMap<>();
67
68     /**
69      * list of all imported names for template
70      */
71     private final Map<String, String> importedNames = new HashMap<>();
72
73     /**
74      * Generated property is set if among methods is found one with the name GET_AUGMENTATION_METHOD_NAME
75      */
76     private GeneratedProperty augmentField;
77
78     boolean instantiable = false;
79
80     public BuilderRenderer(final GeneratedType type) {
81         super(type);
82         this.properties = propertiesFromMethods(createMethods());
83         putToImportMap(Builder.class.getSimpleName(), Builder.class.getPackage().getName());
84         putToImportMap(type.getName(), type.getPackageName());
85     }
86
87     @Override
88     protected String packageDefinition() {
89         final StringBuilder sb = new StringBuilder();
90         sb.append("package ")
91                 .append(((GeneratedTypeForBuilder)getType()).getPackageNameForBuilder())
92                 .append(";\n\n");
93         return sb.toString();
94     }
95
96     @Override
97     protected boolean hasSamePackage(final String importedTypePackageName) {
98         return ((GeneratedTypeForBuilder)getType()).getPackageNameForBuilder()
99                 .equals(importedTypePackageName);
100     }
101
102     /**
103      * Creates set of generated property instances from getter <code>methods</code>.
104      *
105      * @param methods set of method signature instances which should be transformed to list of properties
106      * @return set of generated property instances which represents the getter <code>methods</code>
107      */
108     private Set<GeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
109         if (methods == null || methods.isEmpty()) {
110             return Collections.emptySet();
111         }
112         final Set<GeneratedProperty> result = new LinkedHashSet<>();
113         for (MethodSignature method : methods) {
114             final GeneratedProperty createdField = propertyFromGetter(method);
115             if (createdField != null) {
116                 result.add(createdField);
117                 importedNamesForProperties.put(createdField, importedName(createdField.getReturnType()));
118             }
119         }
120         return result;
121     }
122
123     /**
124      * Creates generated property instance from the getter <code>method</code> name and return type.
125      *
126      * @param method method signature from which is the method name and return type obtained
127      * @return generated property instance for the getter <code>method</code>
128      * @throws IllegalArgumentException
129      *  <li>if the <code>method</code> equals <code>null</code></li>
130      *  <li>if the name of the <code>method</code> equals <code>null</code></li>
131      *  <li>if the name of the <code>method</code> is empty</li>
132      *  <li>if the return type of the <code>method</code> equals <code>null</code></li>
133      */
134     private GeneratedProperty propertyFromGetter(final MethodSignature method) {
135         Preconditions.checkArgument(method != null, "Method cannot be NULL");
136         Preconditions.checkArgument(!Strings.isNullOrEmpty(method.getName()), "Method name cannot be NULL or empty");
137         Preconditions.checkArgument(method.getReturnType() != null, "Method return type reference cannot be NULL");
138         final String prefix = Types.BOOLEAN.equals(method.getReturnType()) ? "is" : "get";
139         if (method.getName().startsWith(prefix)) {
140             final String fieldName = toFirstLower(method.getName().substring(prefix.length()));
141             final GeneratedTOBuilderImpl tmpGenTO = new GeneratedTOBuilderImpl("foo", "foo");
142             tmpGenTO.addProperty(fieldName)
143                     .setReturnType(method.getReturnType());
144             return tmpGenTO.toInstance().getProperties().get(0);
145         }
146         return null;
147     }
148
149     /**
150      * Returns set of method signature instances which contains all the methods of the <code>genType</code>
151      * and all the methods of the implemented interfaces.
152      *
153      * @returns set of method signature instances
154      */
155     private Set<MethodSignature> createMethods() {
156         final Set<MethodSignature> methods = new LinkedHashSet<>();
157         methods.addAll(getType().getMethodDefinitions());
158         collectImplementedMethods(methods, getType().getImplements());
159         final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(
160                 new AlphabeticallyTypeMemberComparator<MethodSignature>())
161                 .addAll(methods)
162                 .build();
163         return sortedMethods;
164     }
165
166     /**
167      * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
168      * and recursively their implemented interfaces.
169      *
170      * @param methods set of method signatures
171      * @param implementedIfcs list of implemented interfaces
172      */
173     private void collectImplementedMethods(final Set<MethodSignature> methods, List<Type> implementedIfcs) {
174         if (implementedIfcs != null && !implementedIfcs.isEmpty()) {
175             for (Type implementedIfc : implementedIfcs) {
176                 if ((implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))) {
177                     final GeneratedType ifc = (GeneratedType) implementedIfc;
178                     //TODO:temporarily eliminated for through compiling, to be restored in "support choice" patch.
179                   //  if (implementedIfc instanceof GeneratedTypeForBuilder) {
180                         methods.addAll(ifc.getMethodDefinitions());
181                         collectImplementedMethods(methods, ifc.getImplements());
182                   //  }
183                 } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
184                     for (Method method : Augmentable.class.getMethods()) {
185                         if ("getAugmentation".equals(method.getName())) {
186                             final String fullyQualifiedName = method.getReturnType().getName();
187                             final String aPackage = getPackage(fullyQualifiedName);
188                             final String name = getName(fullyQualifiedName);
189                             final GeneratedTOBuilderImpl generatedTOBuilder = new GeneratedTOBuilderImpl(aPackage, name);
190                             final ReferencedTypeImpl referencedType = new ReferencedTypeImpl(aPackage, name, true);
191                             final ReferencedTypeImpl generic = new ReferencedTypeImpl(getType().getPackageName(),
192                                     getType().getName(), true);
193                             final ParameterizedType parametrizedReturnType = Types.parameterizedTypeFor(referencedType, generic);
194                             generatedTOBuilder.addMethod(method.getName()).setReturnType(parametrizedReturnType);
195                             augmentField = propertyFromGetter(generatedTOBuilder.toInstance().getMethodDefinitions().get(0));
196                             importedNames.put("map", importedName(Map.class));
197                             importedNames.put("hashMap", importedName(HashMap.class));
198                             importedNames.put("class", importedName(Class.class));
199 //                            To do This is for third party, is it needed ?
200                             importedNames.put("augmentationHolder", importedName(AugmentationHolder.class));
201                             importedNames.put("collections", importedName(Collections.class));
202                             importedNames.put("augmentFieldReturnType", importedName(augmentField.getReturnType()));
203                         }
204                     }
205                 } else if (Instantiable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
206                     importedNames.put("class", importedName(Class.class));
207                     instantiable = true;
208                 }
209             }
210         }
211     }
212
213     /**
214      * Returns the name of the package from <code>fullyQualifiedName</code>.
215      *
216      * @param fullyQualifiedName string with fully qualified type name (package + type)
217      * @return string with the package name
218      */
219     private String getPackage(final String fullyQualifiedName) {
220         final int lastDotIndex = fullyQualifiedName.lastIndexOf(DOT);
221         return (lastDotIndex == -1) ? "" : fullyQualifiedName.substring(0, lastDotIndex);
222     }
223
224     /**
225      * Returns the name of tye type from <code>fullyQualifiedName</code>
226      *
227      * @param fullyQualifiedName string with fully qualified type name (package + type)
228      * @return string with the name of the type
229      */
230     private String getName(final String fullyQualifiedName) {
231         final int lastDotIndex = fullyQualifiedName.lastIndexOf(DOT);
232         return (lastDotIndex == -1) ? fullyQualifiedName : fullyQualifiedName.substring(lastDotIndex + 1);
233     }
234
235     public static Set<Type> getAllIfcs(final Type type) {
236         final Set<Type> baseIfcs = new HashSet<>();
237         if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) {
238             for (Type impl : ((GeneratedType)type).getImplements()) {
239                 if (impl instanceof GeneratedType && !(((GeneratedType)impl).getMethodDefinitions().isEmpty())) {
240                     baseIfcs.add(impl);
241                 }
242                 baseIfcs.addAll(getAllIfcs(impl));
243             }
244         }
245         return baseIfcs;
246     }
247
248     /**
249      * Method is used to find out if given type implements any interface from uses.
250      */
251     public static boolean hasImplementsFromUses(GeneratedType type) {
252         for (Type impl : getAllIfcs(type)) {
253             if ((impl instanceof GeneratedType) && !(((GeneratedType)impl).getMethodDefinitions().isEmpty())) {
254                 return true;
255             }
256         }
257         return false;
258     }
259
260     public static Set<String> toListOfNames(final Set<Type> types) {
261         final Set<String> names = new HashSet<>();
262         for (Type currentType : types) {
263             names.add(currentType.getFullyQualifiedName());
264         }
265         return names;
266     }
267
268     @Override
269     protected String body() {
270         final String parentTypeForBuilderName;
271         importedNames.put("genType", importedName(getType()));
272         importedNames.put("objects", importedName(Objects.class));
273         importedNames.put("object", importedName(Object.class));
274         importedNames.put("string", importedName(String.class));
275         importedNames.put("arrays", importedName(Arrays.class));
276         importedNames.put("stringBuilder", importedName(StringBuilder.class));
277         importedNames.put("treeNode", importedName(TreeNode.class));
278         importedNames.put("instantiable", importedName(Instantiable.class));
279         importedNames.put("item", importedName(Item.class));
280         if (getType().getParentType() != null) {
281             importedNames.put("parent", importedName(getType().getParentType()));
282             parentTypeForBuilderName = getType().getParentType().getFullyQualifiedName();
283         } else if (getType().getParentTypeForBuilder() != null) {
284             importedNames.put("parentTypeForBuilder", importedName(getType().getParentTypeForBuilder()));
285             parentTypeForBuilderName = getType().getParentTypeForBuilder().getFullyQualifiedName();
286         } else {
287             parentTypeForBuilderName = null;
288         }
289
290         boolean childTreeNode = false;
291         if (getType().getImplements().contains(BindingTypes.TREE_CHILD_NODE)) {
292             childTreeNode = true;
293         }
294
295         importedNames.put("augmentation", importedName(Augmentation.class));
296         importedNames.put("classInstMap", importedName(ClassToInstanceMap.class));
297
298         // list for generate copy constructor
299         final String copyConstructorHelper = generateListForCopyConstructor();
300         List<String> getterMethods = new ArrayList<>(Collections2.transform(properties, this::getterMethod));
301
302         return builderTemplate.render(getType(), properties, importedNames, importedNamesForProperties, augmentField,
303             copyConstructorHelper, getterMethods, parentTypeForBuilderName, childTreeNode, instantiable)
304                 .body();
305     }
306
307     private String generateListForCopyConstructor() {
308         final List allProps = new ArrayList<>(properties);
309         final boolean isList = implementsIfc(getType(), Types.parameterizedTypeFor(Types.typeForClass(Identifiable.class),
310                 getType()));
311         final Type keyType = getKey(getType());
312         if (isList && keyType != null) {
313             final List<GeneratedProperty> keyProps = ((GeneratedTransferObject) keyType).getProperties();
314             final Comparator<GeneratedProperty> function = (GeneratedProperty p1, GeneratedProperty p2) -> {
315                 String name2 = p1.getName();
316                 String name3 = p2.getName();
317                 return name2.compareTo(name3);
318             };
319             Collections.sort(keyProps, function);
320             for (GeneratedProperty keyProp : keyProps) {
321                 removeProperty(allProps, keyProp.getName());
322             }
323             removeProperty(allProps, "key");
324             importedNames.put("keyTypeConstructor", importedName(keyType));
325             return builderConstructorHelperTemplate.render(allProps, keyProps, importedNames, getPropertyList(allProps))
326                     .body();
327         }
328         return builderConstructorHelperTemplate.render(allProps, null, importedNames, null).body();
329     }
330
331     private Type getKey(final GeneratedType genType) {
332         for (MethodSignature methodSignature : genType.getMethodDefinitions()) {
333             if ("getKey".equals(methodSignature.getName())) {
334                 return methodSignature.getReturnType();
335             }
336         }
337         return null;
338     }
339
340     private boolean implementsIfc(final GeneratedType type, final Type impl) {
341         return type.getImplements().contains(impl);
342     }
343
344     private void removeProperty(final Collection<GeneratedProperty> properties, final String name) {
345         for (final GeneratedProperty property : properties) {
346             if (name.equals(property.getName())) {
347                 properties.remove(property);
348                 break;
349             }
350         }
351     }
352 }