WatchedFolderUtils.java 12.4 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.aemfd.watchfolder.job;

import com.adobe.aemfd.watchfolder.job.DuplicateFilesFilter;
import com.adobe.aemfd.watchfolder.job.FilePathBuilder;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.StringCharacterIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WatchedFolderUtils {
    private static final Logger logger = LoggerFactory.getLogger(WatchedFolderUtils.class);
    public static final String FILE_SEPARATOR = System.getProperty("file.separator", "/");
    public static final String REMOVE_POST_FIX = ".remove";
    private static final String EXTENSIONS_SEPARATOR = ".";
    private static final char UNDERSCORE = '_';
    private static final String DEFAULT_SUFFIX = "_0";

    public static boolean validateFileFormat(String value) {
        return value.matches("[a-zA-Z0-9]*");
    }

    public static String resolveFilenameWithoutReplacingSpecialCharacters(String filename) {
        if (filename == null) {
            throw new IllegalArgumentException("Filename is null");
        }
        String resolvedFilename = WatchedFolderUtils.getFilenameWithNoExtension(filename);
        String extension = WatchedFolderUtils.getFileExtensionLowerCase(filename);
        if (extension != null) {
            resolvedFilename = resolvedFilename + "." + extension;
        }
        return resolvedFilename;
    }

    public static String replaceNonDigitNonLetterCharacters(String input) {
        if (input == null) {
            throw new IllegalArgumentException("Input is null");
        }
        StringBuffer result = new StringBuffer();
        StringCharacterIterator iterator = new StringCharacterIterator(input);
        char character = iterator.current();
        while (character != '\uffff') {
            Character ch = new Character(character);
            if (ch.compareTo(new Character('_')) != 0 && !Character.isLetterOrDigit(character)) {
                result.append(Integer.toHexString(new Integer(character)));
            } else {
                result.append(character);
            }
            character = iterator.next();
        }
        return result.toString();
    }

    public static void markForDelete(File aFile) {
        if (aFile == null || aFile != null && !aFile.exists()) {
            return;
        }
        String _fileName = aFile.getAbsolutePath();
        try {
            File removeFile = new File(_fileName + ".remove");
            removeFile.createNewFile();
        }
        catch (IOException e) {
            String msg = "Failed to mark the file \"" + _fileName + "\" for removal due to an exception caught.";
            throw new RuntimeException(msg, e);
        }
    }

    private static File nextFileNameInSequence(File[] matchingFiles) {
        String fileName;
        String nameWithoutExtension;
        int largestSuffix = 0;
        for (int count = 0; count < matchingFiles.length; ++count) {
            int number;
            String suffix;
            nameWithoutExtension = fileName = matchingFiles[count].getName();
            int index = fileName.lastIndexOf(".");
            if (index != -1) {
                nameWithoutExtension = fileName.substring(0, index);
            }
            if ((index = nameWithoutExtension.lastIndexOf(95)) == -1 || index == nameWithoutExtension.length() - 1 || (number = Integer.parseInt(suffix = nameWithoutExtension.substring(index + 1))) <= largestSuffix) continue;
            largestSuffix = number;
        }
        File folder = matchingFiles[0].getParentFile();
        nameWithoutExtension = fileName = matchingFiles[0].getName();
        String extension = "";
        int index = fileName.lastIndexOf(".");
        if (index != -1) {
            nameWithoutExtension = fileName.substring(0, index);
            if (index != fileName.length() - 1) {
                extension = fileName.substring(index + 1);
            }
        }
        String nameWithoutSuffix = nameWithoutExtension;
        index = nameWithoutExtension.lastIndexOf(95);
        if (index != -1) {
            nameWithoutSuffix = nameWithoutExtension.substring(0, index);
        }
        StringBuffer newFileName = new StringBuffer(nameWithoutSuffix).append('_').append(largestSuffix + 1);
        if (!"".equals(extension)) {
            newFileName.append(".").append(extension);
        }
        return new File(folder, newFileName.toString());
    }

    private static File appendDefaultSuffix(String absolutePath) {
        StringBuffer modifiedFileName = new StringBuffer();
        int index = absolutePath.lastIndexOf(".");
        if (index != -1) {
            modifiedFileName.append(absolutePath.substring(0, index));
        } else {
            modifiedFileName.append(absolutePath);
        }
        modifiedFileName.append("_0");
        if (index != -1) {
            modifiedFileName.append(".");
            if (index != absolutePath.length() - 1) {
                modifiedFileName.append(absolutePath.substring(index + 1));
            }
        }
        return new File(modifiedFileName.toString());
    }

    public static File resolveDuplicateFile(String absolutePath, boolean overwriteFiles) {
        File duplicateFile = new File(absolutePath);
        if (!overwriteFiles) {
            File file = new File(absolutePath);
            File folder = file.getParentFile();
            File[] matchingFiles = folder.listFiles(new DuplicateFilesFilter(file.getName()));
            duplicateFile = matchingFiles.length > 0 ? WatchedFolderUtils.nextFileNameInSequence(matchingFiles) : WatchedFolderUtils.appendDefaultSuffix(absolutePath);
        }
        return duplicateFile;
    }

    public static String getFileExtensionLowerCase(String fileName) {
        String extension = null;
        int position = fileName.lastIndexOf(".");
        if (position != -1) {
            extension = fileName.substring(position + 1).toLowerCase();
        }
        return extension;
    }

    public static boolean recursiveDeleteDir(File aDir) {
        File _canDir;
        try {
            _canDir = aDir.getCanonicalFile();
        }
        catch (IOException e) {
            logger.error("Exception while getting canonical path of the file", (Throwable)e);
            return false;
        }
        if (!_canDir.equals(aDir.getAbsoluteFile())) {
            return false;
        }
        File[] _files = _canDir.listFiles();
        if (_files != null) {
            for (int i = 0; i < _files.length; ++i) {
                File _currentfile = _files[i];
                boolean deleted = _currentfile.delete();
                if (deleted || !_currentfile.isDirectory()) continue;
                WatchedFolderUtils.recursiveDeleteDir(_currentfile);
            }
        }
        return aDir.delete();
    }

    public static File verifyAndCreateFilePath(String aParentPath, String aPath) {
        File _file = null;
        if (aParentPath != null) {
            String _parentPath = FilePathBuilder.getConcretePath(aParentPath);
            if (aPath != null) {
                String _path = FilePathBuilder.getConcretePath(aPath);
                _file = new File(_path);
                if (!_file.isAbsolute()) {
                    String _folderPath = WatchedFolderUtils.concatPathAndFolder(_parentPath, _path);
                    _file = new File(_folderPath);
                }
                FilePathBuilder.makeDirectoryPath(_file);
            }
        }
        return _file;
    }

    public static void deleteMarkedFiles(File aOldFile) {
        if (aOldFile == null || aOldFile != null && !aOldFile.exists() && !aOldFile.isDirectory()) {
            return;
        }
        File[] files = aOldFile.listFiles(new FilenameFilter(){

            public boolean accept(File dir, String name) {
                return name.endsWith(".remove");
            }
        });
        if (files == null || files != null && files.length == 0) {
            aOldFile.delete();
            return;
        }
        for (int j = 0; j < files.length; ++j) {
            File markerFile = files[j];
            String markerName = markerFile.toString();
            File file = new File(markerName.substring(0, markerName.length() - ".remove".length()));
            String fileName = file.getName();
            if (!WatchedFolderUtils.validateFileFormat(fileName)) {
                fileName = "";
            }
            logger.debug("Deleting file: " + fileName);
            boolean _deleteMarkerFile = true;
            if (file.exists()) {
                _deleteMarkerFile = WatchedFolderUtils.recursiveDeleteDir(file);
                logger.debug("Deleted File ------ " + fileName);
            } else {
                logger.debug("File Does not exists ----" + fileName);
            }
            if (!_deleteMarkerFile || markerFile == null) continue;
            if (WatchedFolderUtils.recursiveDeleteDir(markerFile)) {
                logger.debug("Deleted marker file ----- " + markerFile);
                continue;
            }
            logger.debug("Could not delete the marker file ----- " + markerFile);
        }
    }

    public static String getFilenameWithNoExtension(String aFilename) {
        if (aFilename == null) {
            throw new IllegalArgumentException("Filename is null");
        }
        String _fileNameWithNoExtension = aFilename;
        int _extPosition = aFilename.lastIndexOf(".");
        int _fileSepPosition = aFilename.lastIndexOf(FILE_SEPARATOR);
        if (_extPosition != -1 && _fileSepPosition != -1) {
            _fileNameWithNoExtension = aFilename.substring(_fileSepPosition + 1, _extPosition);
        }
        if (_extPosition == -1 && _fileSepPosition == -1) {
            _fileNameWithNoExtension = aFilename;
        }
        if (_extPosition == -1 && _fileSepPosition != -1) {
            _fileNameWithNoExtension = aFilename.substring(_fileSepPosition + 1);
        }
        if (_extPosition != -1 && _fileSepPosition == -1) {
            _fileNameWithNoExtension = aFilename.substring(0, _extPosition);
        }
        return _fileNameWithNoExtension;
    }

    public static boolean recursiveDeleteExpiredDir(File aDir, File aParentDir, long aExpirationDuration) {
        File _canDir;
        try {
            _canDir = aDir.getCanonicalFile();
        }
        catch (IOException e) {
            logger.error("Exception while getting canonical path of the file", (Throwable)e);
            return false;
        }
        if (!_canDir.equals(aDir.getAbsoluteFile())) {
            return false;
        }
        File[] _files = _canDir.listFiles();
        if (_files != null) {
            for (int i = 0; i < _files.length; ++i) {
                File _currentfile = _files[i];
                boolean deleted = false;
                if (System.currentTimeMillis() - _currentfile.lastModified() > aExpirationDuration) {
                    deleted = _currentfile.delete();
                }
                if (deleted || !_currentfile.isDirectory()) continue;
                WatchedFolderUtils.recursiveDeleteExpiredDir(_currentfile, aParentDir, aExpirationDuration);
            }
        }
        if (aDir.getAbsolutePath().equals(aParentDir.getAbsolutePath())) {
            return true;
        }
        return aDir.delete();
    }

    public static String concatPathAndFolder(String path, String folder) {
        StringBuffer concatPath = new StringBuffer(path);
        if (!path.endsWith(FILE_SEPARATOR)) {
            concatPath.append(FILE_SEPARATOR);
        }
        concatPath.append(folder);
        return concatPath.toString();
    }

    public static File searchPercent(String aWatchFolderPath, String aPath) {
        int percentIndex;
        File _returnFile = null;
        File _file = new File(aPath);
        String parentPath = _file.getPath();
        if (!_file.isAbsolute()) {
            parentPath = WatchedFolderUtils.concatPathAndFolder(aWatchFolderPath, _file.getPath());
        }
        if ((percentIndex = parentPath.indexOf("%")) != -1) {
            int slashIndex = (parentPath = parentPath.substring(0, percentIndex)).lastIndexOf(File.separator);
            if (slashIndex != -1) {
                parentPath = parentPath.substring(0, slashIndex);
                _returnFile = new File(parentPath);
            }
        } else {
            _returnFile = new File(parentPath);
        }
        return _returnFile;
    }

}