View Javadoc

1   package org.apache.maven.plugin.assembly.testutils;
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 org.codehaus.plexus.util.FileUtils;
23  import org.codehaus.plexus.util.IOUtil;
24  
25  import java.io.File;
26  import java.io.FileReader;
27  import java.io.FileWriter;
28  import java.io.IOException;
29  import java.util.ArrayList;
30  import java.util.Iterator;
31  import java.util.List;
32  
33  import junit.framework.Assert;
34  
35  public class TestFileManager
36  {
37  
38      public static final String TEMP_DIR_PATH = System.getProperty( "java.io.tmpdir" );
39  
40      private final List<File> filesToDelete = new ArrayList<File>();
41  
42      private final String baseFilename;
43  
44      private final String fileSuffix;
45  
46      private StackTraceElement callerInfo;
47  
48      private Thread cleanupWarning;
49  
50      private boolean warnAboutCleanup = false;
51  
52      public TestFileManager( final String baseFilename, final String fileSuffix )
53      {
54          this.baseFilename = baseFilename;
55          this.fileSuffix = fileSuffix;
56  
57          initializeCleanupMonitoring();
58      }
59  
60      private void initializeCleanupMonitoring()
61      {
62          callerInfo = new NullPointerException().getStackTrace()[2];
63  
64          final Runnable warning = new Runnable()
65          {
66  
67              public void run()
68              {
69                  maybeWarnAboutCleanUp();
70              }
71  
72          };
73  
74          cleanupWarning = new Thread( warning );
75  
76          Runtime.getRuntime()
77                 .addShutdownHook( cleanupWarning );
78      }
79  
80      private void maybeWarnAboutCleanUp()
81      {
82          if ( warnAboutCleanup )
83          {
84              System.out.println( "[WARNING] TestFileManager from: " + callerInfo.getClassName() + " not cleaned up!" );
85          }
86      }
87  
88      public void markForDeletion( final File toDelete )
89      {
90          filesToDelete.add( toDelete );
91          warnAboutCleanup = true;
92      }
93  
94      public synchronized File createTempDir()
95      {
96          try
97          {
98              Thread.sleep( 20 );
99          }
100         catch ( final InterruptedException e )
101         {
102         }
103 
104         final File dir = new File( TEMP_DIR_PATH, baseFilename + System.currentTimeMillis() );
105 
106         dir.mkdirs();
107         markForDeletion( dir );
108 
109         return dir;
110     }
111 
112     public synchronized File createTempFile() throws IOException
113     {
114         final File tempFile = File.createTempFile( baseFilename, fileSuffix );
115         tempFile.deleteOnExit();
116         markForDeletion( tempFile );
117 
118         return tempFile;
119     }
120 
121     public void cleanUp()
122     {
123         for ( final Iterator<File> it = filesToDelete.iterator(); it.hasNext(); )
124         {
125             final File file = it.next();
126 
127             if ( file.exists() )
128             {
129                 try
130                 {
131                     FileUtils.forceDelete( file );
132                 }
133                 catch ( final Exception e )
134                 {
135                     System.err.println( "Error while deleting test file/dir: " + file + "; ignoring." );
136                 }
137             }
138 
139             it.remove();
140         }
141 
142         warnAboutCleanup = false;
143     }
144 
145     public void assertFileExistence( final File dir, final String filename, final boolean shouldExist )
146     {
147         final File file = new File( dir, filename );
148 
149         if ( shouldExist )
150         {
151             Assert.assertTrue( file.exists() );
152         }
153         else
154         {
155             Assert.assertFalse( file.exists() );
156         }
157     }
158 
159     public void assertFileContents( final File dir, final String filename, final String contentsTest )
160         throws IOException
161     {
162         assertFileExistence( dir, filename, true );
163 
164         final File file = new File( dir, filename );
165 
166         Assert.assertEquals( contentsTest, getFileContents( file ) );
167     }
168 
169     /**
170      * NOTE: the file content is written using platform encoding.
171      */
172     public File createFile( final File dir, final String filename, final String contents ) throws IOException
173     {
174         final File file = new File( dir, filename );
175 
176         file.getParentFile()
177             .mkdirs();
178 
179         FileWriter writer = null;
180 
181         try
182         {
183             writer = new FileWriter( file ); // platform encoding
184 
185             writer.write( contents );
186         }
187         finally
188         {
189             IOUtil.close( writer );
190         }
191 
192         markForDeletion( file );
193 
194         return file;
195     }
196 
197     /**
198      * NOTE: the file content is read using platform encoding.
199      */
200     public String getFileContents( final File file ) throws IOException
201     {
202         String result = null;
203 
204         FileReader reader = null;
205         try
206         {
207             reader = new FileReader( file ); // platform encoding
208 
209             result = IOUtil.toString( reader );
210         }
211         finally
212         {
213             IOUtil.close( reader );
214         }
215 
216         return result;
217     }
218 
219     @Override
220     protected void finalize() throws Throwable
221     {
222         maybeWarnAboutCleanUp();
223 
224         super.finalize();
225     }
226 
227     public File createFile( final String filename, final String content ) throws IOException
228     {
229         final File dir = createTempDir();
230         return createFile( dir, filename, content );
231     }
232 
233 }