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;
16 import java.io.IOException;
17 import java.util.Collection;
18 import java.util.HashMap;
19 import java.util.List;
21 import java.util.Map.Entry;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import org.apache.commons.io.FileUtils;
26 import org.apache.maven.plugin.logging.Log;
27 import org.apache.maven.project.MavenProject;
28 import org.opendaylight.controller.config.spi.ModuleFactory;
29 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
30 import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator;
31 import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
32 import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
33 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
34 import org.opendaylight.yangtools.yang.common.QName;
35 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.Module;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
38 import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.slf4j.impl.StaticLoggerBinder;
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 LOG = 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 CodeWriter();
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();
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 StringBuilder fullyQualifiedNamesOfFactories = new StringBuilder();
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;
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 LOG.debug(getClass().getCanonicalName(),
189 ": Additional configuration received: ",
190 additionalCfg.toString());
192 this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg);
193 this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg);
196 private boolean extractModuleFactoryBoolean(
197 Map<String, String> additionalCfg) {
198 String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
202 if ("false".equals(bool)) {
209 public void setLog(Log log) {
210 StaticLoggerBinder.getSingleton().setMavenLog(log);
213 private static Map<String, String> extractNamespaceMapping(
214 Map<String, String> additionalCfg) {
215 Map<String, String> namespaceToPackage = Maps.newHashMap();
216 for (String key : additionalCfg.keySet()) {
217 if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) {
218 String mapping = additionalCfg.get(key);
219 NamespaceMapping mappingResolved = extractNamespaceMapping(mapping);
220 namespaceToPackage.put(mappingResolved.namespace,
221 mappingResolved.packageName);
224 return namespaceToPackage;
227 static Pattern namespaceMappingPattern = Pattern.compile("(.+)"
228 + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
230 private static NamespaceMapping extractNamespaceMapping(String mapping) {
231 Matcher matcher = namespaceMappingPattern.matcher(mapping);
233 .checkArgument(matcher.matches(), String.format("Namespace to package mapping:%s is in invalid " +
234 "format, requested format is: %s", mapping, namespaceMappingPattern));
235 return new NamespaceMapping(matcher.group(1), matcher.group(2));
238 private static class NamespaceMapping {
239 public NamespaceMapping(String namespace, String packagename) {
240 this.namespace = namespace;
241 this.packageName = packagename;
244 private final String namespace, packageName;
248 public void setResourceBaseDir(File resourceDir) {
249 this.resourceBaseDir = resourceDir;
253 public void setMavenProject(MavenProject project) {
254 this.projectBaseDir = project.getBasedir();
257 LOG.debug(getClass().getCanonicalName(), " project base dir: ",
263 static class GeneratedFilesTracker {
264 private final Set<File> files = Sets.newHashSet();
266 void addFile(File file) {
267 if (files.contains(file)) {
268 List<File> undeletedFiles = Lists.newArrayList();
269 for (File presentFile : files) {
270 if (presentFile.delete() == false) {
271 undeletedFiles.add(presentFile);
274 if (undeletedFiles.isEmpty() == false) {
276 "Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
279 throw new IllegalStateException(
280 "Name conflict in generated files, file" + file
286 void addFile(Collection<File> files) {
287 for (File file : files) {
292 public Set<File> getFiles() {