View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.artifact.testutils;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.Iterator;
25  import java.util.List;
26  
27  import org.codehaus.plexus.util.FileUtils;
28  
29  import static org.junit.jupiter.api.Assertions.assertEquals;
30  import static org.junit.jupiter.api.Assertions.assertFalse;
31  import static org.junit.jupiter.api.Assertions.assertTrue;
32  
33  public class TestFileManager {
34  
35      public static final String TEMP_DIR_PATH = System.getProperty("java.io.tmpdir");
36  
37      private List<File> filesToDelete = new ArrayList<>();
38  
39      private final String baseFilename;
40  
41      private final String fileSuffix;
42  
43      private StackTraceElement callerInfo;
44  
45      private Thread cleanupWarning;
46  
47      private boolean warnAboutCleanup = false;
48  
49      public TestFileManager(String baseFilename, String fileSuffix) {
50          this.baseFilename = baseFilename;
51          this.fileSuffix = fileSuffix;
52  
53          initializeCleanupMonitoring();
54      }
55  
56      private void initializeCleanupMonitoring() {
57          callerInfo = new NullPointerException().getStackTrace()[2];
58  
59          Runnable warning = new Runnable() {
60  
61              public void run() {
62                  maybeWarnAboutCleanUp();
63              }
64          };
65  
66          cleanupWarning = new Thread(warning);
67  
68          Runtime.getRuntime().addShutdownHook(cleanupWarning);
69      }
70  
71      private void maybeWarnAboutCleanUp() {
72          if (warnAboutCleanup) {
73              System.out.println("[WARNING] TestFileManager from: " + callerInfo.getClassName() + " not cleaned up!");
74          }
75      }
76  
77      public void markForDeletion(File toDelete) {
78          filesToDelete.add(toDelete);
79          warnAboutCleanup = true;
80      }
81  
82      public synchronized File createTempDir() {
83          try {
84              Thread.sleep(20);
85          } catch (InterruptedException e) {
86              // ignore
87          }
88  
89          File dir = new File(TEMP_DIR_PATH, baseFilename + System.currentTimeMillis());
90  
91          dir.mkdirs();
92          markForDeletion(dir);
93  
94          return dir;
95      }
96  
97      public synchronized File createTempFile() throws IOException {
98          File tempFile = File.createTempFile(baseFilename, fileSuffix);
99          tempFile.deleteOnExit();
100         markForDeletion(tempFile);
101 
102         return tempFile;
103     }
104 
105     public void cleanUp() throws IOException {
106         for (Iterator it = filesToDelete.iterator(); it.hasNext(); ) {
107             File file = (File) it.next();
108 
109             if (file.exists()) {
110                 if (file.isDirectory()) {
111                     FileUtils.deleteDirectory(file);
112                 } else {
113                     file.delete();
114                 }
115             }
116 
117             it.remove();
118         }
119 
120         warnAboutCleanup = false;
121     }
122 
123     public void assertFileExistence(File dir, String filename, boolean shouldExist) {
124         File file = new File(dir, filename);
125 
126         if (shouldExist) {
127             assertTrue(file.exists());
128         } else {
129             assertFalse(file.exists());
130         }
131     }
132 
133     public void assertFileContents(File dir, String filename, String contentsTest, String encoding) throws IOException {
134         assertFileExistence(dir, filename, true);
135 
136         File file = new File(dir, filename);
137 
138         String contents = FileUtils.fileRead(file, encoding);
139 
140         assertEquals(contentsTest, contents);
141     }
142 
143     public File createFile(File dir, String filename, String contents, String encoding) throws IOException {
144         File file = new File(dir, filename);
145 
146         file.getParentFile().mkdirs();
147 
148         FileUtils.fileWrite(file.getPath(), encoding, contents);
149 
150         markForDeletion(file);
151 
152         return file;
153     }
154 
155     public String getFileContents(File file, String encoding) throws IOException {
156         return FileUtils.fileRead(file, encoding);
157     }
158 
159     protected void finalize() throws Throwable {
160         maybeWarnAboutCleanUp();
161 
162         super.finalize();
163     }
164 
165     public File createFile(String filename, String content, String encoding) throws IOException {
166         File dir = createTempDir();
167         return createFile(dir, filename, content, encoding);
168     }
169 }