001/*-------------------------------------------------------------------------+
002|                                                                          |
003| Copyright 2005-2011 the ConQAT Project                                   |
004|                                                                          |
005| Licensed under the Apache License, Version 2.0 (the "License");          |
006| you may not use this file except in compliance with the License.         |
007| You may obtain a copy of the License at                                  |
008|                                                                          |
009|    http://www.apache.org/licenses/LICENSE-2.0                            |
010|                                                                          |
011| Unless required by applicable law or agreed to in writing, software      |
012| distributed under the License is distributed on an "AS IS" BASIS,        |
013| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
014| See the License for the specific language governing permissions and      |
015| limitations under the License.                                           |
016+-------------------------------------------------------------------------*/
017package org.conqat.lib.commons.io;
018
019import java.io.File;
020import java.io.IOException;
021import java.nio.file.Files;
022
023import org.conqat.lib.commons.filesystem.FileSystemUtils;
024
025/**
026 * {@link AutoCloseable} wrapper around
027 * {@link Files#createTempDirectory(String, java.nio.file.attribute.FileAttribute...)}
028 * that deletes the temp directory when closed.
029 */
030public class SelfDeletingTempDirectory implements AutoCloseable {
031
032        /**
033         * The temp directory.
034         */
035        private final File directory;
036
037        /** @see #directory */
038        public File getDirectory() {
039                return directory;
040        }
041
042        /**
043         * Creates a new temp directory using the given prefix to determine its
044         * name.
045         */
046        public SelfDeletingTempDirectory(String prefix) throws IOException {
047                directory = Files.createTempDirectory(prefix).toFile();
048        }
049
050        /**
051         * Recursively deletes the temp directory. In case that fails (e.g. if some
052         * files are still being used), registers the directory for deletion on JVM
053         * shutdown.
054         */
055        @Override
056        public void close() {
057                FileSystemUtils.deleteRecursively(directory);
058                if (directory.exists()) {
059                        Runtime.getRuntime().addShutdownHook(new Thread(() -> FileSystemUtils.deleteRecursively(directory)));
060                }
061        }
062}