1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.helpers;
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.URL;
25 import java.net.URLDecoder;
26
27 import org.apache.logging.log4j.Logger;
28 import org.apache.logging.log4j.status.StatusLogger;
29
30
31
32
33 public final class FileUtils {
34
35
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
47
48
49
50
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 }
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 public static boolean isFile(final URL url) {
76 return url != null && (url.getProtocol().equals(PROTOCOL_FILE) || url.getProtocol().equals(JBOSS_FILE));
77 }
78
79
80
81
82
83
84
85 public static void mkdir(final File dir, final boolean createDirectoryIfNotExisting ) throws IOException {
86
87 if (!dir.exists()) {
88 if(!createDirectoryIfNotExisting) {
89 throw new IOException( "The directory " + dir.getAbsolutePath() + " does not exist." );
90 }
91 if(!dir.mkdirs()) {
92 throw new IOException( "Could not create directory " + dir.getAbsolutePath() );
93 }
94 }
95 if (!dir.isDirectory()) {
96 throw new IOException("File " + dir + " exists and is not a directory. Unable to create directory.");
97 }
98 }
99 }