2 * Copyright (c) 2013 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
8 package org.opendaylight.controller.config.yangjmxgenerator.plugin.ftl;
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;
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;
26 import java.util.Map.Entry;
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;
38 public class RuntimeRegistratorFtlTemplate extends GeneralClassTemplate {
40 private RuntimeRegistratorFtlTemplate(RuntimeBeanEntry runtimeBeanEntry,
41 String name, List<Field> fields, List<MethodDefinition> methods) {
43 super(null, runtimeBeanEntry.getPackageName(), name, Collections
44 .emptyList(), Collections.singletonList(Closeable.class
45 .getCanonicalName()), fields, methods);
48 public static RuntimeBeanEntry findRoot(
49 Collection<RuntimeBeanEntry> runtimeBeanEntries) {
50 RuntimeBeanEntry result = null;
51 for (RuntimeBeanEntry rb : runtimeBeanEntries) {
54 throw new IllegalArgumentException(
55 "More than one root runtime bean found");
63 throw new IllegalArgumentException("No root runtime bean found");
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");
76 return constructorBody.toString();
79 // TODO Move to factory
81 * Get registrator and n registration ftls where n is equal to total number
82 * of runtime beans in hierarchy.
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);
99 LinkedHashMap<String, RuntimeRegistratorFtlTemplate> RuntimeRegistratorFtlTemplates =
100 createRegistrationHierarchy(rootRB, Collections.emptySet());
101 RuntimeRegistratorFtlTemplate rootFtlFile = RuntimeRegistratorFtlTemplates
102 .values().iterator().next();
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());
117 MethodDefinition registerMethod = new MethodDefinition(
118 childRegistratorFQN, "register",
119 Collections.singletonList(rbParameter), registerBody);
120 methods.add(registerMethod);
123 MethodDefinition closeRegistrator = createCloseMethodToCloseField(rootRuntimeBeanRegistratorField);
124 methods.add(closeRegistrator);
127 GeneralClassTemplate registrator = new GeneralClassTemplate(null,
128 rootRB.getPackageName(), registratorName,
129 Collections.emptyList(), Collections.singletonList(Closeable.class
130 .getCanonicalName()), constructorParameters, methods);
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);
141 private static Field hierachicalRegistration = new Field(
142 Collections.singletonList(Modifier.FINAL),
143 HierarchicalRuntimeBeanRegistration.class.getCanonicalName(),
146 // TODO move to factory + RuntimeBeanEntry
148 * Create ftls representing registrations. First registration is represents
151 * @return map containing java class name as key, instance representing the
152 * java file as value.
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<>();
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());
171 Set<String> currentOccupiedKeys = new HashSet<>(occupiedKeys);
172 currentOccupiedKeys.add(parent.getJavaNamePrefix());
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) + "()");
180 // create register methods for children
181 for (RuntimeBeanEntry child : parent.getChildren()) {
182 checkArgument(parent.getPackageName()
183 .equals(child.getPackageName()), "Invalid package name");
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
191 if (unorderedResult.containsKey(entry.getKey())) {
192 throw new IllegalStateException(
193 "Conflicting name found while generating runtime registration:"
196 unorderedResult.put(entry.getKey(), entry.getValue());
199 if (!childRegistratorMap.isEmpty()) {
200 // first entry is the direct descendant according to the create
202 RuntimeRegistratorFtlTemplate childRegistrator = childRegistratorMap
203 .values().iterator().next();
204 StringBuilder body = new StringBuilder();
206 key = child.getJavaNamePrefix();
208 "String key = \"%s\"; //TODO: check for conflicts\n",
211 Optional<String> childKeyJavaName = child.getKeyJavaName();
212 if (childKeyJavaName.isPresent()) {
213 value = "bean.get" + childKeyJavaName.get() + "()";
214 value = "String.valueOf(" + value + ")";
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())";
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
227 body.append(format("return new %s(r);",
228 childRegistrator.getFullyQualifiedName()));
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);
242 // create parent registration
243 String createdName = getJavaNameOfRuntimeRegistration(parent.getJavaNamePrefix());
245 List<Field> constructorParameters = Collections.singletonList(hierachicalRegistration);
246 String constructorBody = constructConstructorBody(constructorParameters);
248 MethodDefinition constructor = MethodDefinition.createConstructor(
249 createdName, constructorParameters, constructorBody);
251 MethodDefinition closeRegistrator = createCloseMethodToCloseField(hierachicalRegistration);
252 methods.add(closeRegistrator);
253 methods.add(constructor);
254 List<Field> privateFields = Lists.newArrayList(registratorsMapField);
255 privateFields.addAll(constructorParameters);
257 RuntimeRegistratorFtlTemplate created = new RuntimeRegistratorFtlTemplate(
258 parent, createdName, privateFields, methods);
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);
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);
284 public static String getJavaNameOfRuntimeRegistration(String javaNamePrefix) {
285 return javaNamePrefix + "RuntimeRegistration";
288 public static String getJavaNameOfRuntimeRegistrator(RuntimeBeanEntry rootRB) {
289 checkArgument(rootRB.isRoot(), "RuntimeBeanEntry must be root");
290 return rootRB.getJavaNamePrefix() + "RuntimeRegistrator";