For absolute URIs don't fail on wrongly formatted file URIs
@@ -18,12 +18,9 @@ package org.apache.logging.log4j.core.util;
import java.io.File;
import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
import java.net.URI;
+import java.net.URISyntaxException;
import java.net.URL;
-import java.net.URLDecoder;
-import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -60,41 +57,38 @@ public final class FileUtils {
* @return the resulting file object
*/
public static File fileFromUri(URI uri) {
- // There MUST be a better way to do this. TODO Search other ASL projects...
- if (uri == null || (uri.getScheme() != null
- && (!PROTOCOL_FILE.equals(uri.getScheme()) && !JBOSS_FILE.equals(uri.getScheme())))) {
+ if (uri == null) {
return null;
}
- if (uri.getScheme() == null) {
+ if (uri.isAbsolute()) {
+ if (JBOSS_FILE.equals(uri.getScheme())) try {
+ // patch the scheme
+ uri = new URI(PROTOCOL_FILE, uri.getSchemeSpecificPart(), uri.getFragment());
+ } catch (URISyntaxException use) {
+ // should not happen, ignore
+ }
+ try {
+ if (PROTOCOL_FILE.equals(uri.getScheme())) {
+ return new File(uri);
+ }
+ } catch (final Exception ex) {
+ LOGGER.warn("Invalid URI {}", uri);
+ }
+ } else {
File file = new File(uri.toString());
+ try {
if (file.exists()) {
return file;
}
- try {
final String path = uri.getPath();
file = new File(path);
if (file.exists()) {
return file;
}
- uri = new File(path).toURI();
} catch (final Exception ex) {
LOGGER.warn("Invalid URI {}", uri);
- return null;
}
}
- final String charsetName = StandardCharsets.UTF_8.name();
- try {
- String fileName = uri.toURL().getFile();
- if (new File(fileName).exists()) { // LOG4J2-466
- return new File(fileName); // allow files with '+' char in name
- }
- fileName = URLDecoder.decode(fileName, charsetName);
- return new File(fileName);
- } catch (final MalformedURLException ex) {
- LOGGER.warn("Invalid URL {}", uri, ex);
- } catch (final UnsupportedEncodingException uee) {
- LOGGER.warn("Invalid encoding: {}", charsetName, uee);
- }
return null;
}
