1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.seasar.uruma.util.resource.impl;
17
18 import java.io.File;
19 import java.io.InputStream;
20 import java.net.URL;
21
22 import org.seasar.framework.util.FileInputStreamUtil;
23 import org.seasar.framework.util.FileUtil;
24 import org.seasar.framework.util.InputStreamUtil;
25 import org.seasar.framework.util.StringUtil;
26 import org.seasar.uruma.util.AssertionUtil;
27 import org.seasar.uruma.util.resource.ResourceFilter;
28 import org.seasar.uruma.util.resource.ResourceHandler;
29 import org.seasar.uruma.util.resource.ResourceTraverser;
30
31
32
33
34
35
36 public class FileResourceTraverser implements ResourceTraverser {
37 protected static final String PROTOCOL = "file";
38
39
40
41
42 public String getProtocol() {
43 return PROTOCOL;
44 }
45
46
47
48
49
50
51 public void traverse(final URL root, final URL origin,
52 final ResourceHandler handler, final ResourceFilter filter) {
53 AssertionUtil.assertNotNull("origin", origin);
54 AssertionUtil.assertNotNull("handler", handler);
55
56 String path = origin.getPath();
57 if (StringUtil.isNotBlank(path)) {
58 File file = new File(path);
59 if (file.exists()) {
60 if (file.isDirectory()) {
61 File rootDir = getRootDir(root, origin);
62 traverseFileSystem(rootDir, file, handler, filter);
63 }
64 }
65
66 }
67 }
68
69
70
71
72
73 public void traverse(final URL root, final URL origin,
74 final ResourceHandler handler) {
75 traverse(root, origin, handler, null);
76 }
77
78 protected void traverseFileSystem(final File baseDir, final File dir,
79 final ResourceHandler handler, final ResourceFilter filter) {
80 File[] files = dir.listFiles();
81 String basePath = baseDir.getAbsolutePath().replace('\\', '/');
82
83 for (int i = 0; i < files.length; ++i) {
84 File file = files[i];
85 if (file.isDirectory()) {
86 traverseFileSystem(baseDir, file, handler, filter);
87 } else {
88 int pos = -1;
89 if (baseDir != null) {
90 pos = FileUtil.getCanonicalPath(baseDir).length();
91 }
92 String filePath = FileUtil.getCanonicalPath(file);
93 String resourcePath = filePath.substring(pos + 1).replace('\\',
94 '/');
95
96 if ((filter != null) && !filter.accept(resourcePath)) {
97 continue;
98 }
99
100 InputStream is = FileInputStreamUtil.create(file);
101 try {
102 handler.handle(basePath, resourcePath, is);
103 } finally {
104 InputStreamUtil.close(is);
105 }
106 }
107 }
108 }
109
110 protected File getRootDir(final URL root, final URL origin) {
111 if (root != null) {
112 String path = root.getPath();
113 if (path != null) {
114 File rootDir = new File(path);
115 if (rootDir.exists()) {
116 return rootDir;
117 }
118 }
119 }
120
121 String path = origin.getPath();
122 return new File(path);
123 }
124 }