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  import org.junit.Assert;
29  
30  public class TestFileManager {
31  
32      public static final String TEMP_DIR_PATH = System.getProperty("java.io.tmpdir");
33  
34      private List<File> filesToDelete = new ArrayList<>();
35  
36      private final String baseFilename;
37  
38      private final String fileSuffix;
39  
40      private StackTraceElement callerInfo;
41  
42      private Thread cleanupWarning;
43  
44      private boolean warnAboutCleanup = false;
45  
46      public TestFileManager(String baseFilename, String fileSuffix) {
47          this.baseFilename = baseFilename;
48          this.fileSuffix = fileSuffix;
49  
50          initializeCleanupMonitoring();
51      }
52  
53      private void initializeCleanupMonitoring() {
54          callerInfo = new NullPointerException().getStackTrace()[2];
55  
56          Runnable warning = new Runnable() {
57  
58              public void run() {
59                  maybeWarnAboutCleanUp();
60              }
61          };
62  
63          cleanupWarning = new Thread(warning);
64  
65          Runtime.getRuntime().addShutdownHook(cleanupWarning);
66      }
67  
68      private void maybeWarnAboutCleanUp() {
69          if (warnAboutCleanup) {
70              System.out.println("[WARNING] TestFileManager from: " + callerInfo.getClassName() + " not cleaned up!");
71          }
72      }
73  
74      public void markForDeletion(File toDelete) {
75          filesToDelete.add(toDelete);
76          warnAboutCleanup = true;
77      }
78  
79      public synchronized File createTempDir() {
80          try {
81              Thread.sleep(20);
82          } catch (InterruptedException e) {
83              // ignore
84          }
85  
86          File dir = new File(TEMP_DIR_PATH, baseFilename + System.currentTimeMillis());
87  
88          dir.mkdirs();
89          markForDeletion(dir);
90  
91          return dir;
92      }
93  
94      public synchronized File createTempFile() throws IOException {
95          File tempFile = File.createTempFile(baseFilename, fileSuffix);
96          tempFile.deleteOnExit();
97          markForDeletion(tempFile);
98  
99          return tempFile;
100     }
101 
102     public void cleanUp() throws IOException {
103         for (Iterator it = filesToDelete.iterator(); it.hasNext(); ) {
104             File file = (File) it.next();
105 
106             if (file.exists()) {
107                 if (file.isDirectory()) {
108                     FileUtils.deleteDirectory(file);
109                 } else {
110                     file.delete();
111                 }
112             }
113 
114             it.remove();
115         }
116 
117         warnAboutCleanup = false;
118     }
119 
120     public void assertFileExistence(File dir, String filename, boolean shouldExist) {
121         File file = new File(dir, filename);
122 
123         if (shouldExist) {
124             Assert.assertTrue(file.exists());
125         } else {
126             Assert.assertFalse(file.exists());
127         }
128     }
129 
130     public void assertFileContents(File dir, String filename, String contentsTest, String encoding) throws IOException {
131         assertFileExistence(dir, filename, true);
132 
133         File file = new File(dir, filename);
134 
135         String contents = FileUtils.fileRead(file, encoding);
136 
137         Assert.assertEquals(contentsTest, contents);
138     }
139 
140     public File createFile(File dir, String filename, String contents, String encoding) throws IOException {
141         File file = new File(dir, filename);
142 
143         file.getParentFile().mkdirs();
144 
145         FileUtils.fileWrite(file.getPath(), encoding, contents);
146 
147         markForDeletion(file);
148 
149         return file;
150     }
151 
152     public String getFileContents(File file, String encoding) throws IOException {
153         return FileUtils.fileRead(file, encoding);
154     }
155 
156     protected void finalize() throws Throwable {
157         maybeWarnAboutCleanUp();
158 
159         super.finalize();
160     }
161 
162     public File createFile(String filename, String content, String encoding) throws IOException {
163         File dir = createTempDir();
164         return createFile(dir, filename, content, encoding);
165     }
166 }