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      @Deprecated
59      public static void deleteTempFiles() throws IOException {
60          deleteFile(TMP);
61      }
62  
63      public static void deleteFile(File file) throws IOException {
64          if (file == null) {
65              return;
66          }
67  
68          Collection<File> undeletables = new ArrayList<>();
69  
70          delete(file, undeletables);
71  
72          if (!undeletables.isEmpty()) {
73              throw new IOException("Failed to delete " + undeletables);
74          }
75      }
76  
77      private static void delete(File file, Collection<File> undeletables) {
78          String[] children = file.list();
79          if (children != null) {
80              for (String child : children) {
81                  delete(new File(file, child), undeletables);
82              }
83          }
84  
85          if (!del(file)) {
86              undeletables.add(file.getAbsoluteFile());
87          }
88      }
89  
90      private static boolean del(File file) {
91          for (int i = 0; i < 10; i++) {
92              if (file.delete() || !file.exists()) {
93                  return true;
94              }
95          }
96          return false;
97      }
98  
99      @Deprecated
100     public static boolean mkdirs(File directory) {
101         if (directory == null) {
102             return false;
103         }
104 
105         if (directory.exists()) {
106             return false;
107         }
108         if (directory.mkdir()) {
109             return true;
110         }
111 
112         File canonDir = null;
113         try {
114             canonDir = directory.getCanonicalFile();
115         } catch (IOException e) {
116             return false;
117         }
118 
119         File parentDir = canonDir.getParentFile();
120         return (parentDir != null && (mkdirs(parentDir) || parentDir.exists()) && canonDir.mkdir());
121     }
122 
123     /**
124      * @throws IOException if an I/O error occurs
125      * @deprecated use @TempDir (JUnit 5) Or TemporaryFolder (JUnit 4) instead
126      */
127     @Deprecated
128     public static File createTempFile(String contents) throws IOException {
129         return createTempFile(contents.getBytes(StandardCharsets.UTF_8), 1);
130     }
131 
132     @Deprecated
133     /**
134      * @throws IOException if an I/O error occurs
135      * @deprecated use @TempDir (JUnit 5) Or TemporaryFolder (JUnit 4) instead
136      */
137     public static File createTempFile(byte[] pattern, int repeat) throws IOException {
138         mkdirs(TMP);
139         File tmpFile = File.createTempFile("tmpfile-", ".data", TMP);
140         writeBytes(tmpFile, pattern, repeat);
141         return tmpFile;
142     }
143 
144     /**
145      * Creates a temporary directory.
146      *
147      * @return the temporary directory
148      * @throws IOException if an I/O error occurs
149      * @deprecated use @TempDir (JUnit 5) Or TemporaryFolder (JUnit 4) instead
150      */
151     @Deprecated
152     public static File createTempDir() throws IOException {
153         return createTempDir("");
154     }
155 
156     /**
157      * Creates a temporary directory.
158      *
159      * @return the temporary directory
160      * @throws IOException if an I/O error occurs
161      * @deprecated use {@code @TempDir} (JUnit 5) or {@code TemporaryFolder} (JUnit 4) instead
162      */
163     @Deprecated
164     public static File createTempDir(String suffix) throws IOException {
165         mkdirs(TMP);
166         File tmpFile = File.createTempFile("tmpdir-", suffix, TMP);
167         deleteFile(tmpFile);
168         mkdirs(tmpFile);
169         return tmpFile;
170     }
171 
172     public static long copyFile(File source, File target) throws IOException {
173         long total = 0;
174 
175         mkdirs(target.getParentFile());
176 
177         try (FileInputStream fis = new FileInputStream(source);
178                 OutputStream fos = new BufferedOutputStream(new FileOutputStream(target))) {
179             for (byte[] buffer = new byte[1024 * 32]; ; ) {
180                 int bytes = fis.read(buffer);
181                 if (bytes < 0) {
182                     break;
183                 }
184 
185                 fos.write(buffer, 0, bytes);
186 
187                 total += bytes;
188             }
189         }
190 
191         return total;
192     }
193 
194     /**
195      * Reads the contents of a file into a byte array.
196      *
197      * @param file the file to read
198      * @return the contents of the file as a byte array
199      * @throws IOException if an I/O error occurs
200      * @deprecated use {@code Files.readAllBytes(Path)} instead
201      */
202     @Deprecated
203     public static byte[] readBytes(File file) throws IOException {
204         try (RandomAccessFile in = new RandomAccessFile(file, "r")) {
205             byte[] actual = new byte[(int) in.length()];
206             in.readFully(actual);
207             return actual;
208         }
209     }
210 
211     @Deprecated
212     public static void writeBytes(File file, byte[] pattern, int repeat) throws IOException {
213         file.deleteOnExit();
214         file.getParentFile().mkdirs();
215         try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
216             for (int i = 0; i < repeat; i++) {
217                 out.write(pattern);
218             }
219         }
220     }
221 
222     public static String readString(File file) throws IOException {
223         byte[] content = Files.readAllBytes(file.toPath());
224         return new String(content, StandardCharsets.UTF_8);
225     }
226 
227     @Deprecated
228     public static void writeString(File file, String content) throws IOException {
229         writeBytes(file, content.getBytes(StandardCharsets.UTF_8), 1);
230     }
231 
232     @Deprecated
233     public static void writeString(File file, String content, long timestamp) throws IOException {
234         writeBytes(file, content.getBytes(StandardCharsets.UTF_8), 1);
235         file.setLastModified(timestamp);
236     }
237 
238     public static void readProps(File file, Properties props) throws IOException {
239         try (FileInputStream fis = new FileInputStream(file)) {
240             props.load(fis);
241         }
242     }
243 
244     public static void writeProps(File file, Properties props) throws IOException {
245         file.getParentFile().mkdirs();
246 
247         try (FileOutputStream fos = new FileOutputStream(file)) {
248             props.store(fos, "aether-test");
249         }
250     }
251 }