KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > mock > web > MockServletContext


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.mock.web;
18
19 import java.io.File JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.net.MalformedURLException JavaDoc;
23 import java.net.URL JavaDoc;
24 import java.util.Enumeration JavaDoc;
25 import java.util.Hashtable JavaDoc;
26 import java.util.Properties JavaDoc;
27 import java.util.Set JavaDoc;
28
29 import javax.servlet.RequestDispatcher JavaDoc;
30 import javax.servlet.Servlet JavaDoc;
31 import javax.servlet.ServletContext JavaDoc;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35
36 import org.springframework.core.CollectionFactory;
37 import org.springframework.core.io.DefaultResourceLoader;
38 import org.springframework.core.io.Resource;
39 import org.springframework.core.io.ResourceLoader;
40 import org.springframework.util.Assert;
41 import org.springframework.util.ObjectUtils;
42 import org.springframework.web.util.WebUtils;
43
44 /**
45  * Mock implementation of the {@link javax.servlet.ServletContext} interface.
46  *
47  * <p>Used for testing the Spring web framework; only rarely necessary for testing
48  * application controllers. As long as application components don't explicitly
49  * access the ServletContext, ClassPathXmlApplicationContext or
50  * FileSystemXmlApplicationContext can be used to load the context files for testing,
51  * even for DispatcherServlet context definitions.
52  *
53  * <p>For setting up a full WebApplicationContext in a test environment, you can
54  * use XmlWebApplicationContext (or GenericWebApplicationContext), passing in an
55  * appropriate MockServletContext instance. You might want to configure your
56  * MockServletContext with a FileSystemResourceLoader in that case, to make your
57  * resource paths interpreted as relative file system locations.
58  *
59  * <p>A common setup is to point your JVM working directory to the root of your
60  * web application directory, in combination with filesystem-based resource loading.
61  * This allows to load the context files as used in the web application, with
62  * relative paths getting interpreted correctly. Such a setup will work with both
63  * FileSystemXmlApplicationContext (which will load straight from the file system)
64  * and XmlWebApplicationContext with an underlying MockServletContext (as long as
65  * the MockServletContext has been configured with a FileSystemResourceLoader).
66  *
67  * @author Rod Johnson
68  * @author Juergen Hoeller
69  * @since 1.0.2
70  * @see #MockServletContext(org.springframework.core.io.ResourceLoader)
71  * @see org.springframework.web.context.support.XmlWebApplicationContext
72  * @see org.springframework.web.context.support.GenericWebApplicationContext
73  * @see org.springframework.context.support.ClassPathXmlApplicationContext
74  * @see org.springframework.context.support.FileSystemXmlApplicationContext
75  */

76 public class MockServletContext implements ServletContext JavaDoc {
77
78     private static final String JavaDoc TEMP_DIR_SYSTEM_PROPERTY = "java.io.tmpdir";
79
80
81     private final Log logger = LogFactory.getLog(getClass());
82
83     private final String JavaDoc resourceBasePath;
84     
85     private final ResourceLoader resourceLoader;
86
87     private final Properties JavaDoc initParameters = new Properties JavaDoc();
88
89     private final Hashtable JavaDoc attributes = new Hashtable JavaDoc();
90
91     private String JavaDoc servletContextName = "MockServletContext";
92
93
94     /**
95      * Create a new MockServletContext, using no base path and a
96      * DefaultResourceLoader (i.e. the classpath root as WAR root).
97      * @see org.springframework.core.io.DefaultResourceLoader
98      */

99     public MockServletContext() {
100         this("", null);
101     }
102
103     /**
104      * Create a new MockServletContext, using a DefaultResourceLoader.
105      * @param resourceBasePath the WAR root directory (should not end with a slash)
106      * @see org.springframework.core.io.DefaultResourceLoader
107      */

108     public MockServletContext(String JavaDoc resourceBasePath) {
109         this(resourceBasePath, null);
110     }
111
112     /**
113      * Create a new MockServletContext, using the specified ResourceLoader
114      * and no base path.
115      * @param resourceLoader the ResourceLoader to use (or null for the default)
116      */

117     public MockServletContext(ResourceLoader resourceLoader) {
118         this("", resourceLoader);
119     }
120
121     /**
122      * Create a new MockServletContext.
123      * @param resourceBasePath the WAR root directory (should not end with a slash)
124      * @param resourceLoader the ResourceLoader to use (or null for the default)
125      */

126     public MockServletContext(String JavaDoc resourceBasePath, ResourceLoader resourceLoader) {
127         this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");
128         this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
129
130         // Use JVM temp dir as ServletContext temp dir.
131
String JavaDoc tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
132         if (tempDir != null) {
133             this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File JavaDoc(tempDir));
134         }
135     }
136
137     /**
138      * Build a full resource location for the given path,
139      * prepending the resource base path of this MockServletContext.
140      * @param path the path as specified
141      * @return the full resource path
142      */

