Fix various eclipse warnings
[mdsal.git] / binding / maven-sal-api-gen-plugin / src / test / java / org / opendaylight / yangtools / yang / unified / doc / generator / maven / retest / YangModuleInfoCompilationTest.java
1 /*
2  * Copyright (c) 2015 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.yangtools.yang.unified.doc.generator.maven.retest;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertTrue;
14 import java.io.File;
15 import java.io.FileNotFoundException;
16 import java.lang.reflect.Method;
17 import java.net.URI;
18 import java.net.URL;
19 import java.net.URLClassLoader;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.List;
23 import java.util.Set;
24 import javax.tools.JavaCompiler;
25 import javax.tools.JavaFileObject;
26 import javax.tools.StandardJavaFileManager;
27 import javax.tools.ToolProvider;
28 import org.junit.BeforeClass;
29 import org.junit.Test;
30 import org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl;
31 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
33 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
34
35 /**
36  * Test correct generation of YangModuleInfo class.
37  *
38  */
39 // TODO: most of private static methods are copied from
40 // binding-java-api-generator project - reorganize compilation tests
41 public class YangModuleInfoCompilationTest {
42     public static final String FS = File.separator;
43     private static final String BASE_PKG = "org.opendaylight.yang.gen.v1";
44
45     private static final String TEST_PATH = "target" + FS + "test";
46     private static final File TEST_DIR = new File(TEST_PATH);
47
48     private static final String GENERATOR_OUTPUT_PATH = TEST_PATH + FS + "src";
49     private static final File GENERATOR_OUTPUT_DIR = new File(GENERATOR_OUTPUT_PATH);
50     private static final String COMPILER_OUTPUT_PATH = TEST_PATH + FS + "bin";
51     private static final File COMPILER_OUTPUT_DIR = new File(COMPILER_OUTPUT_PATH);
52
53     @BeforeClass
54     public static void createTestDirs() {
55         if (TEST_DIR.exists()) {
56             deleteTestDir(TEST_DIR);
57         }
58         assertTrue(GENERATOR_OUTPUT_DIR.mkdirs());
59         assertTrue(COMPILER_OUTPUT_DIR.mkdirs());
60     }
61
62     @Test
63     public void compilationTest() throws Exception {
64         final File sourcesOutputDir = new File(GENERATOR_OUTPUT_PATH + FS + "yang");
65         assertTrue("Failed to create test file '" + sourcesOutputDir + "'", sourcesOutputDir.mkdirs());
66         final File compiledOutputDir = new File(COMPILER_OUTPUT_PATH + FS + "yang");
67         assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdirs());
68
69         generateTestSources("/yang-module-info", sourcesOutputDir);
70
71         // Test if $YangModuleInfoImpl.java file is generated
72         final String BASE_PATH = "org" + FS + "opendaylight" + FS + "yang" + FS + "gen" + FS + "v1";
73         final String NS_TEST = BASE_PATH + FS + "yang" + FS + "test" + FS + "main" + FS + "rev140630";
74         File parent = new File(sourcesOutputDir, NS_TEST);
75         File keyArgs = new File(parent, "$YangModuleInfoImpl.java");
76         assertTrue(keyArgs.exists());
77
78         // Test if sources are compilable
79         testCompilation(sourcesOutputDir, compiledOutputDir);
80
81         // Create URLClassLoader
82         URL[] urls = new URL[2];
83         urls[0] = compiledOutputDir.toURI().toURL();
84         urls[1] = new File(System.getProperty("user.dir")).toURI().toURL();
85         ClassLoader loader = new URLClassLoader(urls);
86
87         // Load class
88         Class<?> yangModuleInfoClass = Class.forName(BASE_PKG + ".yang.test.main.rev140630.$YangModuleInfoImpl", true,
89                 loader);
90
91         // Test generated $YangModuleInfoImpl class
92         assertFalse(yangModuleInfoClass.isInterface());
93         Method getInstance = assertContainsMethod(yangModuleInfoClass, YangModuleInfo.class, "getInstance");
94         Object yangModuleInfo = getInstance.invoke(null);
95
96         // Test getImportedModules method
97         Method getImportedModules = assertContainsMethod(yangModuleInfoClass, Set.class, "getImportedModules");
98         Object importedModules = getImportedModules.invoke(yangModuleInfo);
99         assertTrue(importedModules instanceof Set);
100
101         YangModuleInfo infoImport = null;
102         YangModuleInfo infoSub1 = null;
103         YangModuleInfo infoSub2 = null;
104         YangModuleInfo infoSub3 = null;
105         for (Object importedModule : (Set<?>) importedModules) {
106             assertTrue(importedModule instanceof YangModuleInfo);
107             YangModuleInfo ymi = (YangModuleInfo) importedModule;
108             String name = ymi.getName();
109
110             switch (name) {
111             case "import-module":
112                 infoImport = ymi;
113                 break;
114             case "submodule1":
115                 infoSub1 = ymi;
116                 break;
117             case "submodule2":
118                 infoSub2 = ymi;
119                 break;
120             case "submodule3":
121                 infoSub3 = ymi;
122             }
123         }
124         assertNotNull(infoImport);
125         assertNotNull(infoSub1);
126         assertNotNull(infoSub2);
127         assertNotNull(infoSub3);
128
129         cleanUp(sourcesOutputDir, compiledOutputDir);
130     }
131
132     private static void generateTestSources(final String resourceDirPath, final File sourcesOutputDir) throws Exception {
133         final List<File> sourceFiles = getSourceFiles(resourceDirPath);
134         final SchemaContext context = RetestUtils.parseYangSources(sourceFiles);
135         CodeGeneratorImpl codegen = new CodeGeneratorImpl();
136         codegen.setBuildContext(new DefaultBuildContext());
137         codegen.generateSources(context, sourcesOutputDir, context.getModules());
138     }
139
140     private static void testCompilation(final File sourcesOutputDir, final File compiledOutputDir) {
141         JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
142         StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
143         List<File> filesList = getJavaFiles(sourcesOutputDir);
144         Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(filesList);
145         Iterable<String> options = Arrays.asList("-d", compiledOutputDir.getAbsolutePath());
146         boolean compiled = compiler.getTask(null, null, null, options, null, compilationUnits).call();
147         assertTrue(compiled);
148     }
149
150     private static List<File> getJavaFiles(final File directory) {
151         List<File> result = new ArrayList<>();
152         File[] filesToRead = directory.listFiles();
153         if (filesToRead != null) {
154             for (File file : filesToRead) {
155                 if (file.isDirectory()) {
156                     result.addAll(getJavaFiles(file));
157                 } else {
158                     String absPath = file.getAbsolutePath();
159                     if (absPath.endsWith(".java")) {
160                         result.add(file);
161                     }
162                 }
163             }
164         }
165         return result;
166     }
167
168     private static List<File> getSourceFiles(final String path) throws Exception {
169         final URI resPath = YangModuleInfoCompilationTest.class.getResource(path).toURI();
170         final File sourcesDir = new File(resPath);
171         final URI currentDir = new File(System.getProperty("user.dir")).toURI();
172         if (sourcesDir.exists()) {
173             final List<File> sourceFiles = new ArrayList<>();
174             final File[] fileArray = sourcesDir.listFiles();
175             if (fileArray == null) {
176                 throw new IllegalArgumentException("Unable to locate files in " + sourcesDir);
177             }
178             for (File sourceFile : fileArray) {
179                 sourceFiles.add(new File(currentDir.relativize(sourceFile.toURI()).toString()));
180             }
181             return sourceFiles;
182         } else {
183             throw new FileNotFoundException("Testing files were not found(" + sourcesDir.getName() + ")");
184         }
185     }
186
187     private static void deleteTestDir(final File file) {
188         if (file.isDirectory()) {
189             File[] filesToDelete = file.listFiles();
190             if (filesToDelete != null) {
191                 for (File f : filesToDelete) {
192                     deleteTestDir(f);
193                 }
194             }
195         }
196         if (!file.delete()) {
197             throw new RuntimeException("Failed to clean up after test");
198         }
199     }
200
201     private static Method assertContainsMethod(final Class<?> clazz, final Class<?> returnType, final String name, final Class<?>... args) {
202         try {
203             Method m = clazz.getDeclaredMethod(name, args);
204             assertEquals(returnType, m.getReturnType());
205             return m;
206         } catch (NoSuchMethodException e) {
207             throw new AssertionError("Method " + name + " with args " + Arrays.toString(args)
208                     + " does not exists in class " + clazz.getSimpleName());
209         }
210     }
211
212     private static void cleanUp(final File... resourceDirs) {
213         for (File resourceDir : resourceDirs) {
214             if (resourceDir.exists()) {
215                 deleteTestDir(resourceDir);
216             }
217         }
218     }
219
220 }