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.project.MavenProject;
27 import org.opendaylight.controller.config.spi.ModuleFactory;
28 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
29 import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator;
30 import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
31 import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
32 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.Module;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
38 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * This class interfaces with yang-maven-plugin. Gets parsed yang modules in
44 * {@link SchemaContext}, and parameters form the plugin configuration, and
45 * writes service interfaces and/or modules.
47 public class JMXGenerator implements BasicCodeGenerator, MavenProjectAware {
48 private static final class NamespaceMapping {
49 private final String namespace, packageName;
51 public NamespaceMapping(final String namespace, final String packagename) {
52 this.namespace = namespace;
53 this.packageName = packagename;
58 static final String NAMESPACE_TO_PACKAGE_DIVIDER = "==";
60 static final String NAMESPACE_TO_PACKAGE_PREFIX = "namespaceToPackage";
62 static final String MODULE_FACTORY_FILE_BOOLEAN = "moduleFactoryFile";
64 private static final Logger LOG = LoggerFactory.getLogger(JMXGenerator.class);
65 private static final Pattern NAMESPACE_MAPPING_PATTERN = Pattern.compile("(.+)" + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
67 private PackageTranslator packageTranslator;
68 private final CodeWriter codeWriter;
69 private Map<String, String> namespaceToPackageMapping;
70 private File resourceBaseDir;
71 private File projectBaseDir;
72 private boolean generateModuleFactoryFile = true;
74 public JMXGenerator() {
75 this(new CodeWriter());
78 public JMXGenerator(final CodeWriter codeWriter) {
79 this.codeWriter = codeWriter;
83 public Collection<File> generateSources(final SchemaContext context,
84 final File outputBaseDir, final Set<Module> yangModulesInCurrentMavenModule) {
86 Preconditions.checkArgument(context != null, "Null context received");
87 Preconditions.checkArgument(outputBaseDir != null,
88 "Null outputBaseDir received");
91 .checkArgument(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(),
92 "No namespace to package mapping provided in additionalConfiguration");
94 packageTranslator = new PackageTranslator(namespaceToPackageMapping);
96 if (!outputBaseDir.exists()) {
97 outputBaseDir.mkdirs();
100 GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker();
101 // create SIE structure qNamesToSIEs
102 Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>();
105 Map<IdentitySchemaNode, ServiceInterfaceEntry> knownSEITracker = new HashMap<>();
106 for (Module module : context.getModules()) {
107 String packageName = packageTranslator.getPackageName(module);
108 Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry
109 .create(module, packageName, knownSEITracker);
111 for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries
113 // merge value into qNamesToSIEs
114 if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) {
115 qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
117 throw new IllegalStateException(
118 "Cannot add two SIE with same qname "
119 + sieEntry.getValue());
122 if (yangModulesInCurrentMavenModule.contains(module)) {
123 // write this sie to disk
124 for (ServiceInterfaceEntry sie : namesToSIEntries.values()) {
126 generatedFiles.addFile(codeWriter.writeSie(sie,
128 } catch (Exception e) {
129 throw new RuntimeException(
130 "Error occurred during SIE source generate phase",
137 File mainBaseDir = concatFolders(projectBaseDir, "src", "main", "java");
138 Preconditions.checkNotNull(resourceBaseDir,
139 "resource base dir attribute was null");
141 StringBuilder fullyQualifiedNamesOfFactories = new StringBuilder();
143 for (Module module : yangModulesInCurrentMavenModule) {
144 String packageName = packageTranslator.getPackageName(module);
145 Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
146 .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)),
149 for (Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs
151 ModuleMXBeanEntry mbe = mbeEntry.getValue();
153 List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir,
155 generatedFiles.addFile(files1);
156 } catch (Exception e) {
157 throw new RuntimeException(
158 "Error occurred during MBE source generate phase",
161 fullyQualifiedNamesOfFactories.append(mbe
162 .getFullyQualifiedName(mbe.getStubFactoryName()));
163 fullyQualifiedNamesOfFactories.append("\n");
166 // create ModuleFactory file if needed
167 if (fullyQualifiedNamesOfFactories.length() > 0
168 && generateModuleFactoryFile) {
169 File serviceLoaderFile = JMXGenerator.concatFolders(
170 resourceBaseDir, "META-INF", "services",
171 ModuleFactory.class.getName());
172 // if this file does not exist, create empty file
173 serviceLoaderFile.getParentFile().mkdirs();
175 serviceLoaderFile.createNewFile();
176 FileUtils.write(serviceLoaderFile,
177 fullyQualifiedNamesOfFactories.toString());
178 } catch (IOException e) {
179 String message = "Cannot write to " + serviceLoaderFile;
181 throw new RuntimeException(message, e);
184 return generatedFiles.getFiles();
188 static File concatFolders(final File projectBaseDir, final String... folderNames) {
189 StringBuilder b = new StringBuilder();
190 for (String folder : folderNames) {
192 b.append(File.separator);
194 return new File(projectBaseDir, b.toString());
198 public void setAdditionalConfig(final Map<String, String> additionalCfg) {
199 LOG.debug("{}: Additional configuration received: {}", getClass().getCanonicalName(), additionalCfg);
200 this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg);
201 this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg);
204 private boolean extractModuleFactoryBoolean(
205 final Map<String, String> additionalCfg) {
206 String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
210 if ("false".equals(bool)) {
216 private static Map<String, String> extractNamespaceMapping(
217 final Map<String, String> additionalCfg) {
218 Map<String, String> namespaceToPackage = Maps.newHashMap();
219 for (String key : additionalCfg.keySet()) {
220 if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) {
221 String mapping = additionalCfg.get(key);
222 NamespaceMapping mappingResolved = extractNamespaceMapping(mapping);
223 namespaceToPackage.put(mappingResolved.namespace,
224 mappingResolved.packageName);
227 return namespaceToPackage;
230 private static NamespaceMapping extractNamespaceMapping(final String mapping) {
231 Matcher matcher = NAMESPACE_MAPPING_PATTERN.matcher(mapping);
232 Preconditions.checkArgument(matcher.matches(),
233 "Namespace to package mapping:%s is in invalid format, requested format is: %s",
234 mapping, NAMESPACE_MAPPING_PATTERN);
235 return new NamespaceMapping(matcher.group(1), matcher.group(2));
239 public void setResourceBaseDir(final File resourceDir) {
240 this.resourceBaseDir = resourceDir;
244 public void setMavenProject(final MavenProject project) {
245 this.projectBaseDir = project.getBasedir();
246 LOG.debug("{}: project base dir: {}", getClass().getCanonicalName(), projectBaseDir);
250 static class GeneratedFilesTracker {
251 private final Set<File> files = Sets.newHashSet();
253 void addFile(final File file) {
254 if (files.contains(file)) {
255 List<File> undeletedFiles = Lists.newArrayList();
256 for (File presentFile : files) {
257 if (presentFile.delete() == false) {
258 undeletedFiles.add(presentFile);
261 if (undeletedFiles.isEmpty() == false) {
263 "Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
266 throw new IllegalStateException(
267 "Name conflict in generated files, file" + file
273 void addFile(final Collection<File> files) {
274 for (File file : files) {
279 public Set<File> getFiles() {