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