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 (Files.exists(path)) {
  80                     times++;
  81                     if (times > MAX_RETRY_DELETE_TIMES)
  82                         throw new IOException("File still exists after " + times + " waits.");
  83                     Thread.sleep(RETRY_DELETE_MILLIS);
  84                 }
  85                 break;
  86             } catch (NoSuchFileException | DirectoryNotEmptyException x) {
  87                 throw x;
  88             } catch (IOException x) {
  89                 // Backoff/retry in case another process is accessing the file
  90                 times++;
  91                 if (ioe == null)
  92                     ioe = x;
  93                 else
  94                     ioe.addSuppressed(x);
  95 
  96                 if (times > MAX_RETRY_DELETE_TIMES)
  97                     throw ioe;
  98                 Thread.sleep(RETRY_DELETE_MILLIS);
  99             }
 100         }
 101     }
 102 
 103     /**
 104      * Deletes a directory and its subdirectories, retrying if necessary.
 105      *
 106      * @param dir  the directory to delete
 107      *
 108      * @throws  IOException
 109      *          If an I/O error occurs. Any such exceptions are caught
 110      *          internally. If only one is caught, then it is re-thrown.
 111      *          If more than one exception is caught, then the second and
 112      *          following exceptions are added as suppressed exceptions of the
 113      *          first one caught, which is then re-thrown.
 114      */
 115     public static void deleteFileTreeWithRetry(Path dir)
 116          throws IOException
 117     {
 118         IOException ioe = null;
 119         final List<IOException> excs = deleteFileTreeUnchecked(dir);
 120         if (!excs.isEmpty()) {
 121             ioe = excs.remove(0);
 122             for (IOException x : excs)
 123                 ioe.addSuppressed(x);
 124         }
 125         if (ioe != null)
 126             throw ioe;
 127     }
 128 
 129     public static List<IOException> deleteFileTreeUnchecked(Path dir) {
 130         final List<IOException> excs = new ArrayList<>();
 131         try {
 132             java.nio.file.Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
 133                 @Override
 134                 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
 135                     try {
 136                         deleteFileWithRetry0(file);
 137                     } catch (IOException x) {
 138                         excs.add(x);
 139                     } catch (InterruptedException x) {
 140                         excs.add(new IOException("Interrupted while deleting.", x));
 141                         return FileVisitResult.TERMINATE;
 142                     }
 143                     return FileVisitResult.CONTINUE;
 144                 }
 145                 @Override
 146                 public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
 147                     try {
 148                         deleteFileWithRetry0(dir);
 149                     } catch (IOException x) {
 150                         excs.add(x);
 151                     } catch (InterruptedException x) {
 152                         excs.add(new IOException("Interrupted while deleting.", x));
 153                         return FileVisitResult.TERMINATE;
 154                     }
 155                     return FileVisitResult.CONTINUE;
 156                 }
 157                 @Override
 158                 public FileVisitResult visitFileFailed(Path file, IOException exc) {
 159                     excs.add(exc);
 160                     return FileVisitResult.CONTINUE;
 161                 }
 162             });
 163         } catch (IOException x) {
 164             excs.add(x);
 165         }
 166         return excs;
 167     }
 168 }
 169