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 */
017package org.apache.logging.log4j.core.util;
018
019import java.io.File;
020import java.io.IOException;
021import java.io.UnsupportedEncodingException;
022import java.net.MalformedURLException;
023import java.net.URI;
024import java.net.URL;
025import java.net.URLDecoder;
026import java.nio.charset.StandardCharsets;
027
028import org.apache.logging.log4j.Logger;
029import org.apache.logging.log4j.status.StatusLogger;
030
031/**
032 * File utilities.
033 */
034public final class FileUtils {
035
036    /** Constant for the file URL protocol. */
037    private static final String PROTOCOL_FILE = "file";
038
039    private static final String JBOSS_FILE = "vfsfile";
040
041    private static final Logger LOGGER = StatusLogger.getLogger();
042
043    private FileUtils() {
044    }
045
046    /**
047     * Tries to convert the specified URI to a file object. If this fails, <b>null</b> is returned.
048     *
049     * @param uri the URI
050     * @return the resulting file object
051     */
052    public static File fileFromUri(URI uri) {
053        // There MUST be a better way to do this. TODO Search other ASL projects...
054        if (uri == null
055                || (uri.getScheme() != null && (!PROTOCOL_FILE.equals(uri.getScheme()) && !JBOSS_FILE.equals(uri
056                        .getScheme())))) {
057            return null;
058        }
059        if (uri.getScheme() == null) {
060            File file = new File(uri.toString());
061            if (file.exists()) {
062                return file;
063            }
064            try {
065                final String path = uri.getPath();
066                file = new File(path);
067                if (file.exists()) {
068                    return file;
069                }
070                uri = new File(path).toURI();
071            } catch (final Exception ex) {
072                LOGGER.warn("Invalid URI {}", uri);
073                return null;
074            }
075        }
076        final String charsetName = StandardCharsets.UTF_8.name();
077        try {
078            String fileName = uri.toURL().getFile();
079            if (new File(fileName).exists()) { // LOG4J2-466
080                return new File(fileName); // allow files with '+' char in name
081            }
082            fileName = URLDecoder.decode(fileName, charsetName);
083            return new File(fileName);
084        } catch (final MalformedURLException ex) {
085            LOGGER.warn("Invalid URL {}", uri, ex);
086        } catch (final UnsupportedEncodingException uee) {
087            LOGGER.warn("Invalid encoding: {}", charsetName, uee);
088        }
089        return null;
090    }
091
092    public static boolean isFile(final URL url) {
093        return url != null && (url.getProtocol().equals(PROTOCOL_FILE) || url.getProtocol().equals(JBOSS_FILE));
094    }
095
096    public static String getFileExtension(final File file) {
097        final String fileName = file.getName();
098        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
099            return fileName.substring(fileName.lastIndexOf(".") + 1);
100        }
101        return null;
102    }
103
104    /**
105     * Asserts that the given directory exists and creates it if necessary.
106     * 
107     * @param dir the directory that shall exist
108     * @param createDirectoryIfNotExisting specifies if the directory shall be created if it does not exist.
109     * @throws java.io.IOException thrown if the directory could not be created.
110     */
111    public static void mkdir(final File dir, final boolean createDirectoryIfNotExisting) throws IOException {
112        // commons io FileUtils.forceMkdir would be useful here, we just want to omit this dependency
113        if (!dir.exists()) {
114            if (!createDirectoryIfNotExisting) {
115                throw new IOException("The directory " + dir.getAbsolutePath() + " does not exist.");
116            }
117            if (!dir.mkdirs()) {
118                throw new IOException("Could not create directory " + dir.getAbsolutePath());
119            }
120        }
121        if (!dir.isDirectory()) {
122            throw new IOException("File " + dir + " exists and is not a directory. Unable to create directory.");
123        }
124    }
125}