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.util;
020
021import java.io.Closeable;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.nio.ByteBuffer;
026import java.nio.file.Files;
027import java.nio.file.Path;
028import java.nio.file.StandardCopyOption;
029import java.util.concurrent.ThreadLocalRandom;
030import java.util.concurrent.atomic.AtomicBoolean;
031
032import static java.util.Objects.requireNonNull;
033
034/**
035 * A utility class to write files.
036 *
037 * @since 1.9.0
038 */
039public final class FileUtils {
040    // Logic borrowed from Commons-Lang3: we really need only this, to decide do we "atomic move" or not
041    private static final boolean IS_WINDOWS =
042            System.getProperty("os.name", "unknown").startsWith("Windows");
043
044    private FileUtils() {
045        // hide constructor
046    }
047
048    /**
049     * A temporary file, that is removed when closed.
050     */
051    public interface TempFile extends Closeable {
052        /**
053         * Returns the path of the created temp file.
054         */
055        Path getPath();
056    }
057
058    /**
059     * A collocated temporary file, that resides next to a "target" file, and is removed when closed.
060     */
061    public interface CollocatedTempFile extends TempFile {
062        /**
063         * Upon close, atomically moves temp file to target file it is collocated with overwriting target (if exists).
064         * Invocation of this method merely signals that caller ultimately wants temp file to replace the target
065         * file, but when this method returns, the move operation did not yet happen, it will happen when this
066         * instance is closed.
067         * <p>
068         * Invoking this method <em>without writing to temp file</em> {@link #getPath()} (thus, not creating a temp
069         * file to be moved) is considered a bug, a mistake of the caller. Caller of this method should ensure
070         * that this method is invoked ONLY when the temp file is created and moving it to its final place is
071         * required.
072         */
073        void move() throws IOException;
074    }
075
076    /**
077     * Creates a {@link TempFile} instance and backing temporary file on file system. It will be located in the default
078     * temporary-file directory. Returned instance should be handled in try-with-resource construct and created
079     * temp file is removed (if exists) when returned instance is closed.
080     * <p>
081     * This method uses {@link Files#createTempFile(String, String, java.nio.file.attribute.FileAttribute[])} to create
082     * the temporary file on file system.
083     */
084    public static TempFile newTempFile() throws IOException {
085        Path tempFile = Files.createTempFile("resolver", "tmp");
086        return new TempFile() {
087            @Override
088            public Path getPath() {
089                return tempFile;
090            }
091
092            @Override
093            public void close() throws IOException {
094                Files.deleteIfExists(tempFile);
095            }
096        };
097    }
098
099    /**
100     * Creates a {@link CollocatedTempFile} instance for given file without backing file. The path will be located in
101     * same directory where given file is, and will reuse its name for generated (randomized) name. Returned instance
102     * should be handled in try-with-resource and created temp path is removed (if exists) when returned instance is
103     * closed. The {@link CollocatedTempFile#move()} makes possible to atomically replace passed in file with the
104     * processed content written into a file backing the {@link CollocatedTempFile} instance.
105     * <p>
106     * The {@code file} nor it's parent directories have to exist. The parent directories are created if needed.
107     * <p>
108     * This method uses {@link Path#resolve(String)} to create the temporary file path in passed in file parent
109     * directory, but it does NOT create backing file on file system.
110     */
111    public static CollocatedTempFile newTempFile(Path file) throws IOException {
112        Path parent = requireNonNull(file.getParent(), "file must have parent");
113        Files.createDirectories(parent);
114        Path tempFile = parent.resolve(file.getFileName() + "."
115                + Long.toUnsignedString(ThreadLocalRandom.current().nextLong()) + ".tmp");
116        return new CollocatedTempFile() {
117            private final AtomicBoolean wantsMove = new AtomicBoolean(false);
118
119            @Override
120            public Path getPath() {
121                return tempFile;
122            }
123
124            @Override
125            public void move() {
126                wantsMove.set(true);
127            }
128
129            @Override
130            public void close() throws IOException {
131                if (wantsMove.get()) {
132                    if (IS_WINDOWS) {
133                        copy(tempFile, file);
134                    } else {
135                        Files.move(tempFile, file, StandardCopyOption.ATOMIC_MOVE);
136                    }
137                }
138                Files.deleteIfExists(tempFile);
139            }
140        };
141    }
142
143    /**
144     * On Windows we use pre-NIO2 way to copy files, as for some reason it works. Beat me why.
145     */
146    private static void copy(Path source, Path target) throws IOException {
147        ByteBuffer buffer = ByteBuffer.allocate(1024 * 32);
148        byte[] array = buffer.array();
149        try (InputStream is = Files.newInputStream(source);
150                OutputStream os = Files.newOutputStream(target)) {
151            while (true) {
152                int bytes = is.read(array);
153                if (bytes < 0) {
154                    break;
155                }
156                os.write(array, 0, bytes);
157            }
158        }
159    }
160
161    /**
162     * A file writer, that accepts a {@link Path} to write some content to. Note: the file denoted by path may exist,
163     * hence implementation have to ensure it is able to achieve its goal ("replace existing" option or equivalent
164     * should be used).
165     */
166    @FunctionalInterface
167    public interface FileWriter {
168        void write(Path path) throws IOException;
169    }
170
171    /**
172     * Writes file without backup.
173     *
174     * @param target that is the target file (must be file, the path must have parent).
175     * @param writer the writer that will accept a {@link Path} to write content to.
176     * @throws IOException if at any step IO problem occurs.
177     */
178    public static void writeFile(Path target, FileWriter writer) throws IOException {
179        writeFile(target, writer, false);
180    }
181
182    /**
183     * Writes file with backup copy (appends ".bak" extension).
184     *
185     * @param target that is the target file (must be file, the path must have parent).
186     * @param writer the writer that will accept a {@link Path} to write content to.
187     * @throws IOException if at any step IO problem occurs.
188     */
189    public static void writeFileWithBackup(Path target, FileWriter writer) throws IOException {
190        writeFile(target, writer, true);
191    }
192
193    /**
194     * Utility method to write out file to disk in "atomic" manner, with optional backups (".bak") if needed. This
195     * ensures that no other thread or process will be able to read not fully written files. Finally, this methos
196     * may create the needed parent directories, if the passed in target parents does not exist.
197     *
198     * @param target   that is the target file (must be an existing or non-existing file, the path must have parent).
199     * @param writer   the writer that will accept a {@link Path} to write content to.
200     * @param doBackup if {@code true}, and target file is about to be overwritten, a ".bak" file with old contents will
201     *                 be created/overwritten.
202     * @throws IOException if at any step IO problem occurs.
203     */
204    private static void writeFile(Path target, FileWriter writer, boolean doBackup) throws IOException {
205        requireNonNull(target, "target is null");
206        requireNonNull(writer, "writer is null");
207        Path parent = requireNonNull(target.getParent(), "target must have parent");
208
209        try (CollocatedTempFile tempFile = newTempFile(target)) {
210            writer.write(tempFile.getPath());
211            if (doBackup && Files.isRegularFile(target)) {
212                Files.copy(target, parent.resolve(target.getFileName() + ".bak"), StandardCopyOption.REPLACE_EXISTING);
213            }
214            tempFile.move();
215        }
216    }
217}