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