View Javadoc

1   package org.apache.maven.shared.tools.easymock;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.File;
23  import java.io.FileReader;
24  import java.io.FileWriter;
25  import java.io.IOException;
26  import java.io.StringReader;
27  import java.io.StringWriter;
28  import java.util.ArrayList;
29  import java.util.Iterator;
30  import java.util.List;
31  
32  import junit.framework.Assert;
33  
34  import org.codehaus.plexus.util.FileUtils;
35  import org.codehaus.plexus.util.IOUtil;
36  
37  /**
38   * @version $Id$
39   */
40  public class TestFileManager
41  {
42      /** Temp dir from "java.io.tmpdir" property */
43      public static final String TEMP_DIR_PATH = System.getProperty( "java.io.tmpdir" );
44  
45      private List<File> filesToDelete = new ArrayList<File>();
46  
47      private final String baseFilename;
48  
49      private final String fileSuffix;
50  
51      private StackTraceElement callerInfo;
52  
53      private Thread cleanupWarning;
54  
55      private boolean warnAboutCleanup = false;
56  
57      /**
58       * Default constructor
59       *
60       * @param baseFilename
61       * @param fileSuffix
62       */
63      public TestFileManager( String baseFilename, String fileSuffix )
64      {
65          this.baseFilename = baseFilename;
66          this.fileSuffix = fileSuffix;
67  
68          initializeCleanupMonitoring();
69      }
70  
71      private void initializeCleanupMonitoring()
72      {
73          callerInfo = new NullPointerException().getStackTrace()[2];
74  
75          Runnable warning = new Runnable()
76          {
77              /** {@inheritDoc} */
78              public void run()
79              {
80                  maybeWarnAboutCleanUp();
81              }
82  
83          };
84  
85          cleanupWarning = new Thread( warning );
86  
87          Runtime.getRuntime().addShutdownHook( cleanupWarning );
88      }
89  
90      protected void maybeWarnAboutCleanUp()
91      {
92          if ( warnAboutCleanup )
93          {
94              System.out.println( "[WARNING] TestFileManager from: " + callerInfo.getClassName() + " not cleaned up!" );
95          }
96      }
97  
98      /**
99       * @param toDelete
100      */
101     public void markForDeletion( File toDelete )
102     {
103         filesToDelete.add( toDelete );
104         warnAboutCleanup = true;
105     }
106 
107     /**
108      * @return a temp dir
109      */
110     public synchronized File createTempDir()
111     {
112         try
113         {
114             Thread.sleep( 20 );
115         }
116         catch ( InterruptedException e )
117         {
118             // ignored
119         }
120 
121         File dir = new File( TEMP_DIR_PATH, baseFilename + System.currentTimeMillis() );
122 
123         dir.mkdirs();
124         markForDeletion( dir );
125 
126         return dir;
127     }
128 
129     /**
130      * @return a temp file
131      * @throws IOException if any
132      * @todo maybe use {@link FileUtils#createTempFile(String, String, File)}
133      */
134     public synchronized File createTempFile()
135         throws IOException
136     {
137         File tempFile = File.createTempFile( baseFilename, fileSuffix );
138         tempFile.deleteOnExit();
139         markForDeletion( tempFile );
140 
141         return tempFile;
142     }
143 
144     /**
145      * @throws IOException if any
146      */
147     public void cleanUp()
148         throws IOException
149     {
150         for ( Iterator<File> it = filesToDelete.iterator(); it.hasNext(); )
151         {
152             File file = it.next();
153 
154             if ( file.exists() )
155             {
156                 if ( file.isDirectory() )
157                 {
158                     FileUtils.deleteDirectory( file );
159                 }
160                 else
161                 {
162                     file.delete();
163                 }
164             }
165 
166             it.remove();
167         }
168 
169         warnAboutCleanup = false;
170     }
171 
172     /**
173      * @param dir
174      * @param filename
175      * @param shouldExist
176      */
177     public void assertFileExistence( File dir, String filename, boolean shouldExist )
178     {
179         File file = new File( dir, filename );
180 
181         if ( shouldExist )
182         {
183             Assert.assertTrue( file.exists() );
184         }
185         else
186         {
187             Assert.assertFalse( file.exists() );
188         }
189     }
190 
191     /**
192      * @param dir
193      * @param filename
194      * @param contentsTest
195      * @throws IOException if any
196      */
197     public void assertFileContents( File dir, String filename, String contentsTest )
198         throws IOException
199     {
200         assertFileExistence( dir, filename, true );
201 
202         File file = new File( dir, filename );
203 
204         FileReader reader = null;
205         StringWriter writer = new StringWriter();
206 
207         try
208         {
209             reader = new FileReader( file );
210 
211             IOUtil.copy( reader, writer );
212         }
213         finally
214         {
215             IOUtil.close( reader );
216         }
217 
218         Assert.assertEquals( contentsTest, writer.toString() );
219     }
220 
221     /**
222      * @param dir
223      * @param filename
224      * @param contents
225      * @return
226      * @throws IOException if any
227      */
228     public File createFile( File dir, String filename, String contents )
229         throws IOException
230     {
231         File file = new File( dir, filename );
232 
233         file.getParentFile().mkdirs();
234 
235         FileWriter writer = null;
236 
237         try
238         {
239             writer = new FileWriter( file );
240 
241             IOUtil.copy( new StringReader( contents ), writer );
242         }
243         finally
244         {
245             IOUtil.close( writer );
246         }
247 
248         markForDeletion( file );
249 
250         return file;
251     }
252 
253     /**
254      * @param file
255      * @return
256      * @throws IOException if any
257      */
258     public String getFileContents( File file )
259         throws IOException
260     {
261         String result = null;
262 
263         FileReader reader = null;
264         try
265         {
266             reader = new FileReader( file );
267 
268             StringWriter writer = new StringWriter();
269 
270             IOUtil.copy( reader, writer );
271 
272             result = writer.toString();
273         }
274         finally
275         {
276             IOUtil.close( reader );
277         }
278 
279         return result;
280     }
281 
282     /** {@inheritDoc} */
283     protected void finalize()
284         throws Throwable
285     {
286         maybeWarnAboutCleanUp();
287 
288         super.finalize();
289     }
290 
291     /**
292      * @param filename
293      * @param content
294      * @return
295      * @throws IOException if any
296      */
297     public File createFile( String filename, String content )
298         throws IOException
299     {
300         File dir = createTempDir();
301         return createFile( dir, filename, content );
302     }
303 }