01: package org.jicengine.io;
02:
03: import java.io.*;
04: import javax.servlet.ServletContext;
05:
06: /**
07: * <p>
08: * A Resource-implementation for accessing resources inside a web-application.
09: * </p>
10: * <p>
11: * WebApplicationResource used the methods <code>ServletContext.getResource()</code> and
12: * <code>ServletContext.getResourceAsStream()</code> for the job.
13: * </p>
14: *
15: * <p>
16: * Copyright (C) 2004 Timo Laitinen
17: * </p>
18: * @author Timo Laitinen
19: * @created 2004-09-20
20: * @since JICE-0.10
21: */
22:
23: public class WebApplicationResource extends AbstractResource implements
24: UrlReadable {
25:
26: private ServletContext webApplication;
27: private String resourceName;
28:
29: /**
30: * @param webApplication the ServletContext of the web-application
31: * @param resourceName the name of the resource i.e. a path inside
32: * the web-app. must start with "/".
33: */
34: public WebApplicationResource(ServletContext webApplication,
35: String resourceName) {
36: super ("web-app://" + resourceName);
37: this .webApplication = webApplication;
38: this .resourceName = resourceName;
39: }
40:
41: public ServletContext getServletContext() {
42: return this .webApplication;
43: }
44:
45: public String getResourceName() {
46: return this .resourceName;
47: }
48:
49: public java.net.URL getUrl() throws IOException {
50: java.net.URL url = this .webApplication
51: .getResource(getResourceName());
52: if (url != null) {
53: return url;
54: } else {
55: throw new IOException(
56: "Can't find web-application resource '"
57: + getResourceName() + "'");
58: }
59: }
60:
61: public boolean isAvailable() {
62: try {
63: return (this .webApplication.getResource(getResourceName()) != null);
64: } catch (java.net.MalformedURLException e) {
65: return false;
66: }
67: }
68:
69: public InputStream getInputStream() throws java.io.IOException {
70: InputStream stream = this .webApplication
71: .getResourceAsStream(getResourceName());
72:
73: if (stream != null) {
74: return stream;
75: } else {
76: throw new IOException(
77: "Can't find web-application resource '"
78: + getResourceName() + "'");
79: }
80: }
81:
82: public Resource getResource(String relativePath)
83: throws java.io.IOException {
84: return new WebApplicationResource(getServletContext(),
85: PathResolver.getRealPath(getResourceName(),
86: relativePath));
87: }
88: }
|