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.IdentitySchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.Module;
27 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
28 import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.slf4j.impl.StaticLoggerBinder;
34 import java.io.IOException;
35 import java.util.Collection;
36 import java.util.HashMap;
37 import java.util.List;
39 import java.util.Map.Entry;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
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 CodeWriter();
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 // create SIE structure qNamesToSIEs
91 Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>();
94 Map<IdentitySchemaNode, ServiceInterfaceEntry> knownSEITracker = new HashMap<>();
95 for (Module module : context.getModules()) {
96 String packageName = packageTranslator.getPackageName(module);
97 Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry
98 .create(module, packageName, knownSEITracker);
100 for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries
102 // merge value into qNamesToSIEs
103 if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) {
104 qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
106 throw new IllegalStateException(
107 "Cannot add two SIE with same qname "
108 + sieEntry.getValue());
111 if (yangModulesInCurrentMavenModule.contains(module)) {
112 // write this sie to disk
113 for (ServiceInterfaceEntry sie : namesToSIEntries.values()) {
115 generatedFiles.addFile(codeWriter.writeSie(sie,
117 } catch (Exception e) {
118 throw new RuntimeException(
119 "Error occurred during SIE source generate phase",
126 File mainBaseDir = concatFolders(projectBaseDir, "src", "main", "java");
127 Preconditions.checkNotNull(resourceBaseDir,
128 "resource base dir attribute was null");
130 StringBuffer fullyQualifiedNamesOfFactories = new StringBuffer();
132 for (Module module : yangModulesInCurrentMavenModule) {
133 String packageName = packageTranslator.getPackageName(module);
134 Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
135 .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)),
138 for (Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs
140 ModuleMXBeanEntry mbe = mbeEntry.getValue();
142 List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir,
144 generatedFiles.addFile(files1);
145 } catch (Exception e) {
146 throw new RuntimeException(
147 "Error occurred during MBE source generate phase",
150 fullyQualifiedNamesOfFactories.append(mbe
151 .getFullyQualifiedName(mbe.getStubFactoryName()));
152 fullyQualifiedNamesOfFactories.append("\n");
155 // create ModuleFactory file if needed
156 if (fullyQualifiedNamesOfFactories.length() > 0
157 && generateModuleFactoryFile) {
158 File serviceLoaderFile = JMXGenerator.concatFolders(
159 resourceBaseDir, "META-INF", "services",
160 ModuleFactory.class.getName());
161 // if this file does not exist, create empty file
162 serviceLoaderFile.getParentFile().mkdirs();
164 serviceLoaderFile.createNewFile();
165 FileUtils.write(serviceLoaderFile,
166 fullyQualifiedNamesOfFactories.toString());
167 } catch (IOException e) {
168 String message = "Cannot write to " + serviceLoaderFile;
169 logger.error(message);
170 throw new RuntimeException(message, e);
173 return generatedFiles.getFiles();
176 static File concatFolders(File projectBaseDir, String... folderNames) {
177 StringBuilder b = new StringBuilder();
178 for (String folder : folderNames) {
180 b.append(File.separator);
182 return new File(projectBaseDir, b.toString());
186 public void setAdditionalConfig(Map<String, String> additionalCfg) {
188 logger.debug(getClass().getCanonicalName(),
189 ": Additional configuration received: ",
190 additionalCfg.toString());
191 this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg);
192 this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg);
195 private boolean extractModuleFactoryBoolean(
196 Map<String, String> additionalCfg) {
197 String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
200 if (bool.equals("false"))
206 public void setLog(Log log) {
207 StaticLoggerBinder.getSingleton().setMavenLog(log);
210 private static Map<String, String> extractNamespaceMapping(
211 Map<String, String> additionalCfg) {
212 Map<String, String> namespaceToPackage = Maps.newHashMap();
213 for (String key : additionalCfg.keySet()) {
214 if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) {
215 String mapping = additionalCfg.get(key);
216 NamespaceMapping mappingResolved = extractNamespaceMapping(mapping);
217 namespaceToPackage.put(mappingResolved.namespace,
218 mappingResolved.packageName);
221 return namespaceToPackage;
224 static Pattern namespaceMappingPattern = Pattern.compile("(.+)"
225 + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
227 private static NamespaceMapping extractNamespaceMapping(String mapping) {
228 Matcher matcher = namespaceMappingPattern.matcher(mapping);
230 .checkArgument(matcher.matches(), String.format("Namespace to package mapping:%s is in invalid " +
231 "format, requested format is: %s", mapping, namespaceMappingPattern));
232 return new NamespaceMapping(matcher.group(1), matcher.group(2));
235 private static class NamespaceMapping {
236 public NamespaceMapping(String namespace, String packagename) {
237 this.namespace = namespace;
238 this.packageName = packagename;
241 private final String namespace, packageName;
245 public void setResourceBaseDir(File resourceDir) {
246 this.resourceBaseDir = resourceDir;
250 public void setMavenProject(MavenProject project) {
251 this.projectBaseDir = project.getBasedir();
254 logger.debug(getClass().getCanonicalName(), " project base dir: ",
259 static class GeneratedFilesTracker {
260 private final Set<File> files = Sets.newHashSet();
262 void addFile(File file) {
263 if (files.contains(file)) {
264 List<File> undeletedFiles = Lists.newArrayList();
265 for (File presentFile : files) {
266 if (presentFile.delete() == false) {
267 undeletedFiles.add(presentFile);
270 if (undeletedFiles.isEmpty() == false) {
272 "Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
275 throw new IllegalStateException(
276 "Name conflict in generated files, file" + file
282 void addFile(Collection<File> files) {
283 for (File file : files) {
288 public Set<File> getFiles() {