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 com.google.common.io.Files;
17 import java.io.IOException;
18 import java.nio.charset.StandardCharsets;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.List;
23 import java.util.Map.Entry;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
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.mdsal.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.BasicCodeGenerator;
39 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
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 BasicCodeGenerator, MavenProjectAware {
49 private static final class NamespaceMapping {
50 private final String namespace, packageName;
52 public NamespaceMapping(final String namespace, final String packagename) {
53 this.namespace = namespace;
54 this.packageName = packagename;
59 static final String NAMESPACE_TO_PACKAGE_DIVIDER = "==";
61 static final String NAMESPACE_TO_PACKAGE_PREFIX = "namespaceToPackage";
63 static final String MODULE_FACTORY_FILE_BOOLEAN = "moduleFactoryFile";
65 private static final Logger LOG = LoggerFactory.getLogger(JMXGenerator.class);
66 private static final Pattern NAMESPACE_MAPPING_PATTERN = Pattern.compile("(.+)" + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
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((this.namespaceToPackageMapping != null) && !this.namespaceToPackageMapping.isEmpty(),
92 "No namespace to package mapping provided in additionalConfiguration");
94 final PackageTranslator packageTranslator = new PackageTranslator(this.namespaceToPackageMapping);
96 if (!outputBaseDir.exists()) {
97 outputBaseDir.mkdirs();
100 final GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker();
101 // create SIE structure qNamesToSIEs
102 final Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>();
105 final Map<IdentitySchemaNode, ServiceInterfaceEntry> knownSEITracker = new HashMap<>();
106 for (final Module module : context.getModules()) {
107 final String packageName = packageTranslator.getPackageName(module);
108 final Map<QName, ServiceInterfaceEntry> namesToSIEntries = ServiceInterfaceEntry
109 .create(module, packageName, knownSEITracker);
111 for (final Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries
113 // merge value into qNamesToSIEs
114 if (qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue()) != null) {
115 throw new IllegalStateException(
116 "Cannot add two SIE with same qname "
117 + sieEntry.getValue());
120 if (yangModulesInCurrentMavenModule.contains(module)) {
121 // write this sie to disk
122 for (final ServiceInterfaceEntry sie : namesToSIEntries.values()) {
124 generatedFiles.addFile(this.codeWriter.writeSie(sie,
126 } catch (final Exception e) {
127 throw new RuntimeException(
128 "Error occurred during SIE source generate phase",
135 final File mainBaseDir = concatFolders(this.projectBaseDir, "src", "main", "java");
136 Preconditions.checkNotNull(this.resourceBaseDir,
137 "resource base dir attribute was null");
139 final StringBuilder fullyQualifiedNamesOfFactories = new StringBuilder();
141 for (final Module module : yangModulesInCurrentMavenModule) {
142 final String packageName = packageTranslator.getPackageName(module);
143 final Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
144 .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)),
147 for (final Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs
149 final ModuleMXBeanEntry mbe = mbeEntry.getValue();
151 final List<File> files1 = this.codeWriter.writeMbe(mbe, outputBaseDir,
153 generatedFiles.addFile(files1);
154 } catch (final Exception e) {
155 throw new RuntimeException(
156 "Error occurred during MBE source generate phase",
159 fullyQualifiedNamesOfFactories.append(mbe
160 .getFullyQualifiedName(mbe.getStubFactoryName()));
161 fullyQualifiedNamesOfFactories.append("\n");
164 // create ModuleFactory file if needed
165 if ((fullyQualifiedNamesOfFactories.length() > 0)
166 && this.generateModuleFactoryFile) {
167 final File serviceLoaderFile = JMXGenerator.concatFolders(
168 this.resourceBaseDir, "META-INF", "services",
169 ModuleFactory.class.getName());
170 // if this file does not exist, create empty file
171 serviceLoaderFile.getParentFile().mkdirs();
173 serviceLoaderFile.createNewFile();
174 Files.write(fullyQualifiedNamesOfFactories.toString(), serviceLoaderFile, StandardCharsets.UTF_8);
175 } catch (final IOException e) {
176 final String message = "Cannot write to " + serviceLoaderFile;
177 LOG.error(message, e);
178 throw new RuntimeException(message, e);
181 return generatedFiles.getFiles();
185 static File concatFolders(final File projectBaseDir, final String... folderNames) {
186 File result = projectBaseDir;
187 for (final String folder: folderNames) {
188 result = new File(result, folder);
194 public void setAdditionalConfig(final Map<String, String> additionalCfg) {
195 LOG.debug("{}: Additional configuration received: {}", getClass().getCanonicalName(), additionalCfg);
196 this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg);
197 this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg);
200 private static boolean extractModuleFactoryBoolean(final Map<String, String> additionalCfg) {
201 final String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
202 return !"false".equals(bool);
205 private static Map<String, String> extractNamespaceMapping(
206 final Map<String, String> additionalCfg) {
207 final Map<String, String> namespaceToPackage = Maps.newHashMap();
208 for (final String key : additionalCfg.keySet()) {
209 if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) {
210 final String mapping = additionalCfg.get(key);
211 final NamespaceMapping mappingResolved = extractNamespaceMapping(mapping);
212 namespaceToPackage.put(mappingResolved.namespace,
213 mappingResolved.packageName);
216 return namespaceToPackage;
219 private static NamespaceMapping extractNamespaceMapping(final String mapping) {
220 final Matcher matcher = NAMESPACE_MAPPING_PATTERN.matcher(mapping);
221 Preconditions.checkArgument(matcher.matches(),
222 "Namespace to package mapping:%s is in invalid format, requested format is: %s",
223 mapping, NAMESPACE_MAPPING_PATTERN);
224 return new NamespaceMapping(matcher.group(1), matcher.group(2));
228 public void setResourceBaseDir(final File resourceDir) {
229 this.resourceBaseDir = resourceDir;
233 public void setMavenProject(final MavenProject project) {
234 this.projectBaseDir = project.getBasedir();
235 LOG.debug("{}: project base dir: {}", getClass().getCanonicalName(), this.projectBaseDir);
239 static class GeneratedFilesTracker {
240 private final Set<File> files = Sets.newHashSet();
242 void addFile(final File file) {
243 if (this.files.contains(file)) {
244 final List<File> undeletedFiles = Lists.newArrayList();
245 for (final File presentFile : this.files) {
246 if (!presentFile.delete()) {
247 undeletedFiles.add(presentFile);
250 if (!undeletedFiles.isEmpty()) {
252 "Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
255 throw new IllegalStateException(
256 "Name conflict in generated files, file" + file
259 this.files.add(file);
262 void addFile(final Collection<File> files) {
263 for (final File file : files) {
268 public Set<File> getFiles() {