001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  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 */
017
018package org.apache.commons.io.file;
019
020import java.io.IOException;
021import java.nio.file.FileVisitResult;
022import java.nio.file.Files;
023import java.nio.file.LinkOption;
024import java.nio.file.Path;
025import java.nio.file.attribute.BasicFileAttributes;
026import java.util.Arrays;
027import java.util.Objects;
028
029import org.apache.commons.io.file.Counters.PathCounters;
030
031/**
032 * Deletes files but not directories as a visit proceeds.
033 *
034 * @since 2.7
035 */
036public class CleaningPathVisitor extends CountingPathVisitor {
037
038    /**
039     * Constructs a new instance configured with a BigInteger {@link PathCounters}.
040     *
041     * @return a new instance configured with a BigInteger {@link PathCounters}.
042     */
043    public static CountingPathVisitor withBigIntegerCounters() {
044        return new CleaningPathVisitor(Counters.bigIntegerPathCounters());
045    }
046
047    /**
048     * Constructs a new instance configured with a long {@link PathCounters}.
049     *
050     * @return a new instance configured with a long {@link PathCounters}.
051     */
052    public static CountingPathVisitor withLongCounters() {
053        return new CleaningPathVisitor(Counters.longPathCounters());
054    }
055
056    private final String[] skip;
057    private final boolean overrideReadOnly;
058
059    /**
060     * Constructs a new visitor that deletes files except for the files and directories explicitly given.
061     *
062     * @param pathCounter How to count visits.
063     * @param deleteOption How deletion is handled.
064     * @param skip The files to skip deleting.
065     * @since 2.8.0
066     */
067    public CleaningPathVisitor(final PathCounters pathCounter, final DeleteOption[] deleteOption, final String... skip) {
068        super(pathCounter);
069        final String[] temp = skip != null ? skip.clone() : EMPTY_STRING_ARRAY;
070        Arrays.sort(temp);
071        this.skip = temp;
072        this.overrideReadOnly = StandardDeleteOption.overrideReadOnly(deleteOption);
073    }
074
075    /**
076     * Constructs a new visitor that deletes files except for the files and directories explicitly given.
077     *
078     * @param pathCounter How to count visits.
079     * @param skip The files to skip deleting.
080     */
081    public CleaningPathVisitor(final PathCounters pathCounter, final String... skip) {
082        this(pathCounter, PathUtils.EMPTY_DELETE_OPTION_ARRAY, skip);
083    }
084
085    /**
086     * Returns true to process the given path, false if not.
087     *
088     * @param path the path to test.
089     * @return true to process the given path, false if not.
090     */
091    private boolean accept(final Path path) {
092        return Arrays.binarySearch(skip, PathUtils.getFileNameString(path)) < 0;
093    }
094
095    @Override
096    public boolean equals(final Object obj) {
097        if (this == obj) {
098            return true;
099        }
100        if (!super.equals(obj)) {
101            return false;
102        }
103        if (getClass() != obj.getClass()) {
104            return false;
105        }
106        final CleaningPathVisitor other = (CleaningPathVisitor) obj;
107        return overrideReadOnly == other.overrideReadOnly && Arrays.equals(skip, other.skip);
108    }
109
110    @Override
111    public int hashCode() {
112        final int prime = 31;
113        int result = super.hashCode();
114        result = prime * result + Arrays.hashCode(skip);
115        result = prime * result + Objects.hash(overrideReadOnly);
116        return result;
117    }
118
119    @Override
120    public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attributes) throws IOException {
121        super.preVisitDirectory(dir, attributes);
122        return accept(dir) ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
123    }
124
125    @Override
126    public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) throws IOException {
127        // Files.deleteIfExists() never follows links, so use LinkOption.NOFOLLOW_LINKS in other calls to Files.
128        if (accept(file) && Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
129            if (overrideReadOnly) {
130                PathUtils.setReadOnly(file, false, LinkOption.NOFOLLOW_LINKS);
131            }
132            Files.deleteIfExists(file);
133        }
134        updateFileCounters(file, attributes);
135        return FileVisitResult.CONTINUE;
136    }
137}