1 /*
   2  * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 package jdk.testlibrary;
  25 
  26 import java.io.IOException;
  27 import java.nio.file.DirectoryNotEmptyException;
  28 import java.nio.file.FileVisitResult;
  29 import java.nio.file.Files;
  30 import java.nio.file.NoSuchFileException;
  31 import java.nio.file.Path;
  32 import java.nio.file.SimpleFileVisitor;
  33 import java.nio.file.attribute.BasicFileAttributes;
  34 import java.util.ArrayList;
  35 import java.util.List;
  36 
  37 
  38 /**
  39  * Common library for various test file utility functions.
  40  */
  41 public final class FileUtils {
  42 
  43     private static final boolean isWindows =
  44                             System.getProperty("os.name").startsWith("Windows");
  45     private static final int RETRY_DELETE_MILLIS = isWindows ? 500 : 0;
  46     private static final int MAX_RETRY_DELETE_TIMES = isWindows ? 15 : 0;
  47 
  48     /**
  49      * Deletes a file, retrying if necessary.
  50      *
  51      * @param path  the file to delete
  52      *
  53      * @throws NoSuchFileException
  54      *         if the file does not exist (optional specific exception)
  55      * @throws DirectoryNotEmptyException
  56      *         if the file is a directory and could not otherwise be deleted
  57      *         because the directory is not empty (optional specific exception)
  58      * @throws IOException
  59      *         if an I/O error occurs
  60      */
  61     public static void deleteFileWithRetry(Path path)
  62         throws IOException
  63     {
  64         try {
  65             deleteFileWithRetry0(path);
  66         } catch (InterruptedException x) {
  67             throw new IOException("Interrupted while deleting.", x);
  68         }
  69     }
  70 
  71     private static void deleteFileWithRetry0(Path path)
  72         throws IOException, InterruptedException
  73     {
  74         int times = 0;
  75         IOException ioe = null;
  76         while (true) {
  77             try {
  78                 Files.delete(path);
  79                 while (true) {
  80                     if (Files.notExists(path))
  81                         break;
  82                     times++;
  83                     if (times > MAX_RETRY_DELETE_TIMES)
  84                         throw new IOException("File still exists after " + times + " waits.");
  85                     Thread.sleep(RETRY_DELETE_MILLIS);
  86                 }
  87                 break;
  88             } catch (NoSuchFileException | DirectoryNotEmptyException x) {
  89                 throw x;
  90             } catch (IOException x) {
  91                 // Backoff/retry in case another process is accessing the file
  92                 times++;
  93                 if (ioe == null)
  94                     ioe = x;
  95                 else
  96                     ioe.addSuppressed(x);
  97                 if (times > MAX_RETRY_DELETE_TIMES)
  98                     throw ioe;
  99                Thread.sleep(RETRY_DELETE_MILLIS);
 100             }
 101         }
 102     }
 103 
 104     /**
 105      * Deletes a directory and its subdirectories, retrying if necessary.
 106      *
 107      * @param dir  the directory to delete
 108      *
 109      * @throws  IOException
 110      *          If an I/O error occurs. Any such exceptions are caught
 111      *          internally. If only one is caught, then it is re-thrown.
 112      *          If more than one exception is caught, then the second and
 113      *          following exceptions are added as suppressed exceptions of the
 114      *          first one caught, which is then re-thrown.
 115      */
 116     public static void deleteFileTreeWithRetry(Path dir)
 117          throws IOException
 118     {
 119         IOException ioe = null;
 120         final List<IOException> excs = deleteFileTreeUnchecked(dir);
 121         if (!excs.isEmpty()) {
 122             ioe = excs.remove(0);
 123             for (IOException x : excs)
 124                 ioe.addSuppressed(x);
 125         }
 126         if (ioe != null)
 127             throw ioe;
 128     }
 129 
 130     public static List<IOException> deleteFileTreeUnchecked(Path dir) {
 131         final List<IOException> excs = new ArrayList<>();
 132         try {
 133             java.nio.file.Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
 134                 @Override
 135                 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
 136                     try {
 137                         deleteFileWithRetry0(file);
 138                     } catch (IOException x) {
 139                         excs.add(x);
 140                     } catch (InterruptedException x) {
 141                         excs.add(new IOException("Interrupted while deleting.", x));
 142                         return FileVisitResult.TERMINATE;
 143                     }
 144                     return FileVisitResult.CONTINUE;
 145                 }
 146                 @Override
 147                 public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
 148                     try {
 149                         deleteFileWithRetry0(dir);
 150                     } catch (IOException x) {
 151                         excs.add(x);
 152                     } catch (InterruptedException x) {
 153                         excs.add(new IOException("Interrupted while deleting.", x));
 154                         return FileVisitResult.TERMINATE;
 155                     }
 156                     return FileVisitResult.CONTINUE;
 157                 }
 158                 @Override
 159                 public FileVisitResult visitFileFailed(Path file, IOException exc) {
 160                     excs.add(exc);
 161                     return FileVisitResult.CONTINUE;
 162                 }
 163             });
 164         } catch (IOException x) {
 165             excs.add(x);
 166         }
 167         return excs;
 168     }
 169 }
 170