Merge "Reuse PEM provider in netconf-testtool."
[controller.git] / opendaylight / config / yang-jmx-generator-plugin / src / main / java / org / opendaylight / controller / config / yangjmxgenerator / plugin / JMXGenerator.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.config.yangjmxgenerator.plugin;
9
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 java.io.File;
16 import java.io.IOException;
17 import java.util.Collection;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Set;
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;
42
43 /**
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.
47  */
48 public class JMXGenerator implements CodeGenerator {
49
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";
53
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;
62
63     public JMXGenerator() {
64         this.codeWriter = new CodeWriter();
65     }
66
67     public JMXGenerator(CodeWriter codeWriter) {
68         this.codeWriter = codeWriter;
69     }
70
71     @Override
72     public Collection<File> generateSources(SchemaContext context,
73                                             File outputBaseDir, Set<Module> yangModulesInCurrentMavenModule) {
74
75         Preconditions.checkArgument(context != null, "Null context received");
76         Preconditions.checkArgument(outputBaseDir != null,
77                 "Null outputBaseDir received");
78
79         Preconditions
80                 .checkArgument(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(),
81                         "No namespace to package mapping provided in additionalConfiguration");
82
83         packageTranslator = new PackageTranslator(namespaceToPackageMapping);
84
85         if (!outputBaseDir.exists()) {
86             outputBaseDir.mkdirs();
87         }
88
89         GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker();
90         // create SIE structure qNamesToSIEs
91         Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>();
92
93
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);
99
100             for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries
101                     .entrySet()) {
102                 // merge value into qNamesToSIEs
103                 if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) {
104                     qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
105                 } else {
106                     throw new IllegalStateException(
107                         "Cannot add two SIE  with same qname "
108                                 + sieEntry.getValue());
109                 }
110             }
111             if (yangModulesInCurrentMavenModule.contains(module)) {
112                 // write this sie to disk
113                 for (ServiceInterfaceEntry sie : namesToSIEntries.values()) {
114                     try {
115                         generatedFiles.addFile(codeWriter.writeSie(sie,
116                                 outputBaseDir));
117                     } catch (Exception e) {
118                         throw new RuntimeException(
119                                 "Error occurred during SIE source generate phase",
120                                 e);
121                     }
122                 }
123             }
124         }
125
126         File mainBaseDir = concatFolders(projectBaseDir, "src", "main", "java");
127         Preconditions.checkNotNull(resourceBaseDir,
128                 "resource base dir attribute was null");
129
130         StringBuilder fullyQualifiedNamesOfFactories = new StringBuilder();
131         // create MBEs
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)),
136                             packageName);
137
138             for (Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs
139                     .entrySet()) {
140                 ModuleMXBeanEntry mbe = mbeEntry.getValue();
141                 try {
142                     List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir,
143                             mainBaseDir);
144                     generatedFiles.addFile(files1);
145                 } catch (Exception e) {
146                     throw new RuntimeException(
147                             "Error occurred during MBE source generate phase",
148                             e);
149                 }
150                 fullyQualifiedNamesOfFactories.append(mbe
151                         .getFullyQualifiedName(mbe.getStubFactoryName()));
152                 fullyQualifiedNamesOfFactories.append("\n");
153             }
154         }
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();
163             try {
164                 serviceLoaderFile.createNewFile();
165                 FileUtils.write(serviceLoaderFile,
166                         fullyQualifiedNamesOfFactories.toString());
167             } catch (IOException e) {
168                 String message = "Cannot write to " + serviceLoaderFile;
169                 LOG.error(message);
170                 throw new RuntimeException(message, e);
171             }
172         }
173         return generatedFiles.getFiles();
174     }
175
176     static File concatFolders(File projectBaseDir, String... folderNames) {
177         StringBuilder b = new StringBuilder();
178         for (String folder : folderNames) {
179             b.append(folder);
180             b.append(File.separator);
181         }
182         return new File(projectBaseDir, b.toString());
183     }
184
185     @Override
186     public void setAdditionalConfig(Map<String, String> additionalCfg) {
187         if (LOG != null) {
188             LOG.debug(getClass().getCanonicalName(),
189                     ": Additional configuration received: ",
190                     additionalCfg.toString());
191         }
192         this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg);
193         this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg);
194     }
195
196     private boolean extractModuleFactoryBoolean(
197             Map<String, String> additionalCfg) {
198         String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
199         if (bool == null) {
200             return true;
201         }
202         if ("false".equals(bool)) {
203             return false;
204         }
205         return true;
206     }
207
208     @Override
209     public void setLog(Log log) {
210         StaticLoggerBinder.getSingleton().setMavenLog(log);
211     }
212
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);
222             }
223         }
224         return namespaceToPackage;
225     }
226
227     static Pattern namespaceMappingPattern = Pattern.compile("(.+)"
228             + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
229
230     private static NamespaceMapping extractNamespaceMapping(String mapping) {
231         Matcher matcher = namespaceMappingPattern.matcher(mapping);
232         Preconditions
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));
236     }
237
238     private static class NamespaceMapping {
239         public NamespaceMapping(String namespace, String packagename) {
240             this.namespace = namespace;
241             this.packageName = packagename;
242         }
243
244         private final String namespace, packageName;
245     }
246
247     @Override
248     public void setResourceBaseDir(File resourceDir) {
249         this.resourceBaseDir = resourceDir;
250     }
251
252     @Override
253     public void setMavenProject(MavenProject project) {
254         this.projectBaseDir = project.getBasedir();
255
256         if (LOG != null) {
257             LOG.debug(getClass().getCanonicalName(), " project base dir: ",
258                     projectBaseDir);
259         }
260     }
261
262     @VisibleForTesting
263     static class GeneratedFilesTracker {
264         private final Set<File> files = Sets.newHashSet();
265
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);
272                     }
273                 }
274                 if (undeletedFiles.isEmpty() == false) {
275                     LOG.error(
276                             "Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
277                             undeletedFiles);
278                 }
279                 throw new IllegalStateException(
280                         "Name conflict in generated files, file" + file
281                                 + " present twice");
282             }
283             files.add(file);
284         }
285
286         void addFile(Collection<File> files) {
287             for (File file : files) {
288                 addFile(file);
289             }
290         }
291
292         public Set<File> getFiles() {
293             return files;
294         }
295     }
296 }