001/*
002 *  Copyright 2018 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.extraction.utils;
017
018/**
019 * Helper to sanitize file names.
020 */
021/* TODO: move to Runtime ?*/
022public final class FilenameUtils
023{
024    private static final String __FORBIDDEN_CHARACTERS = new StringBuilder("[")
025            .append("\\\\")
026            .append("\\/")
027            .append("\\:")
028            .append("\\*")
029            .append("\\?")
030            .append("\\\"")
031            .append("\\<")
032            .append("\\>")
033            .append("\\|")
034            .append("]")
035            .toString();
036    
037    /**
038     * Default constructor
039     */
040    private FilenameUtils()
041    {
042        // Nothing
043    }
044    
045    /**
046     * Sanitize a file name, i.e. replace illegal characters with the '_' character.
047     * <br>This does not prevent from creating file names forbidden by the OS such as "con", "com1", "..", "prn", ".", "aux", "nul"...
048     * @param filename The file name to sanitize
049     * @return The sanitized file name
050     */
051    public static String sanitize(String filename)
052    {
053        return filename.replaceAll(__FORBIDDEN_CHARACTERS, "_");
054    }
055}