1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.backsource.utils.resource;
19
20 import java.net.URL;
21 import java.net.MalformedURLException;
22
23 import javax.servlet.ServletContext;
24 /***
25 * <p>Resolve URI:s to URL by looking them up in the ServletContext.
26 *
27 * <p>The URI.getPath() is used to get the resource name.
28 *
29 * @author Peter Antman
30 * @version $Revison$
31 */
32
33 public class ServletContextURLFactory implements URLFactory {
34 private ServletContext ctx = null;
35
36 private ServletContextURLFactory() {
37
38
39 }
40
41 /***
42 * Create with a ServletContext.
43 *
44 * @param ctx a servlet context
45 * @exception IllegalArgumentException thrown if ctx is null
46 */
47 public ServletContextURLFactory(ServletContext ctx) {
48 if (ctx == null)
49 throw new IllegalArgumentException("ServletContext must not be null");
50 this.ctx = ctx;
51 }
52 /***
53 * Construct an URL from URI by looking it up in the ContextClassLoader.
54 */
55 public URL getURL(URI uri) throws MalformedURLException {
56 String resUri = getResURI(uri);
57 URL url = ctx.getResource( resUri );
58 if (url == null)
59 throw new MalformedURLException("Could not find resource: " + resUri);
60 return url;
61 }
62
63 protected String getResURI(URI uri) {
64
65
66 return uri.getPath();
67 }
68 }