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