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     */
017    package org.apache.logging.log4j.core.helpers;
018    
019    import org.apache.logging.log4j.Logger;
020    import org.apache.logging.log4j.status.StatusLogger;
021    
022    import java.io.File;
023    import java.io.IOException;
024    import java.io.UnsupportedEncodingException;
025    import java.net.MalformedURLException;
026    import java.net.URI;
027    import java.net.URL;
028    import java.net.URLDecoder;
029    
030    /**
031     * File utilities.
032     */
033    public final class FileUtils {
034    
035        /** Constant for the file URL protocol.*/
036        private static final String PROTOCOL_FILE = "file";
037    
038        private static final String JBOSS_FILE = "vfsfile";
039    
040        private static final Logger LOGGER = StatusLogger.getLogger();
041    
042        private FileUtils() {
043        }
044    
045          /**
046         * Tries to convert the specified URL to a file object. If this fails,
047         * <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            if (uri == null || (uri.getScheme() != null &&
054                (!PROTOCOL_FILE.equals(uri.getScheme()) && !JBOSS_FILE.equals(uri.getScheme())))) {
055                return null;
056            } else {
057                if (uri.getScheme() == null) {
058                    try {
059                        uri = new File(uri.getPath()).toURI();
060                    } catch (final Exception ex) {
061                        LOGGER.warn("Invalid URI " + uri);
062                        return null;
063                    }
064                }
065                try {
066                    return new File(URLDecoder.decode(uri.toURL().getFile(), "UTF8"));
067                } catch (final MalformedURLException ex) {
068                    LOGGER.warn("Invalid URL " + uri, ex);
069                } catch (final UnsupportedEncodingException uee) {
070                    LOGGER.warn("Invalid encoding: UTF8", uee);
071                }
072                return null;
073            }
074        }
075    
076        public static boolean isFile(final URL url) {
077            return url != null && (url.getProtocol().equals(PROTOCOL_FILE) || url.getProtocol().equals(JBOSS_FILE));
078        }
079    
080        /**
081         * Asserts that the given directory exists and creates it if necessary.
082         * @param dir the directory that shall exist
083         * @param createDirectoryIfNotExisting specifies if the directory shall be created if it does not exist.
084         * @throws java.io.IOException thrown if the directory could not be created.
085         */
086        public static void mkdir(final File dir, final boolean createDirectoryIfNotExisting ) throws IOException {
087            // commons io FileUtils.forceMkdir would be useful here, we just want to omit this dependency
088            if (!dir.exists()) {
089                if(!createDirectoryIfNotExisting) {
090                    throw new IOException( "The directory " + dir.getAbsolutePath() + " does not exist." );
091                }
092                if(!dir.mkdirs()) {
093                    throw new IOException( "Could not create directory " + dir.getAbsolutePath() );
094                }
095            }
096            if (!dir.isDirectory()) {
097                throw new IOException("File " + dir + " exists and is not a directory. Unable to create directory.");
098            }
099        }
100    }