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;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Lists;
13 import com.google.common.collect.Maps;
14 import com.google.common.collect.Sets;
15 import org.apache.commons.io.FileUtils;
16 import org.apache.maven.plugin.logging.Log;
17 import org.apache.maven.project.MavenProject;
18 import org.opendaylight.controller.config.spi.ModuleFactory;
19 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
20 import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator;
21 import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
22 import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
23 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.model.api.Module;
26 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
27 import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.slf4j.impl.StaticLoggerBinder;
33 import java.io.IOException;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.List;
38 import java.util.Map.Entry;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
44 * This class interfaces with yang-maven-plugin. Gets parsed yang modules in
45 * {@link SchemaContext}, and parameters form the plugin configuration, and
46 * writes service interfaces and/or modules.
48 public class JMXGenerator implements CodeGenerator {
50 static final String NAMESPACE_TO_PACKAGE_DIVIDER = "==";
51 static final String NAMESPACE_TO_PACKAGE_PREFIX = "namespaceToPackage";
52 static final String MODULE_FACTORY_FILE_BOOLEAN = "moduleFactoryFile";
54 private PackageTranslator packageTranslator;
55 private final CodeWriter codeWriter;
56 private static final Logger logger = LoggerFactory
57 .getLogger(JMXGenerator.class);
58 private Map<String, String> namespaceToPackageMapping;
59 private File resourceBaseDir;
60 private File projectBaseDir;
61 private boolean generateModuleFactoryFile = true;
63 public JMXGenerator() {
64 this.codeWriter = new FreeMarkerCodeWriterImpl();
67 public JMXGenerator(CodeWriter codeWriter) {
68 this.codeWriter = codeWriter;
72 public Collection<File> generateSources(SchemaContext context,
73 File outputBaseDir, Set<Module> yangModulesInCurrentMavenModule) {
75 Preconditions.checkArgument(context != null, "Null context received");
76 Preconditions.checkArgument(outputBaseDir != null,
77 "Null outputBaseDir received");
80 .checkArgument(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(),
81 "No namespace to package mapping provided in additionalConfiguration");
83 packageTranslator = new PackageTranslator(namespaceToPackageMapping);
85 if (!outputBaseDir.exists())
86 outputBaseDir.mkdirs();
88 GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker();
89 Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>();
91 // create SIE structure qNamesToSIEs
92 for (Module module : context.getModules()) {
93 String packageName = packageTranslator.getPackageName(module);
94 Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry
95 .create(module, packageName);
97 for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries
100 // merge value into qNamesToSIEs
101 if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) {
102 qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
104 throw new IllegalStateException(
105 "Cannot add two SIE with same qname "
106 + sieEntry.getValue());
109 if (yangModulesInCurrentMavenModule.contains(module)) {
110 // write this sie to disk
111 for (ServiceInterfaceEntry sie : namesToSIEntries.values()) {
113 generatedFiles.addFile(codeWriter.writeSie(sie,
115 } catch (Exception e) {
116 throw new RuntimeException(
117 "Error occurred during SIE source generate phase",
124 File mainBaseDir = concatFolders(projectBaseDir, "src", "main", "java");
125 Preconditions.checkNotNull(resourceBaseDir,
126 "resource base dir attribute was null");
128 StringBuffer fullyQualifiedNamesOfFactories = new StringBuffer();
130 for (Module module : yangModulesInCurrentMavenModule) {
131 String packageName = packageTranslator.getPackageName(module);
132 Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
133 .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)),
136 for (Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs
138 ModuleMXBeanEntry mbe = mbeEntry.getValue();
140 List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir,
141 mainBaseDir, resourceBaseDir);
142 generatedFiles.addFile(files1);
143 } catch (Exception e) {
144 throw new RuntimeException(
145 "Error occurred during MBE source generate phase",
148 fullyQualifiedNamesOfFactories.append(mbe
149 .getFullyQualifiedName(mbe.getStubFactoryName()));
150 fullyQualifiedNamesOfFactories.append("\n");
153 // create ModuleFactory file if needed
154 if (fullyQualifiedNamesOfFactories.length() > 0
155 && generateModuleFactoryFile) {
156 File serviceLoaderFile = JMXGenerator.concatFolders(
157 resourceBaseDir, "META-INF", "services",
158 ModuleFactory.class.getName());
159 // if this file does not exist, create empty file
160 serviceLoaderFile.getParentFile().mkdirs();
162 serviceLoaderFile.createNewFile();
163 FileUtils.write(serviceLoaderFile,
164 fullyQualifiedNamesOfFactories.toString());
165 } catch (IOException e) {
166 String message = "Cannot write to " + serviceLoaderFile;
167 logger.error(message);
168 throw new RuntimeException(message, e);
171 return generatedFiles.getFiles();
174 static File concatFolders(File projectBaseDir, String... folderNames) {
175 StringBuilder b = new StringBuilder();
176 for (String folder : folderNames) {
178 b.append(File.separator);
180 return new File(projectBaseDir, b.toString());
184 public void setAdditionalConfig(Map<String, String> additionalCfg) {
186 logger.debug(getClass().getCanonicalName(),
187 ": Additional configuration received: ",
188 additionalCfg.toString());
189 this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg);
190 this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg);
193 private boolean extractModuleFactoryBoolean(
194 Map<String, String> additionalCfg) {
195 String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
198 if (bool.equals("false"))
204 public void setLog(Log log) {
205 StaticLoggerBinder.getSingleton().setLog(log);
208 private static Map<String, String> extractNamespaceMapping(
209 Map<String, String> additionalCfg) {
210 Map<String, String> namespaceToPackage = Maps.newHashMap();
211 for (String key : additionalCfg.keySet()) {
212 if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) {
213 String mapping = additionalCfg.get(key);
214 NamespaceMapping mappingResolved = extractNamespaceMapping(mapping);
215 namespaceToPackage.put(mappingResolved.namespace,
216 mappingResolved.packageName);
219 return namespaceToPackage;
222 static Pattern namespaceMappingPattern = Pattern.compile("(.+)"
223 + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
225 private static NamespaceMapping extractNamespaceMapping(String mapping) {
226 Matcher matcher = namespaceMappingPattern.matcher(mapping);
228 .checkArgument(matcher.matches(), String.format("Namespace to package mapping:%s is in invalid " +
229 "format, requested format is: %s", mapping, namespaceMappingPattern));
230 return new NamespaceMapping(matcher.group(1), matcher.group(2));
233 private static class NamespaceMapping {
234 public NamespaceMapping(String namespace, String packagename) {
235 this.namespace = namespace;
236 this.packageName = packagename;
239 private final String namespace, packageName;
243 public void setResourceBaseDir(File resourceDir) {
244 this.resourceBaseDir = resourceDir;
248 public void setMavenProject(MavenProject project) {
249 this.projectBaseDir = project.getBasedir();
252 logger.debug(getClass().getCanonicalName(), " project base dir: ",
257 static class GeneratedFilesTracker {
258 private final Set<File> files = Sets.newHashSet();
260 void addFile(File file) {
261 if (files.contains(file)) {
262 List<File> undeletedFiles = Lists.newArrayList();
263 for (File presentFile : files) {
264 if (presentFile.delete() == false) {
265 undeletedFiles.add(presentFile);
268 if (undeletedFiles.isEmpty() == false) {
270 "Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
273 throw new IllegalStateException(
274 "Name conflict in generated files, file" + file
280 void addFile(Collection<File> files) {
281 for (File file : files) {
286 public Set<File> getFiles() {