1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.myfaces.trinidad.resource;
20
21 import java.io.File;
22 import java.io.IOException;
23
24 import java.net.URL;
25
26 import org.apache.myfaces.trinidad.logging.TrinidadLogger;
27
28 /**
29 * A resource loader implementation which loads resources
30 * from a directory. The returned resource URL will be null
31 * for file resources that do not exist, or for relative paths
32 * that attempt to access paths outside the root directory.
33 *
34 */
35 public class DirectoryResourceLoader extends ResourceLoader
36 {
37 /**
38 * Constructs a new DirectoryResourceLoader.
39 *
40 * @param directory the root directory
41 */
42 public DirectoryResourceLoader(
43 File directory)
44 {
45 if (directory == null)
46 throw new NullPointerException();
47
48 if (!directory.isDirectory())
49 throw new IllegalArgumentException();
50
51 _directory = directory;
52
53 try
54 {
55 _directoryPath = _directory.getCanonicalPath();
56 }
57 catch (IOException ex)
58 {
59 throw new IllegalArgumentException(ex);
60 }
61 }
62
63 /**
64 * Constructs a new DirectoryResourceLoader.
65 *
66 * @param directory the root directory
67 * @param parent the parent resource loader
68 */
69 public DirectoryResourceLoader(
70 File directory,
71 ResourceLoader parent)
72 {
73 super(parent);
74
75 if (directory == null)
76 throw new NullPointerException();
77
78 if (!directory.isDirectory())
79 throw new IllegalArgumentException();
80
81 _directory = directory;
82
83 try
84 {
85 _directoryPath = _directory.getCanonicalPath();
86 }
87 catch (IOException ex)
88 {
89 throw new IllegalArgumentException(ex);
90 }
91
92 }
93
94 @Override
95 protected URL findResource(
96 String path) throws IOException
97 {
98 if (path.charAt(0) == '/')
99 path = path.substring(1);
100
101
102 File file = new File(_directory, path).getCanonicalFile();
103
104
105
106 boolean isContained = file.getCanonicalPath().startsWith(_directoryPath);
107
108
109
110
111
112
113
114
115 return (isContained && file.exists()) ? file.toURI().toURL() : null;
116 }
117
118 private final File _directory;
119 private final String _directoryPath;
120 private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(
121 DirectoryResourceLoader.class);
122 }