143     protected String JavaDoc getResourceLocation(String JavaDoc path) {
144         if (!path.startsWith("/")) {
145             path = "/" + path;
146         }
147         return this.resourceBasePath + path;
148     }
149
150
151     public ServletContext JavaDoc getContext(String JavaDoc name) {
152         throw new UnsupportedOperationException JavaDoc("getContext");
153     }
154
155     public int getMajorVersion() {
156         return 2;
157     }
158
159     public int getMinorVersion() {
160         return 4;
161     }
162
163     public String JavaDoc getMimeType(String JavaDoc filePath) {
164         throw new UnsupportedOperationException JavaDoc("getMimeType");
165     }
166
167     public Set JavaDoc getResourcePaths(String JavaDoc path) {
168         String JavaDoc actualPath = (path.endsWith("/") ? path : path + "/");
169         Resource resource = this.resourceLoader.getResource(getResourceLocation(actualPath));
170         try {
171             File JavaDoc file = resource.getFile();
172             String JavaDoc[] fileList = file.list();
173             if (ObjectUtils.isEmpty(fileList)) {
174                 return null;
175             }
176             Set JavaDoc resourcePaths = CollectionFactory.createLinkedSetIfPossible(fileList.length);
177             for (int i = 0; i < fileList.length; i++) {
178                 String JavaDoc resultPath = actualPath + fileList[i];
179                 if (resource.createRelative(fileList[i]).getFile().isDirectory()) {
180                     resultPath += "/";
181                 }
182                 resourcePaths.add(resultPath);
183             }
184             return resourcePaths;
185         }
186         catch (IOException JavaDoc ex) {
187             logger.warn("Couldn't get resource paths for " + resource, ex);
188             return null;
189         }
190     }
191
192     public URL JavaDoc getResource(String JavaDoc path) throws MalformedURLException JavaDoc {
193         Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
194         if (!resource.exists()) {
195             return null;
196         }
197         try {
198             return resource.getURL();
199         }
200         catch (MalformedURLException JavaDoc ex) {
201             throw ex;
202         }
203         catch (IOException JavaDoc ex) {
204             logger.warn("Couldn't get URL for " + resource, ex);
205             return null;
206         }
207     }
208
209     public InputStream JavaDoc getResourceAsStream(String JavaDoc path) {
210         Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
211         if (!resource.exists()) {
212             return null;
213         }
214         try {
215             return resource.getInputStream();
216         }
217         catch (IOException JavaDoc ex) {
218             logger.warn("Couldn't open InputStream for " + resource, ex);
219             return null;
220         }
221     }
222
223     public RequestDispatcher JavaDoc getRequestDispatcher(String JavaDoc path) {
224         if (!path.startsWith("/")) {
225             throw new IllegalArgumentException JavaDoc("RequestDispatcher path at ServletContext level must start with '/'");
226         }
227         return new MockRequestDispatcher(path);
228     }
229
230     public RequestDispatcher JavaDoc getNamedDispatcher(String JavaDoc path) {
231         throw new UnsupportedOperationException JavaDoc("getNamedDispatcher");
232     }
233
234     public Servlet JavaDoc getServlet(String JavaDoc name) {
235         throw new UnsupportedOperationException JavaDoc("getServlet");
236     }
237
238     public Enumeration JavaDoc getServlets() {
239         throw new UnsupportedOperationException JavaDoc("getServlets");
240     }
241
242     public Enumeration JavaDoc getServletNames() {
243         throw new UnsupportedOperationException JavaDoc("getServletNames");
244     }
245
246     public void log(String JavaDoc message) {
247         logger.info(message);
248     }
249
250     public void log(Exception JavaDoc ex, String JavaDoc message) {
251         logger.info(message, ex);
252     }
253
254     public void log(String JavaDoc message, Throwable JavaDoc ex) {
255         logger.info(message, ex);
256     }
257
258     public String JavaDoc getRealPath(String JavaDoc path) {
259         Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
260         try {
261             return resource.getFile().getAbsolutePath();
262         }
263         catch (IOException JavaDoc ex) {
264             logger.warn("Couldn't determine real path of resource " + resource, ex);
265             return null;
266         }
267     }
268
269     public String JavaDoc getServerInfo() {
270         return "MockServletContext";
271     }
272
273     public String JavaDoc getInitParameter(String JavaDoc name) {
274         Assert.notNull(name, "Parameter name must not be null");
275         return this.initParameters.getProperty(name);
276     }
277
278     public void addInitParameter(String JavaDoc name, String JavaDoc value) {
279         Assert.notNull(name, "Parameter name must not be null");
280         this.initParameters.setProperty(name, value);
281     }
282
283     public Enumeration JavaDoc getInitParameterNames() {
284         return this.initParameters.keys();
285     }
286
287     public Object JavaDoc getAttribute(String JavaDoc name) {
288         Assert.notNull(name, "Attribute name must not be null");
289         return this.attributes.get(name);
290     }
291
292     public Enumeration JavaDoc getAttributeNames() {
293         return this.attributes.keys();
294     }
295
296     public void setAttribute(String JavaDoc name, Object JavaDoc value) {
297         Assert.notNull(name, "Attribute name must not be null");
298         if (value != null) {
299             this.attributes.put(name, value);
300         }
301         else {
302             this.attributes.remove(name);
303         }
304     }
305
306     public void removeAttribute(String JavaDoc name) {
307         Assert.notNull(name, "Attribute name must not be null");
308         this.attributes.remove(name);
309     }
310
311     public void setServletContextName(String JavaDoc servletContextName) {
312         this.servletContextName = servletContextName;
313     }
314
315     public String JavaDoc getServletContextName() {
316         return servletContextName;
317     }
318
319 }
320
Popular Tags