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