All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fr.ird.observe.services.service.CleanTemporaryFilesTask Maven / Gradle / Ivy

The newest version!
package fr.ird.observe.services.service;

/*-
 * #%L
 * ObServe Toolkit :: Service
 * %%
 * Copyright (C) 2017 - 2021 Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * To clean temporaries files.
 *
 * @author Tony Chemit - [email protected]
 * @since 8.0
 */

public class CleanTemporaryFilesTask extends TimerTask {

    private static final Logger log = LogManager.getLogger(CleanTemporaryFilesTask.class);

    private final CleanTemporaryFilesTaskConfiguration configuration;

    public static Timer create(CleanTemporaryFilesTaskConfiguration configuration) {
        Timer result = new Timer("Delete temporary files daemon", true);
        result.scheduleAtFixedRate(new CleanTemporaryFilesTask(configuration), new Date(), TimeUnit.HOURS.toMillis(1));
        return result;
    }

    private static boolean isDirEmpty(final Path directory) throws IOException {
        try (DirectoryStream dirStream = Files.newDirectoryStream(directory)) {
            return !dirStream.iterator().hasNext();
        }
    }

    public CleanTemporaryFilesTask(CleanTemporaryFilesTaskConfiguration configuration) {
        this.configuration = configuration;
    }

    @Override
    public void run() {
        configuration.getTemporaryDirectoriesAndTimeout().forEach(this::run);
    }

    private void run(Path temporaryDirectory, Integer timeout) {
        if (Files.notExists(temporaryDirectory)) {
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR_OF_DAY, -timeout);
        Date deleteBefore = calendar.getTime();
        long deleteBeforeTime = deleteBefore.getTime();

        log.info(String.format("Delete temporary files in directory %s before %s", temporaryDirectory, deleteBefore));
        delete(temporaryDirectory, deleteBeforeTime);
    }

    private boolean delete(Path path, long deleteBeforeTime) {
        try {
            Files.walk(path).forEach(p -> {
                if (Objects.equals(path, p)) {
                    return;
                }
                if (Files.isDirectory(p)) {
                    boolean deleted = delete(p, deleteBeforeTime);
                    if (deleted) {
                        delete0(p, deleteBeforeTime);
                    }
                }
                if (Files.isRegularFile(p)) {
                    delete0(p, deleteBeforeTime);
                }
            });
            if (Files.isRegularFile(path)) {
                return Files.notExists(path);
            }
            if (Files.isDirectory(path)) {
                return isDirEmpty(path);
            }
            return false;
        } catch (IOException e) {
            throw new RuntimeException(String.format("Could not walk through temporary directory: %s", path), e);
        }
    }

    private void delete0(Path p, long deleteBeforeTime) {
        try {
            if (Files.getLastModifiedTime(p).toMillis() < deleteBeforeTime) {
                log.info("Delete temporary file: " + p);
                Files.delete(p);
            }
        } catch (IOException e) {
            log.error("Something wrong while process file: " + p, e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy