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