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.eclipse.aether.internal.test.util;
20  
21  import java.io.BufferedOutputStream;
22  import java.io.File;
23  import java.io.FileInputStream;
24  import java.io.FileOutputStream;
25  import java.io.IOException;
26  import java.io.OutputStream;
27  import java.io.RandomAccessFile;
28  import java.nio.charset.StandardCharsets;
29  import java.nio.file.Files;
30  import java.util.ArrayList;
31  import java.util.Collection;
32  import java.util.Properties;
33  import java.util.UUID;
34  
35  /**
36   * Provides utility methods to read and write (temporary) files.
37   */
38  public class TestFileUtils {
39  
40      private static final File TMP = new File(
41              System.getProperty("java.io.tmpdir"),
42              "aether-" + UUID.randomUUID().toString().substring(0, 8));
43  
44      static {
45          Runtime.getRuntime().addShutdownHook(new Thread(() -> {
46              try {
47                  deleteFile(TMP);
48              } catch (IOException e) {
49                  e.printStackTrace();
50              }
51          }));
52      }
53  
54      private TestFileUtils() {
55          // hide constructor
56      }
57  
58      /**
59       * Deletes the files created by the temp-file helpers of this class.
60       *
61       * @throws IOException if an I/O error occurs
62       * @deprecated use the JUnit 5 {@code @TempDir} extension instead, which cleans up after
63       * itself
64       */
65      @Deprecated
66      public static void deleteTempFiles() throws IOException {
67          deleteFile(TMP);
68      }
69  
70      public static void deleteFile(File file) throws IOException {
71          if (file == null) {
72              return;
73          }
74  
75          Collection<File> undeletables = new ArrayList<>();
76  
77          delete(file, undeletables);
78  
79          if (!undeletables.isEmpty()) {
80              throw new IOException("Failed to delete " + undeletables);
81          }
82      }
83  
84      private static void delete(File file, Collection<File> undeletables) {
85          String[] children = file.list();
86          if (children != null) {
87              for (String child : children) {
88                  delete(new File(file, child), undeletables);
89              }
90          }
91  
92          if (!del(file)) {
93              undeletables.add(file.getAbsoluteFile());
94          }
95      }
96  
97      private static boolean del(File file) {
98          for (int i = 0; i < 10; i++) {
99              if (file.delete() || !file.exists()) {
100                 return true;
101             }
102         }
103         return false;
104     }
105 
106     /**
107      * Creates a directory and its missing parents.
108      *
109      * @param directory the directory to create
110      * @return {@code true} if the directory exists afterwards
111      * @deprecated use {@code Files.createDirectories(Path)} instead
112      */
113     @Deprecated
114     public static boolean mkdirs(File directory) {
115         if (directory == null) {
116             return false;
117         }
118 
119         if (directory.exists()) {
120             return false;
121         }
122         if (directory.mkdir()) {
123             return true;
124         }
125 
126         File canonDir = null;
127         try {
128             canonDir = directory.getCanonicalFile();
129         } catch (IOException e) {
130             return false;
131         }
132 
133         File parentDir = canonDir.getParentFile();
134         return (parentDir != null && (mkdirs(parentDir) || parentDir.exists()) && canonDir.mkdir());
135     }
136 
137     /**
138      * Creates a temporary file with the given UTF-8 content.
139      *
140      * @param contents the content to write
141      * @return the temporary file
142      * @throws IOException if an I/O error occurs
143      * @deprecated use the JUnit 5 {@code @TempDir} extension instead
144      */
145     @Deprecated
146     public static File createTempFile(String contents) throws IOException {
147         return createTempFile(contents.getBytes(StandardCharsets.UTF_8), 1);
148     }
149 
150     /**
151      * Creates a temporary file holding the byte pattern the given number of times.
152      *
153      * @param pattern the bytes to repeat
154      * @param repeat how many times the pattern is written
155      * @return the temporary file
156      * @throws IOException if an I/O error occurs
157      * @deprecated use the JUnit 5 {@code @TempDir} extension instead
158      */
159     @Deprecated
160     public static File createTempFile(byte[] pattern, int repeat) throws IOException {
161         mkdirs(TMP);
162         File tmpFile = File.createTempFile("tmpfile-", ".data", TMP);
163         writeBytes(tmpFile, pattern, repeat);
164         return tmpFile;
165     }
166 
167     /**
168      * Creates a temporary directory.
169      *
170      * @return the temporary directory
171      * @throws IOException if an I/O error occurs
172      * @deprecated use the JUnit 5 {@code @TempDir} extension instead
173      */
174     @Deprecated
175     public static File createTempDir() throws IOException {
176         return createTempDir("");
177     }
178 
179     /**
180      * Creates a temporary directory.
181      *
182      * @return the temporary directory
183      * @throws IOException if an I/O error occurs
184      * @deprecated use the JUnit 5 {@code @TempDir} extension instead
185      */
186     @Deprecated
187     public static File createTempDir(String suffix) throws IOException {
188         mkdirs(TMP);
189         File tmpFile = File.createTempFile("tmpdir-", suffix, TMP);
190         deleteFile(tmpFile);
191         mkdirs(tmpFile);
192         return tmpFile;
193     }
194 
195     public static long copyFile(File source, File target) throws IOException {
196         long total = 0;
197 
198         mkdirs(target.getParentFile());
199 
200         try (FileInputStream fis = new FileInputStream(source);
201                 OutputStream fos = new BufferedOutputStream(new FileOutputStream(target))) {
202             for (byte[] buffer = new byte[1024 * 32]; ; ) {
203                 int bytes = fis.read(buffer);
204                 if (bytes < 0) {
205                     break;
206                 }
207 
208                 fos.write(buffer, 0, bytes);
209 
210                 total += bytes;
211             }
212         }
213 
214         return total;
215     }
216 
217     /**
218      * Reads the contents of a file into a byte array.
219      *
220      * @param file the file to read
221      * @return the contents of the file as a byte array
222      * @throws IOException if an I/O error occurs
223      * @deprecated use {@code Files.readAllBytes(Path)} instead
224      */
225     @Deprecated
226     public static byte[] readBytes(File file) throws IOException {
227         try (RandomAccessFile in = new RandomAccessFile(file, "r")) {
228             byte[] actual = new byte[(int) in.length()];
229             in.readFully(actual);
230             return actual;
231         }
232     }
233 
234     /**
235      * Writes a byte pattern to a file the given number of times.
236      *
237      * @param file the file to write
238      * @param pattern the bytes to repeat
239      * @param repeat how many times the pattern is written
240      * @throws IOException if an I/O error occurs
241      * @deprecated use {@code Files.write(Path, byte[])} instead; it writes the array once, so for
242      * {@code repeat > 1} build the repeated bytes first
243      */
244     @Deprecated
245     public static void writeBytes(File file, byte[] pattern, int repeat) throws IOException {
246         file.deleteOnExit();
247         file.getParentFile().mkdirs();
248         try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
249             for (int i = 0; i < repeat; i++) {
250                 out.write(pattern);
251             }
252         }
253     }
254 
255     public static String readString(File file) throws IOException {
256         byte[] content = Files.readAllBytes(file.toPath());
257         return new String(content, StandardCharsets.UTF_8);
258     }
259 
260     /**
261      * Writes a UTF-8 string to a file.
262      *
263      * @param file the file to write
264      * @param content the content to write
265      * @throws IOException if an I/O error occurs
266      * @deprecated use {@code Files.write(Path, byte[])} instead
267      */
268     @Deprecated
269     public static void writeString(File file, String content) throws IOException {
270         writeBytes(file, content.getBytes(StandardCharsets.UTF_8), 1);
271     }
272 
273     /**
274      * Writes a UTF-8 string to a file and sets its last-modified time.
275      *
276      * @param file the file to write
277      * @param content the content to write
278      * @param timestamp the last-modified time to set, in milliseconds since the epoch
279      * @throws IOException if an I/O error occurs
280      * @deprecated use {@code Files.write(Path, byte[])} and {@code Files.setLastModifiedTime(Path, FileTime)} instead
281      */
282     @Deprecated
283     public static void writeString(File file, String content, long timestamp) throws IOException {
284         writeBytes(file, content.getBytes(StandardCharsets.UTF_8), 1);
285         file.setLastModified(timestamp);
286     }
287 
288     public static void readProps(File file, Properties props) throws IOException {
289         try (FileInputStream fis = new FileInputStream(file)) {
290             props.load(fis);
291         }
292     }
293 
294     public static void writeProps(File file, Properties props) throws IOException {
295         file.getParentFile().mkdirs();
296 
297         try (FileOutputStream fos = new FileOutputStream(file)) {
298             props.store(fos, "aether-test");
299         }
300     }
301 }