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;
11 import java.io.IOException;
12 import java.util.Collection;
13 import java.util.HashMap;
14 import java.util.List;
16 import java.util.Map.Entry;
18 import java.util.regex.Matcher;
19 import java.util.regex.Pattern;
21 import org.apache.commons.io.FileUtils;
22 import org.apache.maven.plugin.logging.Log;
23 import org.apache.maven.project.MavenProject;
24 import org.opendaylight.controller.config.spi.ModuleFactory;
25 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
26 import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator;
27 import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
28 import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
29 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.model.api.Module;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
33 import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.slf4j.impl.StaticLoggerBinder;
38 import com.google.common.annotations.VisibleForTesting;
39 import com.google.common.base.Preconditions;
40 import com.google.common.collect.Lists;
41 import com.google.common.collect.Maps;
42 import com.google.common.collect.Sets;
45 * This class interfaces with yang-maven-plugin. Gets parsed yang modules in
46 * {@link SchemaContext}, and parameters form the plugin configuration, and
47 * writes service interfaces and/or modules.
49 public class JMXGenerator implements CodeGenerator {
51 static final String NAMESPACE_TO_PACKAGE_DIVIDER = "==";
52 static final String NAMESPACE_TO_PACKAGE_PREFIX = "namespaceToPackage";
53 static final String MODULE_FACTORY_FILE_BOOLEAN = "moduleFactoryFile";
55 private PackageTranslator packageTranslator;
56 private final CodeWriter codeWriter;
57 private static final Logger logger = LoggerFactory
58 .getLogger(JMXGenerator.class);
59 private Map<String, String> namespaceToPackageMapping;
60 private File resourceBaseDir;
61 private File projectBaseDir;
62 private boolean generateModuleFactoryFile = true;
64 public JMXGenerator() {
65 this.codeWriter = new FreeMarkerCodeWriterImpl();
68 public JMXGenerator(CodeWriter codeWriter) {
69 this.codeWriter = codeWriter;
73 public Collection<File> generateSources(SchemaContext context,
74 File outputBaseDir, Set<Module> yangModulesInCurrentMavenModule) {
76 Preconditions.checkArgument(context != null, "Null context received");
77 Preconditions.checkArgument(outputBaseDir != null,
78 "Null outputBaseDir received");
81 .checkArgument(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(),
82 "No namespace to package mapping provided in additionalConfiguration");
84 packageTranslator = new PackageTranslator(namespaceToPackageMapping);
86 if (!outputBaseDir.exists())
87 outputBaseDir.mkdirs();
89 GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker();
90 Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>();
92 // create SIE structure qNamesToSIEs
93 for (Module module : context.getModules()) {
94 String packageName = packageTranslator.getPackageName(module);
95 Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry
96 .create(module, packageName);
98 for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries
101 // merge value into qNamesToSIEs
102 if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) {
103 qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
105 throw new IllegalStateException(
106 "Cannot add two SIE with same qname "
107 + sieEntry.getValue());
110 if (yangModulesInCurrentMavenModule.contains(module)) {
111 // write this sie to disk
112 for (ServiceInterfaceEntry sie : namesToSIEntries.values()) {
114 generatedFiles.addFile(codeWriter.writeSie(sie,
116 } catch (Exception e) {
117 throw new RuntimeException(
118 "Error occurred during SIE source generate phase",
125 File mainBaseDir = concatFolders(projectBaseDir, "src", "main", "java");
126 Preconditions.checkNotNull(resourceBaseDir,
127 "resource base dir attribute was null");
129 StringBuffer fullyQualifiedNamesOfFactories = new StringBuffer();
131 for (Module module : yangModulesInCurrentMavenModule) {
132 String packageName = packageTranslator.getPackageName(module);
133 Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
134 .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)),
137 for (Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs
139 ModuleMXBeanEntry mbe = mbeEntry.getValue();
141 List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir,
142 mainBaseDir, resourceBaseDir);
143 generatedFiles.addFile(files1);
144 } catch (Exception e) {
145 throw new RuntimeException(
146 "Error occurred during MBE source generate phase",
149 fullyQualifiedNamesOfFactories.append(mbe
150 .getFullyQualifiedName(mbe.getStubFactoryName()));
151 fullyQualifiedNamesOfFactories.append("\n");
154 // create ModuleFactory file if needed
155 if (fullyQualifiedNamesOfFactories.length() > 0
156 && generateModuleFactoryFile) {
157 File serviceLoaderFile = JMXGenerator.concatFolders(
158 resourceBaseDir, "META-INF", "services",
159 ModuleFactory.class.getName());
160 // if this file does not exist, create empty file
161 serviceLoaderFile.getParentFile().mkdirs();
163 serviceLoaderFile.createNewFile();
164 FileUtils.write(serviceLoaderFile,
165 fullyQualifiedNamesOfFactories.toString());
166 } catch (IOException e) {
167 String message = "Cannot write to " + serviceLoaderFile;
168 logger.error(message);
169 throw new RuntimeException(message, e);
172 return generatedFiles.getFiles();
175 static File concatFolders(File projectBaseDir, String... folderNames) {
176 StringBuilder b = new StringBuilder();
177 for (String folder : folderNames) {
179 b.append(File.separator);
181 return new File(projectBaseDir, b.toString());
185 public void setAdditionalConfig(Map<String, String> additionalCfg) {
187 logger.debug(getClass().getCanonicalName(),
188 ": Additional configuration received: ",
189 additionalCfg.toString());
190 this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg);
191 this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg);
194 private boolean extractModuleFactoryBoolean(
195 Map<String, String> additionalCfg) {
196 String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
199 if (bool.equals("false"))
205 public void setLog(Log log) {
206 StaticLoggerBinder.getSingleton().setLog(log);
209 private static Map<String, String> extractNamespaceMapping(
210 Map<String, String> additionalCfg) {
211 Map<String, String> namespaceToPackage = Maps.newHashMap();
212 for (String key : additionalCfg.keySet()) {
213 if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) {
214 String mapping = additionalCfg.get(key);
215 NamespaceMapping mappingResolved = extractNamespaceMapping(mapping);
216 namespaceToPackage.put(mappingResolved.namespace,
217 mappingResolved.packageName);
220 return namespaceToPackage;
223 static Pattern namespaceMappingPattern = Pattern.compile("(.+)"
224 + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
226 private static NamespaceMapping extractNamespaceMapping(String mapping) {
227 Matcher matcher = namespaceMappingPattern.matcher(mapping);
229 .checkArgument(matcher.matches(), String.format("Namespace to package mapping:%s is in invalid " +
230 "format, requested format is: %s", mapping, namespaceMappingPattern));
231 return new NamespaceMapping(matcher.group(1), matcher.group(2));
234 private static class NamespaceMapping {
235 public NamespaceMapping(String namespace, String packagename) {
236 this.namespace = namespace;
237 this.packageName = packagename;
240 private final String namespace, packageName;
244 public void setResourceBaseDir(File resourceDir) {
245 this.resourceBaseDir = resourceDir;
249 public void setMavenProject(MavenProject project) {
250 this.projectBaseDir = project.getBasedir();
253 logger.debug(getClass().getCanonicalName(), " project base dir: ",
258 static class GeneratedFilesTracker {
259 private final Set<File> files = Sets.newHashSet();
261 void addFile(File file) {
262 if (files.contains(file)) {
263 List<File> undeletedFiles = Lists.newArrayList();
264 for (File presentFile : files) {
265 if (presentFile.delete() == false) {
266 undeletedFiles.add(presentFile);
269 if (undeletedFiles.isEmpty() == false) {
271 "Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
274 throw new IllegalStateException(
275 "Name conflict in generated files, file" + file
281 void addFile(Collection<File> files) {
282 for (File file : files) {
287 public Set<File> getFiles() {