BUG-980: stop emiting copyright
[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 org.apache.commons.io.FileUtils;
16 import org.apache.maven.plugin.logging.Log;
17 import org.apache.maven.project.MavenProject;
18 import org.opendaylight.controller.config.spi.ModuleFactory;
19 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
20 import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator;
21 import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
22 import org.opendaylight.controller.config.yangjmxgenerator.TypeProviderWrapper;
23 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.Module;
27 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
28 import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.slf4j.impl.StaticLoggerBinder;
32
33 import java.io.File;
34 import java.io.IOException;
35 import java.util.Collection;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Map.Entry;
40 import java.util.Set;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
43
44 /**
45  * This class interfaces with yang-maven-plugin. Gets parsed yang modules in
46  * {@link SchemaContext}, and parameters form the plugin configuration, and
47  * writes service interfaces and/or modules.
48  */
49 public class JMXGenerator implements CodeGenerator {
50
51     static final String NAMESPACE_TO_PACKAGE_DIVIDER = "==";
52     static final String NAMESPACE_TO_PACKAGE_PREFIX = "namespaceToPackage";
53     static final String MODULE_FACTORY_FILE_BOOLEAN = "moduleFactoryFile";
54
55     private PackageTranslator packageTranslator;
56     private final CodeWriter codeWriter;
57     private static final Logger logger = LoggerFactory
58             .getLogger(JMXGenerator.class);
59     private Map<String, String> namespaceToPackageMapping;
60     private File resourceBaseDir;
61     private File projectBaseDir;
62     private boolean generateModuleFactoryFile = true;
63
64     public JMXGenerator() {
65         this.codeWriter = new CodeWriter();
66     }
67
68     public JMXGenerator(CodeWriter codeWriter) {
69         this.codeWriter = codeWriter;
70     }
71
72     @Override
73     public Collection<File> generateSources(SchemaContext context,
74                                             File outputBaseDir, Set<Module> yangModulesInCurrentMavenModule) {
75
76         Preconditions.checkArgument(context != null, "Null context received");
77         Preconditions.checkArgument(outputBaseDir != null,
78                 "Null outputBaseDir received");
79
80         Preconditions
81                 .checkArgument(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(),
82                         "No namespace to package mapping provided in additionalConfiguration");
83
84         packageTranslator = new PackageTranslator(namespaceToPackageMapping);
85
86         if (!outputBaseDir.exists())
87             outputBaseDir.mkdirs();
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         StringBuffer fullyQualifiedNamesOfFactories = new StringBuffer();
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                 logger.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 (logger != null)
188             logger.debug(getClass().getCanonicalName(),
189                     ": Additional configuration received: ",
190                     additionalCfg.toString());
191         this.namespaceToPackageMapping = extractNamespaceMapping(additionalCfg);
192         this.generateModuleFactoryFile = extractModuleFactoryBoolean(additionalCfg);
193     }
194
195     private boolean extractModuleFactoryBoolean(
196             Map<String, String> additionalCfg) {
197         String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
198         if (bool == null)
199             return true;
200         if (bool.equals("false"))
201             return false;
202         return true;
203     }
204
205     @Override
206     public void setLog(Log log) {
207         StaticLoggerBinder.getSingleton().setMavenLog(log);
208     }
209
210     private static Map<String, String> extractNamespaceMapping(
211             Map<String, String> additionalCfg) {
212         Map<String, String> namespaceToPackage = Maps.newHashMap();
213         for (String key : additionalCfg.keySet()) {
214             if (key.startsWith(NAMESPACE_TO_PACKAGE_PREFIX)) {
215                 String mapping = additionalCfg.get(key);
216                 NamespaceMapping mappingResolved = extractNamespaceMapping(mapping);
217                 namespaceToPackage.put(mappingResolved.namespace,
218                         mappingResolved.packageName);
219             }
220         }
221         return namespaceToPackage;
222     }
223
224     static Pattern namespaceMappingPattern = Pattern.compile("(.+)"
225             + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
226
227     private static NamespaceMapping extractNamespaceMapping(String mapping) {
228         Matcher matcher = namespaceMappingPattern.matcher(mapping);
229         Preconditions
230                 .checkArgument(matcher.matches(), String.format("Namespace to package mapping:%s is in invalid " +
231                         "format, requested format is: %s", mapping, namespaceMappingPattern));
232         return new NamespaceMapping(matcher.group(1), matcher.group(2));
233     }
234
235     private static class NamespaceMapping {
236         public NamespaceMapping(String namespace, String packagename) {
237             this.namespace = namespace;
238             this.packageName = packagename;
239         }
240
241         private final String namespace, packageName;
242     }
243
244     @Override
245     public void setResourceBaseDir(File resourceDir) {
246         this.resourceBaseDir = resourceDir;
247     }
248
249     @Override
250     public void setMavenProject(MavenProject project) {
251         this.projectBaseDir = project.getBasedir();
252
253         if (logger != null)
254             logger.debug(getClass().getCanonicalName(), " project base dir: ",
255                     projectBaseDir);
256     }
257
258     @VisibleForTesting
259     static class GeneratedFilesTracker {
260         private final Set<File> files = Sets.newHashSet();
261
262         void addFile(File file) {
263             if (files.contains(file)) {
264                 List<File> undeletedFiles = Lists.newArrayList();
265                 for (File presentFile : files) {
266                     if (presentFile.delete() == false) {
267                         undeletedFiles.add(presentFile);
268                     }
269                 }
270                 if (undeletedFiles.isEmpty() == false) {
271                     logger.error(
272                             "Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
273                             undeletedFiles);
274                 }
275                 throw new IllegalStateException(
276                         "Name conflict in generated files, file" + file
277                                 + " present twice");
278             }
279             files.add(file);
280         }
281
282         void addFile(Collection<File> files) {
283             for (File file : files) {
284                 addFile(file);
285             }
286         }
287
288         public Set<File> getFiles() {
289             return files;
290         }
291     }
292 }