Binding generator v2 - uses statement - support choice
[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                     if (implementedIfc instanceof GeneratedTypeForBuilder) {
179                         methods.addAll(ifc.getMethodDefinitions());
180                     }
181                     collectImplementedMethods(methods, ifc.getImplements());
182                 } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
183                     for (Method method : Augmentable.class.getMethods()) {
184                         if ("getAugmentation".equals(method.getName())) {
185                             final String fullyQualifiedName = method.getReturnType().getName();
186                             final String aPackage = getPackage(fullyQualifiedName);
187                             final String name = getName(fullyQualifiedName);
188                             final GeneratedTOBuilderImpl generatedTOBuilder = new GeneratedTOBuilderImpl(aPackage, name);
189                             final ReferencedTypeImpl referencedType = new ReferencedTypeImpl(aPackage, name, true);
190                             final ReferencedTypeImpl generic = new ReferencedTypeImpl(getType().getPackageName(),
191                                     getType().getName(), true);
192                             final ParameterizedType parametrizedReturnType = Types.parameterizedTypeFor(referencedType, generic);
193                             generatedTOBuilder.addMethod(method.getName()).setReturnType(parametrizedReturnType);
194                             augmentField = propertyFromGetter(generatedTOBuilder.toInstance().getMethodDefinitions().get(0));
195                             importedNames.put("map", importedName(Map.class));
196                             importedNames.put("hashMap", importedName(HashMap.class));
197                             importedNames.put("class", importedName(Class.class));
198 //                            To do This is for third party, is it needed ?
199                             importedNames.put("augmentationHolder", importedName(AugmentationHolder.class));
200                             importedNames.put("collections", importedName(Collections.class));
201                             importedNames.put("augmentFieldReturnType", importedName(augmentField.getReturnType()));
202                         }
203                     }
204                 } else if (Instantiable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
205                     importedNames.put("class", importedName(Class.class));
206                     instantiable = true;
207                 }
208             }
209         }
210     }
211
212     /**
213      * Returns the name of the package from <code>fullyQualifiedName</code>.
214      *
215      * @param fullyQualifiedName string with fully qualified type name (package + type)
216      * @return string with the package name
217      */
218     private String getPackage(final String fullyQualifiedName) {
219         final int lastDotIndex = fullyQualifiedName.lastIndexOf(DOT);
220         return (lastDotIndex == -1) ? "" : fullyQualifiedName.substring(0, lastDotIndex);
221     }
222
223     /**
224      * Returns the name of tye type from <code>fullyQualifiedName</code>
225      *
226      * @param fullyQualifiedName string with fully qualified type name (package + type)
227      * @return string with the name of the type
228      */
229     private String getName(final String fullyQualifiedName) {
230         final int lastDotIndex = fullyQualifiedName.lastIndexOf(DOT);
231         return (lastDotIndex == -1) ? fullyQualifiedName : fullyQualifiedName.substring(lastDotIndex + 1);
232     }
233
234     public static Set<Type> getAllIfcs(final Type type) {
235         final Set<Type> baseIfcs = new HashSet<>();
236         if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) {
237             for (Type impl : ((GeneratedType)type).getImplements()) {
238                 if (impl instanceof GeneratedType && !(((GeneratedType)impl).getMethodDefinitions().isEmpty())) {
239                     baseIfcs.add(impl);
240                 }
241                 baseIfcs.addAll(getAllIfcs(impl));
242             }
243         }
244         return baseIfcs;
245     }
246
247     /**
248      * Method is used to find out if given type implements any interface from uses.
249      */
250     public static boolean hasImplementsFromUses(GeneratedType type) {
251         for (Type impl : getAllIfcs(type)) {
252             if ((impl instanceof GeneratedType) && !(((GeneratedType)impl).getMethodDefinitions().isEmpty())) {
253                 return true;
254             }
255         }
256         return false;
257     }
258
259     public static Set<String> toListOfNames(final Set<Type> types) {
260         final Set<String> names = new HashSet<>();
261         for (Type currentType : types) {
262             names.add(currentType.getFullyQualifiedName());
263         }
264         return names;
265     }
266
267     @Override
268     protected String body() {
269         final String parentTypeForBuilderName;
270         importedNames.put("genType", importedName(getType()));
271         importedNames.put("objects", importedName(Objects.class));
272         importedNames.put("object", importedName(Object.class));
273         importedNames.put("string", importedName(String.class));
274         importedNames.put("arrays", importedName(Arrays.class));
275         importedNames.put("stringBuilder", importedName(StringBuilder.class));
276         importedNames.put("treeNode", importedName(TreeNode.class));
277         importedNames.put("instantiable", importedName(Instantiable.class));
278         importedNames.put("item", importedName(Item.class));
279         if (getType().getParentType() != null) {
280             importedNames.put("parent", importedName(getType().getParentType()));
281             parentTypeForBuilderName = getType().getParentType().getFullyQualifiedName();
282         } else if (getType().getParentTypeForBuilder() != null) {
283             importedNames.put("parentTypeForBuilder", importedName(getType().getParentTypeForBuilder()));
284             parentTypeForBuilderName = getType().getParentTypeForBuilder().getFullyQualifiedName();
285         } else {
286             parentTypeForBuilderName = null;
287         }
288
289         boolean childTreeNode = false;
290         if (getType().getImplements().contains(BindingTypes.TREE_CHILD_NODE)) {
291             childTreeNode = true;
292         }
293
294         importedNames.put("augmentation", importedName(Augmentation.class));
295         importedNames.put("classInstMap", importedName(ClassToInstanceMap.class));
296
297         // list for generate copy constructor
298         final String copyConstructorHelper = generateListForCopyConstructor();
299         List<String> getterMethods = new ArrayList<>(Collections2.transform(properties, this::getterMethod));
300
301         return builderTemplate.render(getType(), properties, importedNames, importedNamesForProperties, augmentField,
302             copyConstructorHelper, getterMethods, parentTypeForBuilderName, childTreeNode, instantiable)
303                 .body();
304     }
305
306     private String generateListForCopyConstructor() {
307         final List allProps = new ArrayList<>(properties);
308         final boolean isList = implementsIfc(getType(), Types.parameterizedTypeFor(Types.typeForClass(Identifiable.class),
309                 getType()));
310         final Type keyType = getKey(getType());
311         if (isList && keyType != null) {
312             final List<GeneratedProperty> keyProps = ((GeneratedTransferObject) keyType).getProperties();
313             final Comparator<GeneratedProperty> function = (GeneratedProperty p1, GeneratedProperty p2) -> {
314                 String name2 = p1.getName();
315                 String name3 = p2.getName();
316                 return name2.compareTo(name3);
317             };
318             Collections.sort(keyProps, function);
319             for (GeneratedProperty keyProp : keyProps) {
320                 removeProperty(allProps, keyProp.getName());
321             }
322             removeProperty(allProps, "key");
323             importedNames.put("keyTypeConstructor", importedName(keyType));
324             return builderConstructorHelperTemplate.render(allProps, keyProps, importedNames, getPropertyList(allProps))
325                     .body();
326         }
327         return builderConstructorHelperTemplate.render(allProps, null, importedNames, null).body();
328     }
329
330     private Type getKey(final GeneratedType genType) {
331         for (MethodSignature methodSignature : genType.getMethodDefinitions()) {
332             if ("getKey".equals(methodSignature.getName())) {
333                 return methodSignature.getReturnType();
334             }
335         }
336         return null;
337     }
338
339     private boolean implementsIfc(final GeneratedType type, final Type impl) {
340         return type.getImplements().contains(impl);
341     }
342
343     private void removeProperty(final Collection<GeneratedProperty> properties, final String name) {
344         for (final GeneratedProperty property : properties) {
345             if (name.equals(property.getName())) {
346                 properties.remove(property);
347                 break;
348             }
349         }
350     }
351 }