1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.settings4j.contentresolver;
18
19 import java.io.File;
20 import java.io.IOException;
21
22 import org.apache.commons.io.FileUtils;
23 import org.settings4j.ContentResolver;
24
25
26
27
28
29
30
31
32
33
34
35
36
37 public class FSContentResolver implements ContentResolver {
38
39
40 private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(FSContentResolver.class);
41
42
43 public static final String FILE_URL_PREFIX = "file:";
44
45 private File rootFolder;
46
47
48 public void addContentResolver(final ContentResolver contentResolver) {
49 throw new UnsupportedOperationException("FSContentResolver cannot add other ContentResolvers");
50 }
51
52
53 public byte[] getContent(final String key) {
54 String normalizedKey = key;
55 if (normalizedKey.startsWith(FILE_URL_PREFIX)) {
56 normalizedKey = normalizedKey.substring(FILE_URL_PREFIX.length());
57 }
58
59 File file = new File(normalizedKey);
60 if (file.exists()) {
61 try {
62 return FileUtils.readFileToByteArray(file);
63 } catch (final IOException e) {
64 LOG.info(e.getMessage(), e);
65 }
66 } else {
67 file = new File(getRootFolder(), normalizedKey);
68 if (file.exists()) {
69 try {
70 return FileUtils.readFileToByteArray(file);
71 } catch (final IOException e) {
72 LOG.info(e.getMessage(), e);
73 }
74 }
75 }
76 return null;
77 }
78
79
80
81
82
83
84
85 public void setContent(final String key, final byte[] value) throws IOException {
86
87 final String normalizedKey;
88 if (key.startsWith(FILE_URL_PREFIX)) {
89 normalizedKey = key.substring(FILE_URL_PREFIX.length());
90 } else {
91 normalizedKey = key;
92 }
93
94 File file;
95
96 if (normalizedKey.startsWith("/")) {
97
98 file = new File(normalizedKey);
99 } else if (normalizedKey.indexOf(':') >= 0) {
100
101 file = new File(normalizedKey);
102 } else {
103 file = new File(getRootFolder(), normalizedKey);
104 }
105 LOG.debug("Store content in: {}", file.getAbsolutePath());
106
107 FileUtils.writeByteArrayToFile(file, value);
108 }
109
110
111
112
113
114
115
116
117 public File getRootFolder() {
118 if (rootFolder == null) {
119 rootFolder = new File(".");
120 LOG.info("FSContentResolver.rootFolder is null. "
121 + "The RootPath Folder will be used: " + rootFolder.getAbsolutePath());
122 }
123 return rootFolder;
124 }
125
126
127
128
129 public void setRootFolderPath(final String rootFolderPath) {
130 final File newRootFolder = new File(rootFolderPath);
131 if (!newRootFolder.exists()) {
132 try {
133 FileUtils.forceMkdir(newRootFolder);
134 rootFolder = newRootFolder;
135 LOG.info("Set RootPath for FSConntentResolver: {}", newRootFolder.getAbsolutePath());
136 } catch (final IOException e) {
137 LOG.warn("cannot create rootFolder: {}!", rootFolderPath);
138 }
139 } else {
140 rootFolder = newRootFolder;
141 }
142 }
143 }