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.helpers;
018
019import java.io.File;
020import java.io.IOException;
021import java.io.UnsupportedEncodingException;
022import java.net.MalformedURLException;
023import java.net.URI;
024import java.net.URISyntaxException;
025import java.net.URL;
026import java.net.URLDecoder;
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 URL to a file object. If this fails,
048     * <b>null</b> is returned.
049     *
050     * @param uri the URI
051     * @return the resulting file object
052     */
053    public static File fileFromURI(URI uri) {
054        if (uri == null || (uri.getScheme() != null &&
055            (!PROTOCOL_FILE.equals(uri.getScheme()) && !JBOSS_FILE.equals(uri.getScheme())))) {
056            return null;
057        }
058        if (uri.getScheme() == null) {
059            try {
060                uri = new File(uri.getPath()).toURI();
061            } catch (final Exception ex) {
062                LOGGER.warn("Invalid URI " + uri);
063                return null;
064            }
065        }
066        try {
067            String fileName = uri.toURL().getFile();
068            if (new File(fileName).exists()) { // LOG4J2-466
069                return new File(fileName); // allow files with '+' char in name
070            }
071            return new File(URLDecoder.decode(fileName, "UTF8"));
072        } catch (final MalformedURLException ex) {
073            LOGGER.warn("Invalid URL " + uri, ex);
074        } catch (final UnsupportedEncodingException uee) {
075            LOGGER.warn("Invalid encoding: UTF8", uee);
076        }
077        return null;
078    }
079
080    public static boolean isFile(final URL url) {
081        return url != null && (url.getProtocol().equals(PROTOCOL_FILE) || url.getProtocol().equals(JBOSS_FILE));
082    }
083
084    /**
085     * Asserts that the given directory exists and creates it if necessary.
086     * @param dir the directory that shall exist
087     * @param createDirectoryIfNotExisting specifies if the directory shall be created if it does not exist.
088     * @throws java.io.IOException thrown if the directory could not be created.
089     */
090    public static void mkdir(final File dir, final boolean createDirectoryIfNotExisting ) throws IOException {
091        // commons io FileUtils.forceMkdir would be useful here, we just want to omit this dependency
092        if (!dir.exists()) {
093            if(!createDirectoryIfNotExisting) {
094                throw new IOException( "The directory " + dir.getAbsolutePath() + " does not exist." );
095            }
096            if(!dir.mkdirs()) {
097                throw new IOException( "Could not create directory " + dir.getAbsolutePath() );
098            }
099        }
100        if (!dir.isDirectory()) {
101            throw new IOException("File " + dir + " exists and is not a directory. Unable to create directory.");
102        }
103    }
104
105    /**
106     * Takes a given URI string which may contain backslashes (illegal in URIs) in it due to user input or variable
107     * substitution and returns a URI with the backslashes replaced with forward slashes.
108     *
109     * @param uri The URI string
110     * @return the URI.
111     * @throws URISyntaxException if instantiating the URI threw a {@code URISyntaxException}.
112     */
113    public static URI getCorrectedFilePathUri(String uri) throws URISyntaxException {
114        return new URI(uri.replaceAll("\\\\+", "/"));
115    }
116}