2 * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers;
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;
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;
31 import java.util.Objects;
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.MethodSignature;
44 import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType;
45 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
46 import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable;
47 import org.opendaylight.mdsal.binding.javav2.spec.base.Item;
48 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
49 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable;
50 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
51 import org.opendaylight.mdsal.binding.javav2.spec.structural.AugmentationHolder;
52 import org.opendaylight.yangtools.concepts.Builder;
53 import org.opendaylight.yangtools.concepts.Identifiable;
55 public class BuilderRenderer extends BaseRenderer {
58 * Set of class attributes (fields) which are derived from the getter methods names
60 private final Set<GeneratedProperty> properties;
63 * Set of name from properties
65 private final Map<GeneratedProperty, String> importedNamesForProperties = new HashMap<>();
68 * list of all imported names for template
70 private final Map<String, String> importedNames = new HashMap<>();
73 * Generated property is set if among methods is found one with the name GET_AUGMENTATION_METHOD_NAME
75 private GeneratedProperty augmentField;
77 boolean instantiable = false;
79 public BuilderRenderer(final GeneratedType type) {
81 this.properties = propertiesFromMethods(createMethods());
82 putToImportMap(Builder.class.getSimpleName(), Builder.class.getPackage().getName());
86 * Creates set of generated property instances from getter <code>methods</code>.
88 * @param methods set of method signature instances which should be transformed to list of properties
89 * @return set of generated property instances which represents the getter <code>methods</code>
91 private Set<GeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
92 if (methods == null || methods.isEmpty()) {
93 return Collections.emptySet();
95 final Set<GeneratedProperty> result = new LinkedHashSet<>();
96 for (MethodSignature method : methods) {
97 final GeneratedProperty createdField = propertyFromGetter(method);
98 if (createdField != null) {
99 result.add(createdField);
100 importedNamesForProperties.put(createdField, importedName(createdField.getReturnType()));
107 * Creates generated property instance from the getter <code>method</code> name and return type.
109 * @param method method signature from which is the method name and return type obtained
110 * @return generated property instance for the getter <code>method</code>
111 * @throws IllegalArgumentException
112 * <li>if the <code>method</code> equals <code>null</code></li>
113 * <li>if the name of the <code>method</code> equals <code>null</code></li>
114 * <li>if the name of the <code>method</code> is empty</li>
115 * <li>if the return type of the <code>method</code> equals <code>null</code></li>
117 private GeneratedProperty propertyFromGetter(final MethodSignature method) {
118 Preconditions.checkArgument(method != null, "Method cannot be NULL");
119 Preconditions.checkArgument(!Strings.isNullOrEmpty(method.getName()), "Method name cannot be NULL or empty");
120 Preconditions.checkArgument(method.getReturnType() != null, "Method return type reference cannot be NULL");
121 final String prefix = Types.BOOLEAN.equals(method.getReturnType()) ? "is" : "get";
122 if (method.getName().startsWith(prefix)) {
123 final String fieldName = toFirstLower(method.getName().substring(prefix.length()));
124 final GeneratedTOBuilderImpl tmpGenTO = new GeneratedTOBuilderImpl("foo", "foo");
125 tmpGenTO.addProperty(fieldName)
126 .setReturnType(method.getReturnType());
127 return tmpGenTO.toInstance().getProperties().get(0);
133 * Returns set of method signature instances which contains all the methods of the <code>genType</code>
134 * and all the methods of the implemented interfaces.
136 * @returns set of method signature instances
138 private Set<MethodSignature> createMethods() {
139 final Set<MethodSignature> methods = new LinkedHashSet<>();
140 methods.addAll(getType().getMethodDefinitions());
141 collectImplementedMethods(methods, getType().getImplements());
142 final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(
143 new AlphabeticallyTypeMemberComparator<MethodSignature>())
146 return sortedMethods;
150 * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
151 * and recursively their implemented interfaces.
153 * @param methods set of method signatures
154 * @param implementedIfcs list of implemented interfaces
156 private void collectImplementedMethods(final Set<MethodSignature> methods, List<Type> implementedIfcs) {
157 if (implementedIfcs != null && !implementedIfcs.isEmpty()) {
158 for (Type implementedIfc : implementedIfcs) {
159 if ((implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))) {
160 final GeneratedType ifc = (GeneratedType) implementedIfc;
161 methods.addAll(ifc.getMethodDefinitions());
162 collectImplementedMethods(methods, ifc.getImplements());
163 } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
164 for (Method method : Augmentable.class.getMethods()) {
165 if ("getAugmentation".equals(method.getName())) {
166 final String fullyQualifiedName = method.getReturnType().getName();
167 final String aPackage = getPackage(fullyQualifiedName);
168 final String name = getName(fullyQualifiedName);
169 final GeneratedTOBuilderImpl generatedTOBuilder = new GeneratedTOBuilderImpl(aPackage, name);
170 final ReferencedTypeImpl referencedType = new ReferencedTypeImpl(aPackage, name, true);
171 final ReferencedTypeImpl generic = new ReferencedTypeImpl(getType().getPackageName(),
172 getType().getName(), true);
173 final ParameterizedType parametrizedReturnType = Types.parameterizedTypeFor(referencedType, generic);
174 generatedTOBuilder.addMethod(method.getName()).setReturnType(parametrizedReturnType);
175 augmentField = propertyFromGetter(generatedTOBuilder.toInstance().getMethodDefinitions().get(0));
176 importedNames.put("map", importedName(Map.class));
177 importedNames.put("hashMap", importedName(HashMap.class));
178 importedNames.put("class", importedName(Class.class));
179 // To do This is for third party, is it needed ?
180 importedNames.put("augmentationHolder", importedName(AugmentationHolder.class));
181 importedNames.put("collections", importedName(Collections.class));
182 importedNames.put("augmentFieldReturnType", importedName(augmentField.getReturnType()));
185 } else if (Instantiable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
186 importedNames.put("class", importedName(Class.class));
194 * Returns the name of the package from <code>fullyQualifiedName</code>.
196 * @param fullyQualifiedName string with fully qualified type name (package + type)
197 * @return string with the package name
199 private String getPackage(final String fullyQualifiedName) {
200 final int lastDotIndex = fullyQualifiedName.lastIndexOf(DOT);
201 return (lastDotIndex == -1) ? "" : fullyQualifiedName.substring(0, lastDotIndex);
205 * Returns the name of tye type from <code>fullyQualifiedName</code>
207 * @param fullyQualifiedName string with fully qualified type name (package + type)
208 * @return string with the name of the type
210 private String getName(final String fullyQualifiedName) {
211 final int lastDotIndex = fullyQualifiedName.lastIndexOf(DOT);
212 return (lastDotIndex == -1) ? fullyQualifiedName : fullyQualifiedName.substring(lastDotIndex + 1);
215 public static Set<Type> getAllIfcs(final Type type) {
216 final Set<Type> baseIfcs = new HashSet<>();
217 if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) {
218 for (Type impl : ((GeneratedType)type).getImplements()) {
219 if (impl instanceof GeneratedType && !(((GeneratedType)impl).getMethodDefinitions().isEmpty())) {
222 baseIfcs.addAll(getAllIfcs(impl));
229 * Method is used to find out if given type implements any interface from uses.
231 public static boolean hasImplementsFromUses(GeneratedType type) {
232 for (Type impl : getAllIfcs(type)) {
233 if ((impl instanceof GeneratedType) && !(((GeneratedType)impl).getMethodDefinitions().isEmpty())) {
240 public static Set<String> toListOfNames(final Set<Type> types) {
241 final Set<String> names = new HashSet<>();
242 for (Type currentType : types) {
243 names.add(currentType.getFullyQualifiedName());
249 protected String body() {
250 final String parentTypeForBuilderName;
251 importedNames.put("genType", importedName(getType()));
252 importedNames.put("objects", importedName(Objects.class));
253 importedNames.put("object", importedName(Object.class));
254 importedNames.put("string", importedName(String.class));
255 importedNames.put("arrays", importedName(Arrays.class));
256 importedNames.put("stringBuilder", importedName(StringBuilder.class));
257 importedNames.put("treeNode", importedName(TreeNode.class));
258 importedNames.put("instantiable", importedName(Instantiable.class));
259 importedNames.put("item", importedName(Item.class));
260 if (getType().getParentType() != null) {
261 importedNames.put("parent", importedName(getType().getParentType()));
262 parentTypeForBuilderName = getType().getParentType().getFullyQualifiedName();
263 } else if (getType().getParentTypeForBuilder() != null) {
264 importedNames.put("parentTypeForBuilder", importedName(getType().getParentTypeForBuilder()));
265 parentTypeForBuilderName = getType().getParentTypeForBuilder().getFullyQualifiedName();
267 parentTypeForBuilderName = null;
270 boolean childTreeNode = false;
271 if (getType().getImplements().contains(BindingTypes.TREE_CHILD_NODE)) {
272 childTreeNode = true;
275 importedNames.put("augmentation", importedName(Augmentation.class));
276 importedNames.put("classInstMap", importedName(ClassToInstanceMap.class));
278 // list for generate copy constructor
279 final String copyConstructorHelper = generateListForCopyConstructor();
280 List<String> getterMethods = new ArrayList<>(Collections2.transform(properties, this::getterMethod));
282 return builderTemplate.render(getType(), properties, importedNames, importedNamesForProperties, augmentField,
283 copyConstructorHelper, getterMethods, parentTypeForBuilderName, childTreeNode, instantiable)
287 private String generateListForCopyConstructor() {
288 final List allProps = new ArrayList<>(properties);
289 final boolean isList = implementsIfc(getType(), Types.parameterizedTypeFor(Types.typeForClass(Identifiable.class),
291 final Type keyType = getKey(getType());
292 if (isList && keyType != null) {
293 final List<GeneratedProperty> keyProps = ((GeneratedTransferObject) keyType).getProperties();
294 final Comparator<GeneratedProperty> function = (GeneratedProperty p1, GeneratedProperty p2) -> {
295 String name2 = p1.getName();
296 String name3 = p2.getName();
297 return name2.compareTo(name3);
299 Collections.sort(keyProps, function);
300 for (GeneratedProperty keyProp : keyProps) {
301 removeProperty(allProps, keyProp.getName());
303 removeProperty(allProps, "key");
304 importedNames.put("keyTypeConstructor", importedName(keyType));
305 return builderConstructorHelperTemplate.render(allProps, keyProps, importedNames, getPropertyList(allProps))
308 return builderConstructorHelperTemplate.render(allProps, null, importedNames, null).body();
311 private Type getKey(final GeneratedType genType) {
312 for (MethodSignature methodSignature : genType.getMethodDefinitions()) {
313 if ("getKey".equals(methodSignature.getName())) {
314 return methodSignature.getReturnType();
320 private boolean implementsIfc(final GeneratedType type, final Type impl) {
321 return type.getImplements().contains(impl);
324 private void removeProperty(final Collection<GeneratedProperty> properties, final String name) {
325 for (final GeneratedProperty property : properties) {
326 if (name.equals(property.getName())) {
327 properties.remove(property);