Merge "Bug 2697: Improvement wrong response handling, missing message"
[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.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;
41
42 /**
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.
46  */
47 public class JMXGenerator implements BasicCodeGenerator, MavenProjectAware {
48     private static final class NamespaceMapping {
49         private final String namespace, packageName;
50
51         public NamespaceMapping(final String namespace, final String packagename) {
52             this.namespace = namespace;
53             this.packageName = packagename;
54         }
55     }
56
57     @VisibleForTesting
58     static final String NAMESPACE_TO_PACKAGE_DIVIDER = "==";
59     @VisibleForTesting
60     static final String NAMESPACE_TO_PACKAGE_PREFIX = "namespaceToPackage";
61     @VisibleForTesting
62     static final String MODULE_FACTORY_FILE_BOOLEAN = "moduleFactoryFile";
63
64     private static final Logger LOG = LoggerFactory.getLogger(JMXGenerator.class);
65     private static final Pattern NAMESPACE_MAPPING_PATTERN = Pattern.compile("(.+)" + NAMESPACE_TO_PACKAGE_DIVIDER + "(.+)");
66
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;
73
74     public JMXGenerator() {
75         this(new CodeWriter());
76     }
77
78     public JMXGenerator(final CodeWriter codeWriter) {
79         this.codeWriter = codeWriter;
80     }
81
82     @Override
83     public Collection<File> generateSources(final SchemaContext context,
84                                             final File outputBaseDir, final Set<Module> yangModulesInCurrentMavenModule) {
85
86         Preconditions.checkArgument(context != null, "Null context received");
87         Preconditions.checkArgument(outputBaseDir != null,
88                 "Null outputBaseDir received");
89
90         Preconditions
91                 .checkArgument(namespaceToPackageMapping != null && !namespaceToPackageMapping.isEmpty(),
92                         "No namespace to package mapping provided in additionalConfiguration");
93
94         packageTranslator = new PackageTranslator(namespaceToPackageMapping);
95
96         if (!outputBaseDir.exists()) {
97             outputBaseDir.mkdirs();
98         }
99
100         GeneratedFilesTracker generatedFiles = new GeneratedFilesTracker();
101         // create SIE structure qNamesToSIEs
102         Map<QName, ServiceInterfaceEntry> qNamesToSIEs = new HashMap<>();
103
104
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);
110
111             for (Entry<QName, ServiceInterfaceEntry> sieEntry : namesToSIEntries
112                     .entrySet()) {
113                 // merge value into qNamesToSIEs
114                 if (qNamesToSIEs.containsKey(sieEntry.getKey()) == false) {
115                     qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
116                 } else {
117                     throw new IllegalStateException(
118                         "Cannot add two SIE  with same qname "
119                                 + sieEntry.getValue());
120                 }
121             }
122             if (yangModulesInCurrentMavenModule.contains(module)) {
123                 // write this sie to disk
124                 for (ServiceInterfaceEntry sie : namesToSIEntries.values()) {
125                     try {
126                         generatedFiles.addFile(codeWriter.writeSie(sie,
127                                 outputBaseDir));
128                     } catch (Exception e) {
129                         throw new RuntimeException(
130                                 "Error occurred during SIE source generate phase",
131                                 e);
132                     }
133                 }
134             }
135         }
136
137         File mainBaseDir = concatFolders(projectBaseDir, "src", "main", "java");
138         Preconditions.checkNotNull(resourceBaseDir,
139                 "resource base dir attribute was null");
140
141         StringBuilder fullyQualifiedNamesOfFactories = new StringBuilder();
142         // create MBEs
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)),
147                             packageName);
148
149             for (Entry<String, ModuleMXBeanEntry> mbeEntry : namesToMBEs
150                     .entrySet()) {
151                 ModuleMXBeanEntry mbe = mbeEntry.getValue();
152                 try {
153                     List<File> files1 = codeWriter.writeMbe(mbe, outputBaseDir,
154                             mainBaseDir);
155                     generatedFiles.addFile(files1);
156                 } catch (Exception e) {
157                     throw new RuntimeException(
158                             "Error occurred during MBE source generate phase",
159                             e);
160                 }
161                 fullyQualifiedNamesOfFactories.append(mbe
162                         .getFullyQualifiedName(mbe.getStubFactoryName()));
163                 fullyQualifiedNamesOfFactories.append("\n");
164             }
165         }
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();
174             try {
175                 serviceLoaderFile.createNewFile();
176                 FileUtils.write(serviceLoaderFile,
177                         fullyQualifiedNamesOfFactories.toString());
178             } catch (IOException e) {
179                 String message = "Cannot write to " + serviceLoaderFile;
180                 LOG.error(message);
181                 throw new RuntimeException(message, e);
182             }
183         }
184         return generatedFiles.getFiles();
185     }
186
187     @VisibleForTesting
188     static File concatFolders(final File projectBaseDir, final String... folderNames) {
189         StringBuilder b = new StringBuilder();
190         for (String folder : folderNames) {
191             b.append(folder);
192             b.append(File.separator);
193         }
194         return new File(projectBaseDir, b.toString());
195     }
196
197     @Override
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);
202     }
203
204     private boolean extractModuleFactoryBoolean(
205             final Map<String, String> additionalCfg) {
206         String bool = additionalCfg.get(MODULE_FACTORY_FILE_BOOLEAN);
207         if (bool == null) {
208             return true;
209         }
210         if ("false".equals(bool)) {
211             return false;
212         }
213         return true;
214     }
215
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);
225             }
226         }
227         return namespaceToPackage;
228     }
229
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));
236     }
237
238     @Override
239     public void setResourceBaseDir(final File resourceDir) {
240         this.resourceBaseDir = resourceDir;
241     }
242
243     @Override
244     public void setMavenProject(final MavenProject project) {
245         this.projectBaseDir = project.getBasedir();
246         LOG.debug("{}: project base dir: {}", getClass().getCanonicalName(), projectBaseDir);
247     }
248
249     @VisibleForTesting
250     static class GeneratedFilesTracker {
251         private final Set<File> files = Sets.newHashSet();
252
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);
259                     }
260                 }
261                 if (undeletedFiles.isEmpty() == false) {
262                     LOG.error(
263                             "Illegal state occurred: Unable to delete already generated files, undeleted files: {}",
264                             undeletedFiles);
265                 }
266                 throw new IllegalStateException(
267                         "Name conflict in generated files, file" + file
268                                 + " present twice");
269             }
270             files.add(file);
271         }
272
273         void addFile(final Collection<File> files) {
274             for (File file : files) {
275                 addFile(file);
276             }
277         }
278
279         public Set<File> getFiles() {
280             return files;
281         }
282     }
283 }