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