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