Remove yang-test
[controller.git] / opendaylight / config / yang-jmx-generator-plugin / src / main / java / org / opendaylight / controller / config / yangjmxgenerator / plugin / ftl / RuntimeRegistratorFtlTemplate.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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.lang.String.format;
13
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.base.Optional;
16 import com.google.common.collect.Lists;
17 import java.io.Closeable;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.LinkedHashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Set;
28 import java.util.concurrent.atomic.AtomicInteger;
29 import javax.lang.model.element.Modifier;
30 import org.opendaylight.controller.config.api.runtime.HierarchicalRuntimeBeanRegistration;
31 import org.opendaylight.controller.config.api.runtime.RootRuntimeBeanRegistrator;
32 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
33 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Annotation;
34 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.Field;
35 import org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl.model.MethodDefinition;
36 import org.opendaylight.controller.config.yangjmxgenerator.plugin.util.FullyQualifiedNameHelper;
37
38 public class RuntimeRegistratorFtlTemplate extends GeneralClassTemplate {
39
40     private RuntimeRegistratorFtlTemplate(RuntimeBeanEntry runtimeBeanEntry,
41             String name, List<Field> fields, List<MethodDefinition> methods) {
42         // TODO header
43         super(null, runtimeBeanEntry.getPackageName(), name, Collections
44                 .emptyList(), Collections.singletonList(Closeable.class
45                 .getCanonicalName()), fields, methods);
46     }
47
48     public static RuntimeBeanEntry findRoot(
49             Collection<RuntimeBeanEntry> runtimeBeanEntries) {
50         RuntimeBeanEntry result = null;
51         for (RuntimeBeanEntry rb : runtimeBeanEntries) {
52             if (rb.isRoot()) {
53                 if (result != null) {
54                     throw new IllegalArgumentException(
55                             "More than one root runtime bean found");
56                 }
57                 result = rb;
58             }
59         }
60         if (result != null) {
61             return result;
62         }
63         throw new IllegalArgumentException("No root runtime bean found");
64     }
65
66     private static String constructConstructorBody(
67             List<Field> constructorParameters) {
68         StringBuilder constructorBody = new StringBuilder();
69         for (Field field : constructorParameters) {
70             constructorBody.append("this.");
71             constructorBody.append(field.getName());
72             constructorBody.append("=");
73             constructorBody.append(field.getName());
74             constructorBody.append(";\n");
75         }
76         return constructorBody.toString();
77     }
78
79     // TODO Move to factory
80     /**
81      * Get registrator and n registration ftls where n is equal to total number
82      * of runtime beans in hierarchy.
83      */
84     public static Map<String, FtlTemplate> create(RuntimeBeanEntry rootRB) {
85         checkArgument(rootRB.isRoot(), "RuntimeBeanEntry must be root");
86         String registratorName = getJavaNameOfRuntimeRegistrator(rootRB);
87         List<MethodDefinition> methods = new ArrayList<>();
88         Field rootRuntimeBeanRegistratorField = new Field(
89                 Collections.singletonList(Modifier.FINAL),
90                 RootRuntimeBeanRegistrator.class.getName(),
91                 "rootRuntimeBeanRegistrator");
92         List<Field> constructorParameters = Lists
93                 .newArrayList(rootRuntimeBeanRegistratorField);
94         String constructorBody = constructConstructorBody(constructorParameters);
95         MethodDefinition constructor = MethodDefinition.createConstructor(
96                 registratorName, constructorParameters, constructorBody);
97         methods.add(constructor);
98
99         LinkedHashMap<String, RuntimeRegistratorFtlTemplate> RuntimeRegistratorFtlTemplates =
100                 createRegistrationHierarchy(rootRB, Collections.emptySet());
101         RuntimeRegistratorFtlTemplate rootFtlFile = RuntimeRegistratorFtlTemplates
102                 .values().iterator().next();
103
104         {// add register(rootruntimemxbean)
105             String fullyQualifiedNameOfMXBean = FullyQualifiedNameHelper
106                     .getFullyQualifiedName(rootRB.getPackageName(), rootRB.getJavaNameOfRuntimeMXBean());
107             String childRegistratorFQN = rootFtlFile.getFullyQualifiedName();
108             Field rbParameter = new Field(fullyQualifiedNameOfMXBean, "rb");
109             String registerBody = format("%s %s = this.%s.registerRoot(%s);\n"
110                             + "return new %s(%2$s);\n",
111                     HierarchicalRuntimeBeanRegistration.class.getCanonicalName(),
112                     hierachicalRegistration.getName(),
113                     rootRuntimeBeanRegistratorField.getName(),
114                     rbParameter.getName(),
115                     rootFtlFile.getFullyQualifiedName());
116
117             MethodDefinition registerMethod = new MethodDefinition(
118                     childRegistratorFQN, "register",
119                     Collections.singletonList(rbParameter), registerBody);
120             methods.add(registerMethod);
121         }
122
123         MethodDefinition closeRegistrator = createCloseMethodToCloseField(rootRuntimeBeanRegistratorField);
124         methods.add(closeRegistrator);
125
126         // TODO add header
127         GeneralClassTemplate registrator = new GeneralClassTemplate(null,
128                 rootRB.getPackageName(), registratorName,
129                 Collections.emptyList(), Collections.singletonList(Closeable.class
130                 .getCanonicalName()), constructorParameters, methods);
131
132         checkState(!RuntimeRegistratorFtlTemplates.containsKey(registrator
133                 .getTypeDeclaration().getName()), "Name conflict: "
134                 + registrator.getTypeDeclaration().getName());
135         Map<String, FtlTemplate> result = new HashMap<>();
136         result.putAll(RuntimeRegistratorFtlTemplates);
137         result.put(registrator.getTypeDeclaration().getName(), registrator);
138         return result;
139     }
140
141     private static Field hierachicalRegistration = new Field(
142             Collections.singletonList(Modifier.FINAL),
143             HierarchicalRuntimeBeanRegistration.class.getCanonicalName(),
144             "registration");
145
146     // TODO move to factory + RuntimeBeanEntry
147     /**
148      * Create ftls representing registrations. First registration is represents
149      * parent.
150      *
151      * @return map containing java class name as key, instance representing the
152      *         java file as value.
153      */
154     private static LinkedHashMap<String, RuntimeRegistratorFtlTemplate> createRegistrationHierarchy(
155             RuntimeBeanEntry parent, Set<String> occupiedKeys) {
156         LinkedHashMap<String, RuntimeRegistratorFtlTemplate> unorderedResult = new LinkedHashMap<>();
157         List<MethodDefinition> methods = new ArrayList<>();
158
159         // hierarchy of ON is created as follows:
160         // root RB: <domain>, type=RuntimeBean
161         // 1st RB in hierarchy: <domain>, type=RuntimeBean, <java name of leaf
162         // list>: key or counter
163         // n-th RB in hierarchy has same ON as n-1, with added <java name of
164         // leaf list>: key or counter
165         if (occupiedKeys.contains(parent.getJavaNamePrefix())) {
166             throw new IllegalArgumentException(
167                     "Name conflict in runtime bean hierarchy - java name found more than "
168                             + "once. Consider using java-name extension. Conflicting name: "
169                             + parent.getJavaNamePrefix());
170         }
171         Set<String> currentOccupiedKeys = new HashSet<>(occupiedKeys);
172         currentOccupiedKeys.add(parent.getJavaNamePrefix());
173
174         Field registratorsMapField = new Field(Collections.singletonList(Modifier.FINAL),
175                 TypeHelper.getGenericType(Map.class, String.class,
176                         AtomicInteger.class), "unkeyedMap", "new "
177                         + TypeHelper.getGenericType(HashMap.class,
178                                 String.class, AtomicInteger.class) + "()");
179
180         // create register methods for children
181         for (RuntimeBeanEntry child : parent.getChildren()) {
182             checkArgument(parent.getPackageName()
183                     .equals(child.getPackageName()), "Invalid package name");
184
185             // call itself recursively to generate child
186             // registrators/registrations
187             LinkedHashMap<String, RuntimeRegistratorFtlTemplate> childRegistratorMap = createRegistrationHierarchy(
188                     child, currentOccupiedKeys);
189             for (Entry<String, RuntimeRegistratorFtlTemplate> entry : childRegistratorMap
190                     .entrySet()) {
191                 if (unorderedResult.containsKey(entry.getKey())) {
192                     throw new IllegalStateException(
193                             "Conflicting name found while generating runtime registration:"
194                                     + entry.getKey());
195                 }
196                 unorderedResult.put(entry.getKey(), entry.getValue());
197             }
198
199             if (!childRegistratorMap.isEmpty()) {
200                 // first entry is the direct descendant according to the create
201                 // contract
202                 RuntimeRegistratorFtlTemplate childRegistrator = childRegistratorMap
203                         .values().iterator().next();
204                 StringBuilder body = new StringBuilder();
205                 String key, value;
206                 key = child.getJavaNamePrefix();
207                 body.append(format(
208                         "String key = \"%s\"; //TODO: check for conflicts\n",
209                         key));
210
211                 Optional<String> childKeyJavaName = child.getKeyJavaName();
212                 if (childKeyJavaName.isPresent()) {
213                     value = "bean.get" + childKeyJavaName.get() + "()";
214                     value = "String.valueOf(" + value + ")";
215                 } else {
216                     body.append("java.util.concurrent.atomic.AtomicInteger counter = unkeyedMap.get(key);\n"
217                             + "if (counter==null){\n"
218                             + "counter = new java.util.concurrent.atomic.AtomicInteger();\n"
219                             + "unkeyedMap.put(key, counter);\n" + "}\n");
220                     value = "String.valueOf(counter.incrementAndGet())";
221                 }
222                 body.append(format("String value = %s;\n", value));
223                 body.append(format("%s r = %s.register(key, value, bean);\n",
224                         HierarchicalRuntimeBeanRegistration.class
225                                 .getCanonicalName(), hierachicalRegistration
226                                 .getName()));
227                 body.append(format("return new %s(r);",
228                         childRegistrator.getFullyQualifiedName()));
229
230                 Field param = new Field(Collections.singletonList(Modifier.FINAL),
231                         child.getJavaNameOfRuntimeMXBean(), "bean");
232                 MethodDefinition register = new MethodDefinition(
233                         Collections.singletonList(Modifier.SYNCHRONIZED),
234                         childRegistrator.getFullyQualifiedName(), "register",
235                         Collections.singletonList(param), Collections.emptyList(),
236                         Collections.emptyList(), body.toString());
237                 methods.add(register);
238
239             }
240         }
241
242         // create parent registration
243         String createdName = getJavaNameOfRuntimeRegistration(parent.getJavaNamePrefix());
244
245         List<Field> constructorParameters = Collections.singletonList(hierachicalRegistration);
246         String constructorBody = constructConstructorBody(constructorParameters);
247
248         MethodDefinition constructor = MethodDefinition.createConstructor(
249                 createdName, constructorParameters, constructorBody);
250
251         MethodDefinition closeRegistrator = createCloseMethodToCloseField(hierachicalRegistration);
252         methods.add(closeRegistrator);
253         methods.add(constructor);
254         List<Field> privateFields = Lists.newArrayList(registratorsMapField);
255         privateFields.addAll(constructorParameters);
256
257         RuntimeRegistratorFtlTemplate created = new RuntimeRegistratorFtlTemplate(
258                 parent, createdName, privateFields, methods);
259
260         LinkedHashMap<String, RuntimeRegistratorFtlTemplate> result = new LinkedHashMap<>();
261         result.put(created.getTypeDeclaration().getName(), created);
262         checkState(!unorderedResult.containsKey(created.getTypeDeclaration()
263                 .getName()), "Naming conflict: "
264                 + created.getTypeDeclaration().getName());
265         result.putAll(unorderedResult);
266         return result;
267     }
268
269     private static MethodDefinition createCloseMethodToCloseField(Field field) {
270         String body = field.getName() + ".close();";
271         // TODO Thrown exception breaks build
272         // return new MethodDefinition(Collections.<String> emptyList(), "void",
273         // "close", Collections.<Field> emptyList(),
274         // Arrays.asList(IOException.class.getCanonicalName()),
275         // Collections.<Annotation> emptyList(), body);
276         List<Annotation> annotations = Lists.newArrayList(new Annotation(
277                 "Override", Collections.emptyList()));
278         return new MethodDefinition(Collections.emptyList(), "void",
279                 "close", Collections.emptyList(),
280                 Collections.emptyList(), annotations, body);
281     }
282
283     @VisibleForTesting
284     public static String getJavaNameOfRuntimeRegistration(String javaNamePrefix) {
285         return javaNamePrefix + "RuntimeRegistration";
286     }
287
288     public static String getJavaNameOfRuntimeRegistrator(RuntimeBeanEntry rootRB) {
289         checkArgument(rootRB.isRoot(), "RuntimeBeanEntry must be root");
290         return rootRB.getJavaNamePrefix() + "RuntimeRegistrator";
291     }
292 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.