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.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;
30 import java.util.Objects;
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;
54 public class BuilderRenderer extends BaseRenderer {
57 * Set of class attributes (fields) which are derived from the getter methods names
59 private final Set<GeneratedProperty> properties;
62 * Set of name from properties
64 private final Map<GeneratedProperty, String> importedNamesForProperties = new HashMap<>();
67 * list of all imported names for template
69 private final Map<String, String> importedNames = new HashMap<>();
72 * Generated property is set if among methods is found one with the name GET_AUGMENTATION_METHOD_NAME
74 private GeneratedProperty augmentField;
76 boolean instantiable = false;
78 public BuilderRenderer(final GeneratedType type) {
80 this.properties = propertiesFromMethods(createMethods());
81 putToImportMap(Builder.class.getSimpleName(), Builder.class.getPackage().getName());
85 * Creates set of generated property instances from getter <code>methods</code>.
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>
90 private Set<GeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
91 if (methods == null || methods.isEmpty()) {
92 return Collections.emptySet();
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()));
106 * Creates generated property instance from the getter <code>method</code> name and return type.
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>
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);
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.
135 * @returns set of method signature instances
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>())
145 return sortedMethods;
149 * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
150 * and recursively their implemented interfaces.
152 * @param methods set of method signatures
153 * @param implementedIfcs list of implemented interfaces
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()));
184 } else if (Instantiable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
185 importedNames.put("class", importedName(Class.class));
193 * Returns the name of the package from <code>fullyQualifiedName</code>.
195 * @param fullyQualifiedName string with fully qualified type name (package + type)
196 * @return string with the package name
198 private String getPackage(final String fullyQualifiedName) {
199 final int lastDotIndex = fullyQualifiedName.lastIndexOf(DOT);
200 return (lastDotIndex == -1) ? "" : fullyQualifiedName.substring(0, lastDotIndex);
204 * Returns the name of tye type from <code>fullyQualifiedName</code>
206 * @param fullyQualifiedName string with fully qualified type name (package + type)
207 * @return string with the name of the type
209 private String getName(final String fullyQualifiedName) {
210 final int lastDotIndex = fullyQualifiedName.lastIndexOf(DOT);
211 return (lastDotIndex == -1) ? fullyQualifiedName : fullyQualifiedName.substring(lastDotIndex + 1);
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())) {
221 baseIfcs.addAll(getAllIfcs(impl));
228 * Method is used to find out if given type implements any interface from uses.
230 public static boolean hasImplementsFromUses(GeneratedType type) {
231 for (Type impl : getAllIfcs(type)) {
232 if ((impl instanceof GeneratedType) && !(((GeneratedType)impl).getMethodDefinitions().isEmpty())) {
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());
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();
265 parentTypeForBuilderName = null;
268 boolean childTreeNode = false;
269 if (getType().getImplements().contains(BindingTypes.TREE_CHILD_NODE)) {
270 childTreeNode = true;
273 importedNames.put("augmentation", importedName(Augmentation.class));
274 importedNames.put("classInstMap", importedName(ClassToInstanceMap.class));
276 // list for generate copy constructor
277 final String copyConstructorHelper = generateListForCopyConstructor();
278 List<String> getterMethods = new ArrayList<>(Collections2.transform(properties, this::getterMethod));
280 return builderTemplate.render(getType(), properties, importedNames, importedNamesForProperties, augmentField,
281 copyConstructorHelper, getterMethods, parentTypeForBuilderName, childTreeNode, instantiable)
285 private String generateListForCopyConstructor() {
286 final List allProps = new ArrayList<>(properties);
287 final boolean isList = implementsIfc(getType(), Types.parameterizedTypeFor(Types.typeForClass(Identifiable.class),
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);
297 Collections.sort(keyProps, function);
298 for (GeneratedProperty keyProp : keyProps) {
299 removeProperty(allProps, keyProp.getName());
301 removeProperty(allProps, "key");
302 importedNames.put("keyTypeConstructor", importedName(keyType));
303 return builderConstructorHelperTemplate.render(allProps, keyProps, importedNames, getPropertyList(allProps))
306 return builderConstructorHelperTemplate.render(allProps, null, importedNames, null).body();
309 private Type getKey(final GeneratedType genType) {
310 for (MethodSignature methodSignature : genType.getMethodDefinitions()) {
311 if ("getKey".equals(methodSignature.getName())) {
312 return methodSignature.getReturnType();
318 private boolean implementsIfc(final GeneratedType type, final Type impl) {
319 return type.getImplements().contains(impl);
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);