View Javadoc
1   package net.sourceforge.jenesis4java.util;
2   
3   /*
4    * #%L
5    * Jenesis 4 Java Code Generator
6    * %%
7    * Copyright (C) 2000 - 2016 jenesis4java
8    * %%
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU Lesser General Public License as
11   * published by the Free Software Foundation, either version 3 of the
12   * License, or (at your option) any later version.
13   * 
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Lesser Public License for more details.
18   * 
19   * You should have received a copy of the GNU General Lesser Public
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/lgpl-3.0.html>.
22   * #L%
23   */
24  
25  import net.sourceforge.jenesis4java.CompilationUnit;
26  import net.sourceforge.jenesis4java.VirtualMachine;
27  import org.junit.rules.ExternalResource;
28  
29  import java.io.File;
30  import java.io.IOException;
31  
32  import static org.junit.Assert.assertTrue;
33  
34  public class VmInTempFolder extends ExternalResource {
35  
36      private VirtualMachine vm;
37  
38      private File tempDirectory;
39  
40      @Override
41      public void before() throws IOException {
42          vm = VirtualMachine.getVirtualMachine();
43          tempDirectory = File.createTempFile("jenesisTmp", "tmp");
44          tempDirectory.delete();
45          tempDirectory.mkdirs();
46      }
47  
48      @Override
49      public void after() {
50          recursiveDelete(tempDirectory);
51      }
52  
53      public CompilationUnit newCompilationUnit() throws IOException {
54          return vm.newCompilationUnit(tempDirectory.getCanonicalPath());
55      }
56  
57      public VirtualMachine getVm() {
58          return vm;
59      }
60  
61      public void assertFileExists(String path) {
62          File pathToFile = new File(tempDirectory, path);
63          String errorMsg = "File with path '" + path //
64                  + "' (complete path: '" + pathToFile + "') does not exist.";
65          assertTrue(errorMsg, pathToFile.exists());
66      }
67  
68      private void recursiveDelete(File file) {
69          File[] files = file.listFiles();
70          if (files != null) {
71              for (File each : files) {
72                  recursiveDelete(each);
73              }
74          }
75          file.delete();
76      }
77  
78  }