001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether.internal.test.util;
020
021import java.io.BufferedOutputStream;
022import java.io.File;
023import java.io.FileInputStream;
024import java.io.FileOutputStream;
025import java.io.IOException;
026import java.io.OutputStream;
027import java.io.RandomAccessFile;
028import java.nio.charset.StandardCharsets;
029import java.nio.file.Files;
030import java.util.ArrayList;
031import java.util.Collection;
032import java.util.Properties;
033import java.util.UUID;
034
035/**
036 * Provides utility methods to read and write (temporary) files.
037 */
038public class TestFileUtils {
039
040    private static final File TMP = new File(
041            System.getProperty("java.io.tmpdir"),
042            "aether-" + UUID.randomUUID().toString().substring(0, 8));
043
044    static {
045        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
046            try {
047                deleteFile(TMP);
048            } catch (IOException e) {
049                e.printStackTrace();
050            }
051        }));
052    }
053
054    private TestFileUtils() {
055        // hide constructor
056    }
057
058    /**
059     * Deletes the files created by the temp-file helpers of this class.
060     *
061     * @throws IOException if an I/O error occurs
062     * @deprecated use the JUnit 5 {@code @TempDir} extension instead, which cleans up after
063     * itself
064     */
065    @Deprecated
066    public static void deleteTempFiles() throws IOException {
067        deleteFile(TMP);
068    }
069
070    public static void deleteFile(File file) throws IOException {
071        if (file == null) {
072            return;
073        }
074
075        Collection<File> undeletables = new ArrayList<>();
076
077        delete(file, undeletables);
078
079        if (!undeletables.isEmpty()) {
080            throw new IOException("Failed to delete " + undeletables);
081        }
082    }
083
084    private static void delete(File file, Collection<File> undeletables) {
085        String[] children = file.list();
086        if (children != null) {
087            for (String child : children) {
088                delete(new File(file, child), undeletables);
089            }
090        }
091
092        if (!del(file)) {
093            undeletables.add(file.getAbsoluteFile());
094        }
095    }
096
097    private static boolean del(File file) {
098        for (int i = 0; i < 10; i++) {
099            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}