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