Merge topic 'archetype'
[controller.git] / opendaylight / config / yang-jmx-generator-plugin / src / main / java / org / opendaylight / controller / config / yangjmxgenerator / plugin / ftl / TemplateFactory.java
1 /*
2  * Copyright (c) 2013 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.controller.config.yangjmxgenerator.plugin.ftl;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.Lists;
12 import com.google.common.collect.Maps;
13 import java.util.ArrayList;
14 import java.util.Arrays;
15 import java.util.Collections;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import javax.management.openmbean.SimpleType;
21 import org.opendaylight.controller.config.api.DependencyResolver;
22 import org.opendaylight.controller.config.api.IdentityAttributeRef;
23 import org.opendaylight.controller.config.api.RuntimeBeanRegistratorAwareModule;
24 import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
25 import org.opendaylight.controller.config.api.runtime.RuntimeBean;
26 import org.opendaylight.controller.config.spi.AbstractModule;
27 import org.opendaylight.controller.config.yangjmxgenerator.AbstractEntry;
28 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
29 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
30 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry.Rpc;
31 import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
32 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AbstractDependencyAttribute;
33 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
34 import org.opendaylight.controller.config.yangjmxgenerator.attribute.Dependency;
35 import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
36 import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
37 import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
38 import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
39 import org.opendaylight.controller.config.yangjmxgenerator.attribute.TypedAttribute;
40 import org.opendaylight.controller.config.yangjmxgenerator.attribute.VoidAttribute;
41 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
42 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation.Parameter;
43 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Constructor;
44 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
45 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Header;
46 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.IdentityRefModuleField;
47 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDeclaration;
48 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
49 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.ModuleField;
50 import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
51 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
52 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
53 import org.opendaylight.yangtools.sal.binding.model.api.Type;
54
55 public class TemplateFactory {
56
57     /**
58      * Get map of file name as key, FtlFile instance representing runtime mx
59      * bean as value that should be persisted from this instance.
60      */
61     public static Map<String, FtlTemplate> getTOAndMXInterfaceFtlFiles(
62             RuntimeBeanEntry entry) {
63         Map<String, FtlTemplate> result = new HashMap<>();
64         { // create GeneralInterfaceFtlFile for runtime MXBean. Attributes will
65           // be transformed to getter methods
66             String mxBeanTypeName = entry.getJavaNameOfRuntimeMXBean();
67             List<String> extendedInterfaces = Arrays.asList(RuntimeBean.class
68                     .getCanonicalName());
69             List<MethodDeclaration> methods = new ArrayList<>();
70
71             // convert attributes to getters
72             for (AttributeIfc attributeIfc : entry.getAttributes()) {
73                 String returnType;
74                 returnType = getReturnType(attributeIfc);
75                 String getterName = "get"
76                         + attributeIfc.getUpperCaseCammelCase();
77                 MethodDeclaration getter = new MethodDeclaration(returnType,
78                         getterName, Collections.<Field> emptyList());
79                 methods.add(getter);
80             }
81
82             // add rpc methods
83             for (Rpc rpc : entry.getRpcs()) {
84                 // convert JavaAttribute parameters into fields
85                 List<Field> fields = new ArrayList<>();
86                 for (JavaAttribute ja : rpc.getParameters()) {
87                     Field field = new Field(Collections.<String> emptyList(),
88                             ja.getType().getFullyQualifiedName(),
89                             ja.getLowerCaseCammelCase(), ja.getNullableDefaultWrappedForCode());
90                     fields.add(field);
91                 }
92                 MethodDeclaration operation = new MethodDeclaration(
93                         getReturnType(rpc.getReturnType()), rpc.getName(), fields);
94                 methods.add(operation);
95             }
96
97             // FIXME header
98             GeneralInterfaceTemplate runtimeMxBeanIfc = new GeneralInterfaceTemplate(
99                     null, entry.getPackageName(), mxBeanTypeName,
100                     extendedInterfaces, methods);
101
102             result.put(runtimeMxBeanIfc.getTypeDeclaration().getName()
103                     + ".java", runtimeMxBeanIfc);
104         }
105
106         result.putAll(TemplateFactory.tOsFromRbe(entry));
107
108         return result;
109     }
110
111     // FIXME: put into Type.toString
112     static String serializeType(Type type, boolean addWildcards) {
113         if (type instanceof ParameterizedType){
114             ParameterizedType parameterizedType = (ParameterizedType) type;
115             StringBuilder sb = new StringBuilder();
116             sb.append(parameterizedType.getRawType().getFullyQualifiedName());
117             sb.append(addWildcards ? "<? extends " : "<");
118             boolean first = true;
119             for(Type parameter: parameterizedType.getActualTypeArguments()) {
120                 if (first) {
121                     first = false;
122                 } else {
123                     sb.append(",");
124                 }
125                 sb.append(serializeType(parameter));
126             }
127             sb.append(">");
128             return sb.toString();
129         } else {
130             return type.getFullyQualifiedName();
131         }
132     }
133
134     static String serializeType(Type type) {
135         return serializeType(type, false);
136     }
137
138     private static String getReturnType(AttributeIfc attributeIfc) {
139         String returnType;
140         if (attributeIfc instanceof TypedAttribute) {
141             Type type = ((TypedAttribute) attributeIfc).getType();
142             returnType = serializeType(type);
143         } else if (attributeIfc == VoidAttribute.getInstance()) {
144             return "void";
145         } else {
146             throw new UnsupportedOperationException(
147                     "Attribute not supported: "
148                             + attributeIfc.getClass());
149         }
150         return returnType;
151     }
152
153     public static GeneralInterfaceTemplate serviceInterfaceFromSie(
154             ServiceInterfaceEntry sie) {
155
156         List<String> extendedInterfaces = Lists
157                 .newArrayList(AbstractServiceInterface.class.getCanonicalName());
158         if (sie.getBase().isPresent()) {
159             extendedInterfaces.add(sie.getBase().get().getFullyQualifiedName());
160         }
161
162         // FIXME header
163         GeneralInterfaceTemplate sieTemplate = new GeneralInterfaceTemplate(
164                 getHeaderFromEntry(sie), sie.getPackageName(),
165                 sie.getTypeName(), extendedInterfaces,
166                 Lists.<MethodDeclaration> newArrayList());
167         sieTemplate.setJavadoc(sie.getNullableDescription());
168
169         if (sie.getNullableDescription() != null) {
170             sieTemplate.getAnnotations().add(
171                     Annotation.createDescriptionAnnotation(sie
172                             .getNullableDescription()));
173         }
174         sieTemplate.getAnnotations().addAll(Annotation.createSieAnnotations(sie));
175
176         return sieTemplate;
177     }
178
179     public static AbstractFactoryTemplate abstractFactoryTemplateFromMbe(
180             ModuleMXBeanEntry mbe) {
181         AbstractFactoryAttributesProcessor attrProcessor = new AbstractFactoryAttributesProcessor();
182         attrProcessor.processAttributes(mbe.getAttributes(),
183                 mbe.getPackageName());
184
185
186
187         return new AbstractFactoryTemplate(getHeaderFromEntry(mbe),
188                 mbe.getPackageName(), mbe.getAbstractFactoryName(),
189                 attrProcessor.getFields()
190         );
191     }
192
193     public static AbstractModuleTemplate abstractModuleTemplateFromMbe(
194             ModuleMXBeanEntry mbe) {
195         AbstractModuleAttributesProcessor attrProcessor = new AbstractModuleAttributesProcessor(mbe.getAttributes());
196
197         List<ModuleField> moduleFields = attrProcessor.getModuleFields();
198         List<String> implementedIfcs = Lists.newArrayList(
199                 mbe.getFullyQualifiedName(mbe.getMXBeanInterfaceName()));
200
201         for (String implementedService : mbe.getProvidedServices().keySet()) {
202             implementedIfcs.add(implementedService);
203         }
204
205         boolean generateRuntime = false;
206         String registratorFullyQualifiedName = null;
207         if (mbe.getRuntimeBeans() != null
208                 && mbe.getRuntimeBeans().isEmpty() == false) {
209             generateRuntime = true;
210             RuntimeBeanEntry rootEntry = RuntimeRegistratorFtlTemplate
211                     .findRoot(mbe.getRuntimeBeans());
212             registratorFullyQualifiedName = rootEntry
213                     .getPackageName()
214                     .concat(".")
215                     .concat(RuntimeRegistratorFtlTemplate.getJavaNameOfRuntimeRegistrator(rootEntry));
216             implementedIfcs.add(RuntimeBeanRegistratorAwareModule.class
217                     .getCanonicalName());
218         }
219
220         List<String> extendedClasses = Collections.singletonList(AbstractModule.class.getCanonicalName() + "<" + mbe.getAbstractModuleName() + ">");
221
222         AbstractModuleTemplate abstractModuleTemplate = new AbstractModuleTemplate(
223                 getHeaderFromEntry(mbe), mbe.getPackageName(),
224                 mbe.getAbstractModuleName(), extendedClasses, implementedIfcs, moduleFields,
225                 attrProcessor.getMethods(), generateRuntime,
226                 registratorFullyQualifiedName);
227
228         if (mbe.getNullableDescription() != null) {
229             abstractModuleTemplate.getAnnotations().add(
230                     Annotation.createDescriptionAnnotation(mbe
231                             .getNullableDescription()));
232         }
233         return abstractModuleTemplate;
234     }
235
236     public static StubFactoryTemplate stubFactoryTemplateFromMbe(
237             ModuleMXBeanEntry mbe) {
238         return new StubFactoryTemplate(getHeaderFromEntry(mbe),
239                 mbe.getPackageName(), mbe.getStubFactoryName(),
240                 mbe.getFullyQualifiedName(mbe.getAbstractFactoryName())
241         );
242     }
243
244     public static GeneralInterfaceTemplate mXBeanInterfaceTemplateFromMbe(
245             ModuleMXBeanEntry mbe) {
246         MXBeanInterfaceAttributesProcessor attrProcessor = new MXBeanInterfaceAttributesProcessor();
247         attrProcessor.processAttributes(mbe.getAttributes());
248         GeneralInterfaceTemplate ifcTemplate = new GeneralInterfaceTemplate(
249                 getHeaderFromEntry(mbe), mbe.getPackageName(),
250                 mbe.getMXBeanInterfaceName(), Lists.<String> newArrayList(),
251                 attrProcessor.getMethods());
252         ifcTemplate.setJavadoc(mbe.getNullableDescription());
253         return ifcTemplate;
254     }
255
256     public static Map<String, GeneralClassTemplate> tOsFromMbe(
257             ModuleMXBeanEntry mbe) {
258         Map<String, GeneralClassTemplate> retVal = Maps.newHashMap();
259         TOAttributesProcessor processor = new TOAttributesProcessor();
260         processor.processAttributes(mbe.getAttributes());
261         for (org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory.TOAttributesProcessor.TOInternal to : processor
262                 .getTOs()) {
263             List<Constructor> constructors = Lists.newArrayList();
264             constructors.add(new Constructor(to.getName(), "super();"));
265
266             Header header = getHeaderFromEntry(mbe);
267             retVal.put(
268                     to.getType(),
269                     new GeneralClassTemplate(header, mbe.getPackageName(), to
270                             .getName(), Collections.<String> emptyList(),
271                             Collections.<String> emptyList(), to.getFields(),
272                             to.getMethods(), false, false, constructors));
273         }
274         return retVal;
275     }
276
277     public static Map<String, GeneralClassTemplate> tOsFromRbe(
278             RuntimeBeanEntry rbe) {
279         Map<String, GeneralClassTemplate> retVal = Maps.newHashMap();
280         TOAttributesProcessor processor = new TOAttributesProcessor();
281         Map<String, AttributeIfc> yangPropertiesToTypesMap = Maps.newHashMap(rbe.getYangPropertiesToTypesMap());
282
283         // Add TOs from output parameters
284         for (Rpc rpc : rbe.getRpcs()) {
285             AttributeIfc returnType = rpc.getReturnType();
286
287             if (returnType == VoidAttribute.getInstance()) {
288                 continue;
289             }
290             if (returnType instanceof JavaAttribute) {
291                 continue;
292             }
293             if (returnType instanceof ListAttribute && returnType.getOpenType() instanceof SimpleType) {
294                 continue;
295             }
296
297             Preconditions.checkState(yangPropertiesToTypesMap.containsKey(returnType.getAttributeYangName()) == false,
298                     "Duplicate TO %s for %s", returnType.getAttributeYangName(), rbe);
299             yangPropertiesToTypesMap.put(returnType.getAttributeYangName(), returnType);
300         }
301
302         processor.processAttributes(yangPropertiesToTypesMap);
303         for (org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.TemplateFactory.TOAttributesProcessor.TOInternal to : processor
304                 .getTOs()) {
305             List<Constructor> constructors = Lists.newArrayList();
306             constructors.add(new Constructor(to.getName(), "super();"));
307
308             // TODO header
309             retVal.put(
310                     to.getType(),
311                     new GeneralClassTemplate(null, rbe.getPackageName(), to
312                             .getName(), Collections.<String> emptyList(),
313                             Collections.<String> emptyList(), to.getFields(),
314                             to.getMethods(), false, false, constructors));
315         }
316         return retVal;
317     }
318
319     private static Header getHeaderFromEntry(AbstractEntry mbe) {
320         return new Header(mbe.getYangModuleName(), mbe.getYangModuleLocalname());
321     }
322
323     // TODO refactor attribute processors
324
325     private static class TOAttributesProcessor {
326
327         private final List<TOInternal> tos = Lists.newArrayList();
328
329         void processAttributes(Map<String, AttributeIfc> attributes) {
330             for (Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
331                 AttributeIfc attributeIfc = attrEntry.getValue();
332                 if (attributeIfc instanceof TOAttribute) {
333                     createTOInternal((TOAttribute) attributeIfc);
334                 }
335                 if (attributeIfc instanceof ListAttribute) {
336                     AttributeIfc innerAttr = ((ListAttribute) attributeIfc)
337                             .getInnerAttribute();
338                     if (innerAttr instanceof TOAttribute) {
339                         createTOInternal((TOAttribute) innerAttr);
340                     }
341                 }
342             }
343         }
344
345         private void createTOInternal(TOAttribute toAttribute) {
346
347             Map<String, AttributeIfc> attrs = toAttribute.getCapitalizedPropertiesToTypesMap();
348             // recursive processing of TO's attributes
349             processAttributes(attrs);
350
351             tos.add(new TOInternal(toAttribute.getType(), attrs));
352         }
353
354         List<TOInternal> getTOs() {
355             return tos;
356         }
357
358         private static class TOInternal {
359             private final String fullyQualifiedName, name;
360             private List<Field> fields;
361             private List<MethodDefinition> methods;
362
363             public TOInternal(Type type, Map<String, AttributeIfc> attrs) {
364                 this(type.getFullyQualifiedName(), type.getName(), attrs, type.getPackageName());
365             }
366
367             public TOInternal(String fullyQualifiedName, String name,
368                     Map<String, AttributeIfc> attrs, String packageName) {
369                 this.fullyQualifiedName = fullyQualifiedName;
370                 this.name = name;
371                 processAttrs(attrs, packageName);
372             }
373
374             private final static String dependencyResolverVarName = "dependencyResolver";
375             private final static String dependencyResolverInjectMethodName = "injectDependencyResolver";
376
377             private void processAttrs(Map<String, AttributeIfc> attrs, String packageName) {
378                 fields = Lists.newArrayList();
379                 methods = Lists.newArrayList();
380
381                 // FIXME conflict if "dependencyResolver" field from yang
382                 Field depRes = new Field(DependencyResolver.class.getName(), dependencyResolverVarName);
383                 fields.add(depRes);
384                 methods.add(new MethodDefinition("void", dependencyResolverInjectMethodName, Lists.newArrayList(depRes),
385                         "this." + dependencyResolverVarName + " = " + dependencyResolverVarName + ";"));
386
387                 for (Entry<String, AttributeIfc> attrEntry : attrs.entrySet()) {
388                     String innerName = attrEntry.getKey();
389                     String varName = BindingGeneratorUtil
390                             .parseToValidParamName(attrEntry.getKey());
391
392                     String fullyQualifiedName, nullableDefault = null;
393                     if (attrEntry.getValue() instanceof TypedAttribute) {
394                         Type type = ((TypedAttribute) attrEntry.getValue()).getType();
395                         if(attrEntry.getValue() instanceof JavaAttribute) {
396                             nullableDefault = ((JavaAttribute)attrEntry.getValue()).getNullableDefaultWrappedForCode();
397                             if(((JavaAttribute)attrEntry.getValue()).isIdentityRef()) {
398
399                                 String fieldType = serializeType(type, true);
400                                 String innerType = getInnerTypeFromIdentity(type);
401                                 methods.add(new MethodDefinition(fieldType, "resolve" + attrEntry.getKey(), Collections.<Field>emptyList(),
402                                         "return " + varName + ".resolveIdentity(" + dependencyResolverVarName + "," +  innerType + ".class);"));
403                                 type = identityRefType;
404                             }
405                         }
406                         fullyQualifiedName = serializeType(type);
407                     } else {
408                         fullyQualifiedName = FullyQualifiedNameHelper
409                                 .getFullyQualifiedName(packageName, attrEntry.getValue().getUpperCaseCammelCase());
410                     }
411                     fields.add(new Field(fullyQualifiedName, varName, nullableDefault, needsDepResolver(attrEntry.getValue())));
412
413                     String getterName = "get" + innerName;
414                     MethodDefinition getter = new MethodDefinition(
415                             fullyQualifiedName, getterName,
416                             Collections.<Field> emptyList(), "return "
417                                     + varName + ";");
418
419                     String setterName = "set" + innerName;
420                     MethodDefinition setter = new MethodDefinition("void",
421                             setterName, Lists.newArrayList(new Field(
422                                     fullyQualifiedName, varName)), "this."
423                                     + varName + " = " + varName + ";");
424                     methods.add(getter);
425                     methods.add(setter);
426                 }
427
428             }
429
430             String getType() {
431                 return fullyQualifiedName;
432             }
433
434             String getName() {
435                 return name;
436             }
437
438             List<Field> getFields() {
439                 return fields;
440             }
441
442             List<MethodDefinition> getMethods() {
443                 return methods;
444             }
445         }
446     }
447
448
449     private static class MXBeanInterfaceAttributesProcessor {
450         private final List<MethodDeclaration> methods = Lists.newArrayList();
451
452         void processAttributes(Map<String, AttributeIfc> attributes) {
453             for (Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
454                 String returnType;
455                 AttributeIfc attributeIfc = attrEntry.getValue();
456
457                 if (attributeIfc instanceof TypedAttribute) {
458                     TypedAttribute typedAttribute = (TypedAttribute) attributeIfc;
459                     returnType = serializeType(typedAttribute.getType());
460
461                     if (attributeIfc instanceof JavaAttribute && ((JavaAttribute)attrEntry.getValue()).isIdentityRef()) {
462                         returnType = serializeType(identityRefType);
463                     }
464
465                 } else {
466                     throw new UnsupportedOperationException(
467                             "Attribute not supported: "
468                                     + attributeIfc.getClass());
469                 }
470
471                 String getterName = "get"
472                         + attributeIfc.getUpperCaseCammelCase();
473                 MethodDeclaration getter = new MethodDeclaration(returnType,
474                         getterName, Collections.<Field> emptyList());
475
476                 String varName = BindingGeneratorUtil
477                         .parseToValidParamName(attrEntry.getKey());
478                 String setterName = "set"
479                         + attributeIfc.getUpperCaseCammelCase();
480                 MethodDeclaration setter = new MethodDeclaration("void",
481                         setterName, Lists.newArrayList(new Field(returnType,
482                                 varName)));
483
484                 methods.add(getter);
485                 methods.add(setter);
486
487                 if (attributeIfc.getNullableDescription() != null) {
488                     setter.setJavadoc(attrEntry.getValue()
489                             .getNullableDescription());
490                 }
491             }
492         }
493
494         List<MethodDeclaration> getMethods() {
495             return methods;
496         }
497     }
498
499     private static final Type identityRefType = new Type() {
500         public final Class<IdentityAttributeRef> IDENTITY_ATTRIBUTE_REF_CLASS = IdentityAttributeRef.class;
501
502         @Override
503         public String getPackageName() {
504             return IDENTITY_ATTRIBUTE_REF_CLASS.getPackage().getName();
505         }
506
507         @Override
508         public String getName() {
509             return IDENTITY_ATTRIBUTE_REF_CLASS.getSimpleName();
510         }
511
512         @Override
513         public String getFullyQualifiedName() {
514             return IDENTITY_ATTRIBUTE_REF_CLASS.getName();
515         }
516     };
517
518     private static class AbstractFactoryAttributesProcessor {
519
520         private final List<Field> fields = Lists.newArrayList();
521
522         void processAttributes(Map<String, AttributeIfc> attributes,
523                 String packageName) {
524             for (Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
525                 String type;
526                 String nullableDefaultWrapped = null;
527                 AttributeIfc attributeIfc = attrEntry.getValue();
528
529                 if (attributeIfc instanceof TypedAttribute) {
530                     TypedAttribute typedAttribute = (TypedAttribute) attributeIfc;
531                     type = serializeType(typedAttribute.getType());
532                 } else {
533                     throw new UnsupportedOperationException(
534                             "Attribute not supported: "
535                                     + attributeIfc.getClass());
536                 }
537
538                 fields.add(new Field(type, attributeIfc
539                         .getUpperCaseCammelCase(), nullableDefaultWrapped));
540             }
541         }
542
543         List<Field> getFields() {
544             return fields;
545         }
546     }
547
548     private static class AbstractModuleAttributesProcessor {
549         private static class Holder {
550             private final List<ModuleField> moduleFields;
551             private final List<MethodDefinition> methods;
552
553             private Holder(List<ModuleField> moduleFields, List<MethodDefinition> methods) {
554                 this.moduleFields = Collections.unmodifiableList(moduleFields);
555                 this.methods = Collections.unmodifiableList(methods);
556             }
557         }
558
559         private final Holder holder;
560
561
562         private AbstractModuleAttributesProcessor(Map<String, AttributeIfc> attributes) {
563             this.holder = processAttributes(attributes);
564         }
565
566         private static Holder processAttributes(Map<String, AttributeIfc> attributes) {
567             List<ModuleField> moduleFields = new ArrayList<>();
568             List<MethodDefinition> methods = new ArrayList<>();
569             for (Entry<String, AttributeIfc> attrEntry : attributes.entrySet()) {
570                 String type, nullableDefaultWrapped = null;
571                 AttributeIfc attributeIfc = attrEntry.getValue();
572                 boolean isIdentity = false;
573                 boolean needsDepResolver = needsDepResolver(attrEntry.getValue());
574
575                 if (attributeIfc instanceof TypedAttribute) {
576                     TypedAttribute typedAttribute = (TypedAttribute) attributeIfc;
577                     type = serializeType(typedAttribute.getType());
578                     if (attributeIfc instanceof JavaAttribute) {
579                         nullableDefaultWrapped = ((JavaAttribute) attributeIfc).getNullableDefaultWrappedForCode();
580                         if(((JavaAttribute)attrEntry.getValue()).isIdentityRef()) {
581                             isIdentity = true;
582                             type = serializeType(typedAttribute.getType(), true);
583                         }
584                     }
585                 } else {
586                     throw new UnsupportedOperationException(
587                             "Attribute not supported: "
588                                     + attributeIfc.getClass());
589                 }
590
591                 boolean isDependency = false;
592                 boolean isListOfDependencies = false;
593                 Dependency dependency = null;
594                 Annotation overrideAnnotation = new Annotation("Override",
595                         Collections.<Parameter> emptyList());
596                 List<Annotation> annotations = Lists
597                         .newArrayList(overrideAnnotation);
598
599                 if (attributeIfc instanceof AbstractDependencyAttribute) {
600                     isDependency = true;
601                     dependency = ((AbstractDependencyAttribute) attributeIfc)
602                             .getDependency();
603                     annotations.add(Annotation
604                             .createRequireIfcAnnotation(dependency.getSie()));
605                     if (attributeIfc instanceof ListDependenciesAttribute) {
606                         isListOfDependencies = true;
607                     }
608                 }
609
610                 String varName = BindingGeneratorUtil
611                         .parseToValidParamName(attrEntry.getKey());
612
613                 ModuleField field;
614                 if (isIdentity) {
615                     String identityBaseClass = getInnerTypeFromIdentity(((TypedAttribute) attributeIfc).getType());
616                     IdentityRefModuleField identityField = new IdentityRefModuleField(type, varName,
617                             attributeIfc.getUpperCaseCammelCase(), identityBaseClass);
618
619                     String getterName = "get"
620                             + attributeIfc.getUpperCaseCammelCase() + "Identity";
621                     MethodDefinition additionalGetter = new MethodDefinition(type, getterName, Collections.<Field> emptyList(),
622                             Collections.<Annotation> emptyList(), "return " + identityField.getIdentityClassName()
623                                     + ";");
624                     methods.add(additionalGetter);
625
626                     String setterName = "set"
627                             + attributeIfc.getUpperCaseCammelCase();
628
629                     String setterBody = "this." + identityField.getIdentityClassName() + " = " + identityField.getIdentityClassName() + ";";
630                     MethodDefinition additionalSetter = new MethodDefinition("void",
631                             setterName,
632                             Lists.newArrayList(new Field(type, identityField.getIdentityClassName())),
633                             Collections.<Annotation> emptyList(), setterBody);
634                     additionalSetter.setJavadoc(attributeIfc.getNullableDescription());
635
636                     methods.add(additionalSetter);
637
638                     type = serializeType(identityRefType);
639                     field = identityField;
640                 } else {
641                     field = new ModuleField(type, varName, attributeIfc.getUpperCaseCammelCase(),
642                             nullableDefaultWrapped, isDependency, dependency, isListOfDependencies, needsDepResolver);
643                 }
644                 moduleFields.add(field);
645
646
647                 String getterName = "get"
648                         + attributeIfc.getUpperCaseCammelCase();
649                 MethodDefinition getter = new MethodDefinition(type,
650                         getterName, Collections.<Field> emptyList(),
651                         Lists.newArrayList(overrideAnnotation), "return "
652                         + varName + ";");
653
654                 methods.add(getter);
655
656                 String setterName = "set"
657                         + attributeIfc.getUpperCaseCammelCase();
658
659                 if (attributeIfc.getNullableDescription() != null) {
660                     annotations.add(Annotation
661                             .createDescriptionAnnotation(attributeIfc.getNullableDescription()));
662                 }
663
664                 String setterBody = "this." + varName + " = " + varName + ";";
665                 if (isListOfDependencies) {
666                     String nullCheck = String.format("if (%s == null) throw new IllegalArgumentException(\"Null not supported\");%n",
667                             varName);
668                     setterBody = nullCheck + setterBody;
669                 }
670                 MethodDefinition setter = new MethodDefinition("void",
671                         setterName,
672                         Lists.newArrayList(new Field(type, varName)),
673                         annotations, setterBody);
674                 setter.setJavadoc(attributeIfc.getNullableDescription());
675
676                 methods.add(setter);
677             }
678             return new Holder(moduleFields, methods);
679         }
680
681         List<ModuleField> getModuleFields() {
682             return holder.moduleFields;
683         }
684
685         List<MethodDefinition> getMethods() {
686             return holder.methods;
687         }
688
689     }
690
691
692     private static boolean needsDepResolver(AttributeIfc value) {
693         if(value instanceof TOAttribute) {
694             return true;
695         }
696         if(value instanceof ListAttribute) {
697             AttributeIfc innerAttribute = ((ListAttribute) value).getInnerAttribute();
698             return needsDepResolver(innerAttribute);
699         }
700
701         return false;
702     }
703
704     private static String getInnerTypeFromIdentity(Type type) {
705         Preconditions.checkArgument(type instanceof ParameterizedType);
706         Type[] args = ((ParameterizedType) type).getActualTypeArguments();
707         Preconditions.checkArgument(args.length ==1);
708         return serializeType(args[0]);
709     }
710 }