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.nio.charset.StandardCharsets;
28  import java.util.regex.Pattern;
29  
30  import org.apache.logging.log4j.Logger;
31  import org.apache.logging.log4j.status.StatusLogger;
32  
33  /**
34   * File utilities.
35   */
36  public final class FileUtils {
37  
38      /** Constant for the file URL protocol.*/
39      private static final String PROTOCOL_FILE = "file";
40  
41      private static final String JBOSS_FILE = "vfsfile";
42  
43      private static final Logger LOGGER = StatusLogger.getLogger();
44      private static final Pattern WINDOWS_DIRECTORY_SEPARATOR = Pattern.compile("\\\\+");
45  
46      private FileUtils() {
47      }
48  
49        /**
50       * Tries to convert the specified URI to a file object. If this fails,
51       * <b>null</b> is returned.
52       *
53       * @param uri the URI
54       * @return the resulting file object
55       */
56      public static File fileFromUri(URI uri) {
57          // There MUST be a better way to do this. TODO Search other ASL projects...
58          if (uri == null
59                  || (uri.getScheme() != null && (!PROTOCOL_FILE.equals(uri.getScheme()) && !JBOSS_FILE.equals(uri
60                          .getScheme())))) {
61              return null;
62          }
63          if (uri.getScheme() == null) {
64              File file = new File(uri.toString());
65              if (file.exists()) {
66                  return file;
67              }
68              try {
69                  final String path = uri.getPath();
70                  file = new File(path);
71                  if (file.exists()) {
72                      return file;
73                  }
74                  uri = new File(path).toURI();
75              } catch (final Exception ex) {
76                  LOGGER.warn("Invalid URI {}", uri);
77                  return null;
78              }
79          }
80          final String charsetName = StandardCharsets.UTF_8.name();
81          try {
82              String fileName = uri.toURL().getFile();
83              if (new File(fileName).exists()) { // LOG4J2-466
84                  return new File(fileName); // allow files with '+' char in name
85              }
86              fileName = URLDecoder.decode(fileName, charsetName);
87              return new File(fileName);
88          } catch (final MalformedURLException ex) {
89              LOGGER.warn("Invalid URL {}", uri, ex);
90          } catch (final UnsupportedEncodingException uee) {
91              LOGGER.warn("Invalid encoding: {}", charsetName, uee);
92          }
93          return null;
94      }
95  
96      public static boolean isFile(final URL url) {
97          return url != null && (url.getProtocol().equals(PROTOCOL_FILE) || url.getProtocol().equals(JBOSS_FILE));
98      }
99  
100     /**
101      * Asserts that the given directory exists and creates it if necessary.
102      * @param dir the directory that shall exist
103      * @param createDirectoryIfNotExisting specifies if the directory shall be created if it does not exist.
104      * @throws java.io.IOException thrown if the directory could not be created.
105      */
106     public static void mkdir(final File dir, final boolean createDirectoryIfNotExisting ) throws IOException {
107         // commons io FileUtils.forceMkdir would be useful here, we just want to omit this dependency
108         if (!dir.exists()) {
109             if(!createDirectoryIfNotExisting) {
110                 throw new IOException("The directory " + dir.getAbsolutePath() + " does not exist.");
111             }
112             if(!dir.mkdirs()) {
113                 throw new IOException("Could not create directory " + dir.getAbsolutePath());
114             }
115         }
116         if (!dir.isDirectory()) {
117             throw new IOException("File " + dir + " exists and is not a directory. Unable to create directory.");
118         }
119     }
120 }