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.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.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(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(),
92 "No namespace to package mapping provided in additionalConfiguration");
94 PackageTranslator 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.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 (ServiceInterfaceEntry sie : namesToSIEntries.values()) {
124 generatedFiles.addFile(codeWriter.writeSie(sie,
126 } catch (Exception e) {
127 throw new RuntimeException(
128 "Error occurred during SIE source generate phase",
135 File mainBaseDir = concatFolders(projectBaseDir, "src", "main", "java");
136 Preconditions.checkNotNull(resourceBaseDir,
137 "resource base dir attribute was null");
139 StringBuilder fullyQualifiedNamesOfFactories = new StringBuilder();
141 for (Module module : yangModulesInCurrentMavenModule) {
142 String packageName = packageTranslator.getPackageName(module);
143 Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
144 .create(module, qNamesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context)),
147 for (Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs
149 ModuleMXBeanEntry mbe = mbeEntry.getValue();
151 List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir,
153 generatedFiles.addFile(files1);
154 } catch (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 && generateModuleFactoryFile) {
167 File serviceLoaderFile = JMXGenerator.concatFolders(
168 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 (IOException e) {
176 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 (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 boolean extractModuleFactoryBoolean(
201 final Map<String, String> additionalCfg) {
202 String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
203 return !"false".equals(bool);
206 private static Map<String, String> extractNamespaceMapping(
207 final Map<String, String> additionalCfg) {
208 Map<String, String> namespaceToPackage = Maps.newHashMap();
209 for (String key : additionalCfg.keySet()) {
210 if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) {
211 String mapping = additionalCfg.get(key);
212 NamespaceMapping mappingResolved = extractNamespaceMapping(mapping);
213 namespaceToPackage.put(mappingResolved.namespace,
214 mappingResolved.packageName);
217 return namespaceToPackage;
220 private static NamespaceMapping extractNamespaceMapping(final String mapping) {
221 Matcher matcher = NAMESPACE_MAPPING_PATTERN.matcher(mapping);
222 Preconditions.checkArgument(matcher.matches(),
223 "Namespace to package mapping:%s is in invalid format, requested format is: %s",
224 mapping, NAMESPACE_MAPPING_PATTERN);
225 return new NamespaceMapping(matcher.group(1), matcher.group(2));
229 public void setResourceBaseDir(final File resourceDir) {
230 this.resourceBaseDir = resourceDir;
234 public void setMavenProject(final MavenProject project) {
235 this.projectBaseDir = project.getBasedir();
236 LOG.debug("{}: project base dir: {}", getClass().getCanonicalName(), projectBaseDir);
240 static class GeneratedFilesTracker {
241 private final Set<File> files = Sets.newHashSet();
243 void addFile(final File file) {
244 if (files.contains(file)) {
245 List<File> undeletedFiles = Lists.newArrayList();
246 for (File presentFile : files) {
247 if (!presentFile.delete()) {
248 undeletedFiles.add(presentFile);
251 if (!undeletedFiles.isEmpty()) {
253 "Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
256 throw new IllegalStateException(
257 "Name conflict in generated files, file" + file
263 void addFile(final Collection<File> files) {
264 for (File file : files) {
269 public Set<File> getFiles() {