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.util.regex.Pattern;
28
29 import org.apache.logging.log4j.Logger;
30 import org.apache.logging.log4j.status.StatusLogger;
31
32
33
34
35 public final class FileUtils {
36
37
38 private static final String PROTOCOL_FILE = "file";
39
40 private static final String JBOSS_FILE = "vfsfile";
41
42 private static final Logger LOGGER = StatusLogger.getLogger();
43 private static final Pattern WINDOWS_DIRECTORY_SEPARATOR = Pattern.compile("\\\\+");
44
45 private FileUtils() {
46 }
47
48
49
50
51
52
53
54
55 public static File fileFromUri(URI uri) {
56 if (uri == null || (uri.getScheme() != null &&
57 (!PROTOCOL_FILE.equals(uri.getScheme()) && !JBOSS_FILE.equals(uri.getScheme())))) {
58 return null;
59 }
60 if (uri.getScheme() == null) {
61 try {
62 uri = new File(uri.getPath()).toURI();
63 } catch (final Exception ex) {
64 LOGGER.warn("Invalid URI {}", uri);
65 return null;
66 }
67 }
68 try {
69 final String fileName = uri.toURL().getFile();
70 if (new File(fileName).exists()) {
71 return new File(fileName);
72 }
73 return new File(URLDecoder.decode(fileName, "UTF8"));
74 } catch (final MalformedURLException ex) {
75 LOGGER.warn("Invalid URL {}", uri, ex);
76 } catch (final UnsupportedEncodingException uee) {
77 LOGGER.warn("Invalid encoding: UTF8", uee);
78 }
79 return null;
80 }
81
82 public static boolean isFile(final URL url) {
83 return url != null && (url.getProtocol().equals(PROTOCOL_FILE) || url.getProtocol().equals(JBOSS_FILE));
84 }
85
86
87
88
89
90
91
92 public static void mkdir(final File dir, final boolean createDirectoryIfNotExisting ) throws IOException {
93
94 if (!dir.exists()) {
95 if(!createDirectoryIfNotExisting) {
96 throw new IOException("The directory " + dir.getAbsolutePath() + " does not exist.");
97 }
98 if(!dir.mkdirs()) {
99 throw new IOException("Could not create directory " + dir.getAbsolutePath());
100 }
101 }
102 if (!dir.isDirectory()) {
103 throw new IOException("File " + dir + " exists and is not a directory. Unable to create directory.");
104 }
105 }
106
107
108
109
110
111
112
113
114
115 public static URI getCorrectedFilePathUri(final String uri) throws URISyntaxException {
116 return new URI(WINDOWS_DIRECTORY_SEPARATOR.matcher(uri).replaceAll("/"));
117 }
118 }