98d111e894950cc67073a092d960a6a92b5f8a4b
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / BuilderGenerator.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.mdsal.binding.java.api.generator;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTABLE_AUGMENTATION_NAME;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.ImmutableSortedSet;
15 import java.lang.reflect.Method;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Comparator;
19 import java.util.LinkedHashSet;
20 import java.util.List;
21 import java.util.Set;
22 import org.eclipse.xtext.xbase.lib.StringExtensions;
23 import org.opendaylight.mdsal.binding.model.api.CodeGenerator;
24 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
25 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
26 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
27 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
28 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
29 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
30 import org.opendaylight.mdsal.binding.model.api.Type;
31 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
32 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
33 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
34 import org.opendaylight.mdsal.binding.model.util.Types;
35 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.CodegenGeneratedTOBuilder;
36 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.CodegenGeneratedTypeBuilder;
37 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
38 import org.opendaylight.yangtools.yang.binding.Augmentable;
39 import org.opendaylight.yangtools.yang.binding.Augmentation;
40
41 /**
42  * Transformator of the data from the virtual form to JAVA programming language. The result source code represent java
43  * class. For generation of the source code is used the template written in XTEND language.
44  */
45 public final class BuilderGenerator implements CodeGenerator {
46     private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
47     private static final Type AUGMENTATION_RET_TYPE;
48
49     static {
50         final Method m;
51         try {
52             m = Augmentable.class.getDeclaredMethod(AUGMENTABLE_AUGMENTATION_NAME, Class.class);
53         } catch (NoSuchMethodException e) {
54             throw new ExceptionInInitializerError(e);
55         }
56
57         AUGMENTATION_RET_TYPE = new ReferencedTypeImpl(JavaTypeName.create(m.getReturnType()));
58     }
59
60     /**
61      * Passes via list of implemented types in <code>type</code>.
62      *
63      * @param type JAVA <code>Type</code>
64      * @return boolean value which is true if any of implemented types is of the type <code>Augmentable</code>.
65      */
66     @Override
67     public boolean isAcceptable(final Type type) {
68         if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) {
69             for (Type t : ((GeneratedType) type).getImplements()) {
70                 // "rpc" and "grouping" elements do not implement Augmentable
71                 if (t.getFullyQualifiedName().equals(Augmentable.class.getName())) {
72                     return true;
73                 } else if (t.getFullyQualifiedName().equals(Augmentation.class.getName())) {
74                     return true;
75                 }
76
77             }
78         }
79         return false;
80     }
81
82     /**
83      * Generates JAVA source code for generated type <code>Type</code>. The code is generated according to the template
84      * source code template which is written in XTEND language.
85      */
86     @Override
87     public String generate(final Type type) {
88         if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) {
89             return templateForType((GeneratedType) type).generate();
90         }
91         return "";
92     }
93
94     @Override
95     public String getUnitName(final Type type) {
96         return type.getName() + BuilderTemplate.BUILDER;
97     }
98
99     @VisibleForTesting
100     static BuilderTemplate templateForType(final GeneratedType type) {
101         final GeneratedType genType = type;
102         final JavaTypeName origName = genType.getIdentifier();
103
104         final Set<MethodSignature> methods = new LinkedHashSet<>();
105         final Type augmentType = createMethods(genType, methods);
106         final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR)
107                 .addAll(methods).build();
108
109         final GeneratedTypeBuilder builderTypeBuilder = new CodegenGeneratedTypeBuilder(
110             origName.createSibling(origName.simpleName() + BuilderTemplate.BUILDER));
111
112         final GeneratedTOBuilder implTypeBuilder = builderTypeBuilder.addEnclosingTransferObject(
113             origName.simpleName() + "Impl");
114         implTypeBuilder.addImplementsType(genType);
115
116         return new BuilderTemplate(builderTypeBuilder.build(), genType, propertiesFromMethods(sortedMethods),
117             augmentType, getKey(genType));
118     }
119
120     private static Type getKey(final GeneratedType type) {
121         for (MethodSignature m : type.getMethodDefinitions()) {
122             if (BindingMapping.IDENTIFIABLE_KEY_NAME.equals(m.getName())) {
123                 return m.getReturnType();
124             }
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 static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
136         methods.addAll(type.getMethodDefinitions());
137         return collectImplementedMethods(type, methods, type.getImplements());
138     }
139
140     /**
141      * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
142      * and recursively their implemented interfaces.
143      *
144      * @param methods set of method signatures
145      * @param implementedIfcs list of implemented interfaces
146      */
147     private static ParameterizedType collectImplementedMethods(final GeneratedType type,
148             final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
149         if (implementedIfcs == null || implementedIfcs.isEmpty()) {
150             return null;
151         }
152
153         ParameterizedType augmentType = null;
154         for (Type implementedIfc : implementedIfcs) {
155             if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
156                 final GeneratedType ifc = (GeneratedType) implementedIfc;
157                 methods.addAll(ifc.getMethodDefinitions());
158
159                 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
160                 if (t != null && augmentType == null) {
161                     augmentType = t;
162                 }
163             } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
164                 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE,
165                     new ReferencedTypeImpl(type.getIdentifier()));
166             }
167         }
168
169         return augmentType;
170     }
171
172     /**
173      * Creates set of generated property instances from getter <code>methods</code>.
174      *
175      * @param set of method signature instances which should be transformed to list of properties
176      * @return set of generated property instances which represents the getter <code>methods</code>
177      */
178     private static Set<GeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
179         if (methods == null || methods.isEmpty()) {
180             return Collections.emptySet();
181         }
182         final Set<GeneratedProperty> result = new LinkedHashSet<>();
183         for (MethodSignature m : methods) {
184             final GeneratedProperty createdField = propertyFromGetter(m);
185             if (createdField != null) {
186                 result.add(createdField);
187             }
188         }
189         return result;
190     }
191
192     /**
193      * Creates generated property instance from the getter <code>method</code> name and return type.
194      *
195      * @param method method signature from which is the method name and return type obtained
196      * @return generated property instance for the getter <code>method</code>
197      * @throws IllegalArgumentException <ul>
198      *  <li>if the <code>method</code> equals <code>null</code></li>
199      *  <li>if the name of the <code>method</code> equals <code>null</code></li>
200      *  <li>if the name of the <code>method</code> is empty</li>
201      *  <li>if the return type of the <code>method</code> equals <code>null</code></li>
202      * </ul>
203      */
204     private static GeneratedProperty propertyFromGetter(final MethodSignature method) {
205         checkArgument(method != null);
206         checkArgument(method.getReturnType() != null);
207         checkArgument(method.getName() != null);
208         checkArgument(!method.getName().isEmpty());
209         if (method.isDefault()) {
210             return null;
211         }
212         final String prefix = BindingMapping.getGetterPrefix(Types.BOOLEAN.equals(method.getReturnType()));
213         if (!method.getName().startsWith(prefix)) {
214             return null;
215         }
216
217         final String fieldName = StringExtensions.toFirstLower(method.getName().substring(prefix.length()));
218         final GeneratedTOBuilder tmpGenTO = new CodegenGeneratedTOBuilder(JavaTypeName.create("foo", "foo"));
219         tmpGenTO.addProperty(fieldName).setReturnType(method.getReturnType());
220         return tmpGenTO.build().getProperties().get(0);
221     }
222 }