View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.core.util;
18  
19  import java.io.File;
20  import java.io.IOException;
21  import java.io.UnsupportedEncodingException;
22  import java.net.MalformedURLException;
23  import java.net.URI;
24  import java.net.URISyntaxException;
25  import java.net.URL;
26  import java.net.URLDecoder;
27  import java.util.regex.Pattern;
28  
29  import org.apache.logging.log4j.Logger;
30  import org.apache.logging.log4j.status.StatusLogger;
31  
32  /**
33   * File utilities.
34   */
35  public final class FileUtils {
36  
37      /** Constant for the file URL protocol.*/
38      private static final String PROTOCOL_FILE = "file";
39  
40      private static final String JBOSS_FILE = "vfsfile";
41  
42      private static final Logger LOGGER = StatusLogger.getLogger();
43      private static final Pattern WINDOWS_DIRECTORY_SEPARATOR = Pattern.compile("\\\\+");
44  
45      private FileUtils() {
46      }
47  
48        /**
49       * Tries to convert the specified URL to a file object. If this fails,
50       * <b>null</b> is returned.
51       *
52       * @param uri the URI
53       * @return the resulting file object
54       */
55      public static File fileFromUri(URI uri) {
56          if (uri == null || (uri.getScheme() != null &&
57              (!PROTOCOL_FILE.equals(uri.getScheme()) && !JBOSS_FILE.equals(uri.getScheme())))) {
58              return null;
59          }
60          if (uri.getScheme() == null) {
61              try {
62                  uri = new File(uri.getPath()).toURI();
63              } catch (final Exception ex) {
64                  LOGGER.warn("Invalid URI {}", uri);
65                  return null;
66              }
67          }
68          final String charsetName = Charsets.UTF_8.name();
69          try {
70              final String fileName = uri.toURL().getFile();
71              if (new File(fileName).exists()) { // LOG4J2-466
72                  return new File(fileName); // allow files with '+' char in name
73              }
74              return new File(URLDecoder.decode(fileName, charsetName));
75          } catch (final MalformedURLException ex) {
76              LOGGER.warn("Invalid URL {}", uri, ex);
77          } catch (final UnsupportedEncodingException uee) {
78              LOGGER.warn("Invalid encoding: {}", charsetName, uee);
79          }
80          return null;
81      }
82  
83      public static boolean isFile(final URL url) {
84          return url != null && (url.getProtocol().equals(PROTOCOL_FILE) || url.getProtocol().equals(JBOSS_FILE));
85      }
86  
87      /**
88       * Asserts that the given directory exists and creates it if necessary.
89       * @param dir the directory that shall exist
90       * @param createDirectoryIfNotExisting specifies if the directory shall be created if it does not exist.
91       * @throws java.io.IOException thrown if the directory could not be created.
92       */
93      public static void mkdir(final File dir, final boolean createDirectoryIfNotExisting ) throws IOException {
94          // commons io FileUtils.forceMkdir would be useful here, we just want to omit this dependency
95          if (!dir.exists()) {
96              if(!createDirectoryIfNotExisting) {
97                  throw new IOException("The directory " + dir.getAbsolutePath() + " does not exist.");
98              }
99              if(!dir.mkdirs()) {
100                 throw new IOException("Could not create directory " + dir.getAbsolutePath());
101             }
102         }
103         if (!dir.isDirectory()) {
104             throw new IOException("File " + dir + " exists and is not a directory. Unable to create directory.");
105         }
106     }
107 
108     /**
109      * Takes a given URI string which may contain backslashes (illegal in URIs) in it due to user input or variable
110      * substitution and returns a URI with the backslashes replaced with forward slashes.
111      *
112      * @param uri The URI string
113      * @return the URI.
114      * @throws URISyntaxException if instantiating the URI threw a {@code URISyntaxException}.
115      */
116     public static URI getCorrectedFilePathUri(final String uri) throws URISyntaxException {
117         return new URI(WINDOWS_DIRECTORY_SEPARATOR.matcher(uri).replaceAll("/"));
118     }
119 }