001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.rolling.helper;
015
016import java.io.File;
017
018import ch.qos.logback.core.CoreConstants;
019import ch.qos.logback.core.rolling.RollingFileAppender;
020import ch.qos.logback.core.rolling.RolloverFailure;
021import ch.qos.logback.core.spi.ContextAwareBase;
022import ch.qos.logback.core.util.EnvUtil;
023import ch.qos.logback.core.util.FileUtil;
024
025/**
026 * Utility class to help solving problems encountered while renaming files.
027 *
028 * @author Ceki Gulcu
029 */
030public class RenameUtil extends ContextAwareBase {
031
032    static String RENAMING_ERROR_URL = CoreConstants.CODES_URL + "#renamingError";
033
034    /**
035     * A relatively robust file renaming method which in case of failure due to
036     * src and target being on different volumes, falls back onto
037     * renaming by copying.
038     *
039     * @param src
040     * @param target
041     * @throws RolloverFailure
042     */
043    public void rename(String src, String target) throws RolloverFailure {
044        if (src.equals(target)) {
045            addWarn("Source and target files are the same [" + src + "]. Skipping.");
046            return;
047        }
048        File srcFile = new File(src);
049
050        if (srcFile.exists()) {
051            File targetFile = new File(target);
052            createMissingTargetDirsIfNecessary(targetFile);
053
054            addInfo("Renaming file [" + srcFile + "] to [" + targetFile + "]");
055
056            boolean result = srcFile.renameTo(targetFile);
057
058            if (!result) {
059                addWarn("Failed to rename file [" + srcFile + "] as [" + targetFile + "].");
060                Boolean areOnDifferentVolumes = areOnDifferentVolumes(srcFile, targetFile);
061                if (Boolean.TRUE.equals(areOnDifferentVolumes)) {
062                    addWarn("Detected different file systems for source [" + src + "] and target [" + target + "]. Attempting rename by copying.");
063                    renameByCopying(src, target);
064                    return;
065                } else {
066                    addWarn("Please consider leaving the [file] option of " + RollingFileAppender.class.getSimpleName() + " empty.");
067                    addWarn("See also " + RENAMING_ERROR_URL);
068                }
069            }
070        } else {
071            throw new RolloverFailure("File [" + src + "] does not exist.");
072        }
073    }
074
075    
076    
077    /**
078     * Attempts to determine whether both files are on different volumes. Returns true if we could determine that
079     * the files are on different volumes. Returns false otherwise or if an error occurred while doing the check.
080     *
081     * @param srcFile
082     * @param targetFile
083     * @return true if on different volumes, false otherwise or if an error occurred
084     */
085    Boolean areOnDifferentVolumes(File srcFile, File targetFile) throws RolloverFailure {
086        if (!EnvUtil.isJDK7OrHigher())
087            return false;
088
089        // target file is not certain to exist but its parent has to exist given the call hierarchy of this method
090        File parentOfTarget = targetFile.getAbsoluteFile().getParentFile();
091        
092        if(parentOfTarget == null) {
093            addWarn("Parent of target file ["+targetFile+"] is null");
094            return null;
095        }
096        if(!parentOfTarget.exists()) {
097            addWarn("Parent of target file ["+targetFile+"] does not exist");
098            return null;
099        }
100        
101        try {
102            boolean onSameFileStore = FileStoreUtil.areOnSameFileStore(srcFile, parentOfTarget);
103            return !onSameFileStore;
104        } catch (RolloverFailure rf) {
105            addWarn("Error while checking file store equality", rf);
106            return null;
107        }
108    }
109
110    public void renameByCopying(String src, String target) throws RolloverFailure {
111
112        FileUtil fileUtil = new FileUtil(getContext());
113        fileUtil.copy(src, target);
114
115        File srcFile = new File(src);
116        if (!srcFile.delete()) {
117            addWarn("Could not delete " + src);
118        }
119
120    }
121
122    void createMissingTargetDirsIfNecessary(File toFile) throws RolloverFailure {
123        boolean result = FileUtil.createMissingParentDirectories(toFile);
124        if (!result) {
125            throw new RolloverFailure("Failed to create parent directories for [" + toFile.getAbsolutePath() + "]");
126        }
127    }
128
129    @Override
130    public String toString() {
131        return "c.q.l.co.rolling.helper.RenameUtil";
132    }
133}