1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
35
36 public final class FileUtils {
37
38
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
51
52
53
54
55
56 public static File fileFromUri(URI uri) {
57
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()) {
84 return new File(fileName);
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
102
103
104
105
106 public static void mkdir(final File dir, final boolean createDirectoryIfNotExisting ) throws IOException {
107
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 }