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.commons.configuration2.io;
18  
19  import java.io.File;
20  import java.net.URL;
21  import java.nio.ByteBuffer;
22  import java.nio.charset.Charset;
23  import java.nio.charset.StandardCharsets;
24  
25  /**
26   * This class is a subset of org.apache.commons.io.FileUtils, git-svn-id:
27   * https://svn.apache.org/repos/asf/commons/proper/io/trunk@1423916 13f79535-47bb-0310-9956-ffa450edef68. The subset is
28   * determined by {@link FileLocatorUtils}. The copied constants and methods are <em>literally</em> copied.<br />
29   *
30   * See CONFIGURATION-521 for a discussion.
31   */
32  final class FileUtils {
33      /**
34       * The UTF-8 character set, used to decode octets in URLs.
35       */
36      private static final Charset UTF8 = StandardCharsets.UTF_8;
37  
38      /**
39       * Convert from a {@code URL} to a {@code File}.
40       * <p>
41       * From version 1.1 this method will decode the URL. Syntax such as {@code file:///my%20docs/file.txt} will be correctly
42       * decoded to {@code /my docs/file.txt}. Starting with version 1.5, this method uses UTF-8 to decode percent-encoded
43       * octets to characters. Additionally, malformed percent-encoded octets are handled leniently by passing them through
44       * literally.
45       *
46       * @param url the file URL to convert, {@code null} returns {@code null}
47       * @return the equivalent {@code File} object, or {@code null} if the URL's protocol is not {@code file}
48       */
49      public static File toFile(final URL url) {
50          if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) {
51              return null;
52          }
53          String fileName = url.getFile().replace('/', File.separatorChar);
54          fileName = decodeUrl(fileName);
55          return new File(fileName);
56      }
57  
58      /**
59       * Decodes the specified URL as per RFC 3986, i.e. transforms percent-encoded octets to characters by decoding with the
60       * UTF-8 character set. This function is primarily intended for usage with {@link java.net.URL} which unfortunately does
61       * not enforce proper URLs. As such, this method will leniently accept invalid characters or malformed percent-encoded
62       * octets and simply pass them literally through to the result string. Except for rare edge cases, this will make
63       * unencoded URLs pass through unaltered.
64       *
65       * @param url The URL to decode, may be {@code null}.
66       * @return The decoded URL or {@code null} if the input was {@code null}.
67       */
68      static String decodeUrl(final String url) {
69          String decoded = url;
70          if (url != null && url.indexOf('%') >= 0) {
71              final int n = url.length();
72              final StringBuilder buffer = new StringBuilder();
73              final ByteBuffer bytes = ByteBuffer.allocate(n);
74              for (int i = 0; i < n;) {
75                  if (url.charAt(i) == '%') {
76                      try {
77                          do {
78                              final byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16);
79                              bytes.put(octet);
80                              i += 3;
81                          } while (i < n && url.charAt(i) == '%');
82                          continue;
83                      } catch (final RuntimeException ignored) {
84                          // malformed percent-encoded octet, fall through and
85                          // append characters literally
86                      } finally {
87                          if (bytes.position() > 0) {
88                              bytes.flip();
89                              buffer.append(UTF8.decode(bytes));
90                              bytes.clear();
91                          }
92                      }
93                  }
94                  buffer.append(url.charAt(i++));
95              }
96              decoded = buffer.toString();
97          }
98          return decoded;
99      }
100 
101 }