DeletingPathVisitor.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.io.file;

  18. import java.io.IOException;
  19. import java.nio.file.FileVisitResult;
  20. import java.nio.file.Files;
  21. import java.nio.file.LinkOption;
  22. import java.nio.file.NoSuchFileException;
  23. import java.nio.file.Path;
  24. import java.nio.file.attribute.BasicFileAttributes;
  25. import java.util.Arrays;
  26. import java.util.Objects;

  27. import org.apache.commons.io.file.Counters.PathCounters;

  28. /**
  29.  * Deletes files and directories as a visit proceeds.
  30.  *
  31.  * @since 2.7
  32.  */
  33. public class DeletingPathVisitor extends CountingPathVisitor {

  34.     /**
  35.      * Constructs a new instance configured with a BigInteger {@link PathCounters}.
  36.      *
  37.      * @return a new instance configured with a BigInteger {@link PathCounters}.
  38.      */
  39.     public static DeletingPathVisitor withBigIntegerCounters() {
  40.         return new DeletingPathVisitor(Counters.bigIntegerPathCounters());
  41.     }

  42.     /**
  43.      * Constructs a new instance configured with a long {@link PathCounters}.
  44.      *
  45.      * @return a new instance configured with a long {@link PathCounters}.
  46.      */
  47.     public static DeletingPathVisitor withLongCounters() {
  48.         return new DeletingPathVisitor(Counters.longPathCounters());
  49.     }

  50.     private final String[] skip;
  51.     private final boolean overrideReadOnly;
  52.     private final LinkOption[] linkOptions;

  53.     /**
  54.      * Constructs a instance that deletes files except for the files and directories explicitly given.
  55.      *
  56.      * @param pathCounter How to count visits.
  57.      * @param deleteOption How deletion is handled.
  58.      * @param skip The files to skip deleting.
  59.      * @since 2.8.0
  60.      */
  61.     public DeletingPathVisitor(final PathCounters pathCounter, final DeleteOption[] deleteOption, final String... skip) {
  62.         this(pathCounter, PathUtils.noFollowLinkOptionArray(), deleteOption, skip);
  63.     }

  64.     /**
  65.      * Constructs a instance that deletes files except for the files and directories explicitly given.
  66.      *
  67.      * @param pathCounter How to count visits.
  68.      * @param linkOptions How symbolic links are handled.
  69.      * @param deleteOption How deletion is handled.
  70.      * @param skip The files to skip deleting.
  71.      * @since 2.9.0
  72.      */
  73.     public DeletingPathVisitor(final PathCounters pathCounter, final LinkOption[] linkOptions, final DeleteOption[] deleteOption, final String... skip) {
  74.         super(pathCounter);
  75.         final String[] temp = skip != null ? skip.clone() : EMPTY_STRING_ARRAY;
  76.         Arrays.sort(temp);
  77.         this.skip = temp;
  78.         this.overrideReadOnly = StandardDeleteOption.overrideReadOnly(deleteOption);
  79.         // TODO Files.deleteIfExists() never follows links, so use LinkOption.NOFOLLOW_LINKS in other calls to Files.
  80.         this.linkOptions = linkOptions == null ? PathUtils.noFollowLinkOptionArray() : linkOptions.clone();
  81.     }

  82.     /**
  83.      * Constructs a instance that deletes files except for the files and directories explicitly given.
  84.      *
  85.      * @param pathCounter How to count visits.
  86.      * @param skip The files to skip deleting.
  87.      */
  88.     public DeletingPathVisitor(final PathCounters pathCounter, final String... skip) {
  89.         this(pathCounter, PathUtils.EMPTY_DELETE_OPTION_ARRAY, skip);
  90.     }

  91.     /**
  92.      * Returns true to process the given path, false if not.
  93.      *
  94.      * @param path the path to test.
  95.      * @return true to process the given path, false if not.
  96.      */
  97.     private boolean accept(final Path path) {
  98.         return Arrays.binarySearch(skip, PathUtils.getFileNameString(path)) < 0;
  99.     }

  100.     @Override
  101.     public boolean equals(final Object obj) {
  102.         if (this == obj) {
  103.             return true;
  104.         }
  105.         if (!super.equals(obj)) {
  106.             return false;
  107.         }
  108.         if (getClass() != obj.getClass()) {
  109.             return false;
  110.         }
  111.         final DeletingPathVisitor other = (DeletingPathVisitor) obj;
  112.         return overrideReadOnly == other.overrideReadOnly && Arrays.equals(skip, other.skip);
  113.     }

  114.     @Override
  115.     public int hashCode() {
  116.         final int prime = 31;
  117.         int result = super.hashCode();
  118.         result = prime * result + Arrays.hashCode(skip);
  119.         result = prime * result + Objects.hash(overrideReadOnly);
  120.         return result;
  121.     }

  122.     @Override
  123.     public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
  124.         if (PathUtils.isEmptyDirectory(dir)) {
  125.             Files.deleteIfExists(dir);
  126.         }
  127.         return super.postVisitDirectory(dir, exc);
  128.     }

  129.     @Override
  130.     public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
  131.         super.preVisitDirectory(dir, attrs);
  132.         return accept(dir) ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
  133.     }

  134.     @Override
  135.     public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
  136.         if (accept(file)) {
  137.             // delete files and valid links, respecting linkOptions
  138.             if (Files.exists(file, linkOptions)) {
  139.                 if (overrideReadOnly) {
  140.                     PathUtils.setReadOnly(file, false, linkOptions);
  141.                 }
  142.                 Files.deleteIfExists(file);
  143.             }
  144.             // invalid links will survive previous delete, different approach needed:
  145.             if (Files.isSymbolicLink(file)) {
  146.                 try {
  147.                     // deleteIfExists does not work for this case
  148.                     Files.delete(file);
  149.                 } catch (final NoSuchFileException ignored) {
  150.                     // ignore
  151.                 }
  152.             }
  153.         }
  154.         updateFileCounters(file, attrs);
  155.         return FileVisitResult.CONTINUE;
  156.     }
  157. }