KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jicengine > io > WebApplicationResource


1 package org.jicengine.io;
2
3 import java.io.*;
4 import javax.servlet.ServletContext JavaDoc;
5
6 /**
7  * <p>
8  * A Resource-implementation for accessing resources inside a web-application.
9  * </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 UrlReadable {
24
25     private ServletContext JavaDoc webApplication;
26     private String JavaDoc resourceName;
27
28     /**
29      * @param webApplication the ServletContext of the web-application
30      * @param resourceName the name of the resource i.e. a path inside
31      * the web-app. must start with "/".
32      */

33     public WebApplicationResource(ServletContext JavaDoc webApplication, String JavaDoc resourceName)
34     {
35         super("web-app://" + resourceName);
36         this.webApplication = webApplication;
37         this.resourceName = resourceName;
38     }
39
40     public ServletContext JavaDoc getServletContext()
41     {
42         return this.webApplication;
43     }
44
45     public String JavaDoc getResourceName()
46     {
47         return this.resourceName;
48     }
49
50     public java.net.URL JavaDoc getUrl() throws IOException
51     {
52         java.net.URL JavaDoc url = this.webApplication.getResource(getResourceName());
53         if( url != null ){
54             return url;
55         }
56         else {
57             throw new IOException("Can't find web-application resource '" + getResourceName() + "'");
58         }
59     }
60
61     public boolean isAvailable()
62     {
63         try {
64             return (this.webApplication.getResource(getResourceName()) != null);
65         } catch (java.net.MalformedURLException JavaDoc e){
66             return false;
67         }
68     }
69
70     public InputStream getInputStream() throws java.io.IOException JavaDoc
71     {
72         InputStream stream = this.webApplication.getResourceAsStream(getResourceName());
73
74         if( stream != null ){
75             return stream;
76         }
77         else {
78             throw new IOException("Can't find web-application resource '" + getResourceName() + "'");
79         }
80     }
81
82     public Resource getResource(String JavaDoc relativePath) throws java.io.IOException JavaDoc
83     {
84         return new WebApplicationResource(getServletContext(), PathResolver.getRealPath(getResourceName(), relativePath));
85     }
86 }
87
Popular Tags