KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > directwebremoting > spring > DwrController


1 /*
2  * Copyright 2005 Joe Walker
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 package org.directwebremoting.spring;
17
18 import java.util.HashMap JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.Map JavaDoc;
21
22 import javax.servlet.ServletConfig JavaDoc;
23 import javax.servlet.ServletContext JavaDoc;
24 import javax.servlet.http.HttpServletRequest JavaDoc;
25 import javax.servlet.http.HttpServletResponse JavaDoc;
26
27 import org.directwebremoting.WebContextFactory.WebContextBuilder;
28 import org.directwebremoting.impl.ContainerMap;
29 import org.directwebremoting.impl.ContainerUtil;
30 import org.directwebremoting.impl.StartupUtil;
31 import org.directwebremoting.servlet.UrlProcessor;
32 import org.directwebremoting.util.FakeServletConfig;
33 import org.directwebremoting.util.Logger;
34 import org.springframework.beans.BeansException;
35 import org.springframework.beans.factory.BeanCreationException;
36 import org.springframework.beans.factory.BeanFactory;
37 import org.springframework.beans.factory.BeanFactoryAware;
38 import org.springframework.beans.factory.BeanNameAware;
39 import org.springframework.beans.factory.InitializingBean;
40 import org.springframework.util.Assert;
41 import org.springframework.web.servlet.ModelAndView;
42 import org.springframework.web.servlet.mvc.AbstractController;
43
44 /**
45  * A Spring Controller that handles DWR requests. <br/>
46  * Using this controller allows you to configure DWR entirely in Spring. You do not have to create
47  * a separate <code>dwr.xml</code> configuration file when using this controller.
48  *
49  * <p>The following configuration provides a basic example of how too define this controller as a bean
50  * in your application context.
51  *
52  * <code>
53  * <pre>
54    &lt;bean id="dwrController" class="org.directwebremoting.spring.DwrController">
55       &lt;property name="configurators">
56          &lt;list>
57             &lt;ref bean="dwrConfiguration"/>
58          &lt;/list>
59       &lt;/property>
60       &lt;property name="debug" value="true"/>
61    &lt;/bean>
62
63    &lt;bean id="dwrConfiguration" class="org.directwebremoting.spring.SpringConfigurator">
64       &lt;property name="creators">
65          &lt;map>
66             &lt;entry key="<b>mybean</b>">
67                &lt;bean class="org.directwebremoting.spring.CreatorConfig">
68                   &lt;property name="creator">
69                      &lt;bean class="org.directwebremoting.spring.BeanCreator">
70                         &lt;property name="bean" ref="<b>myBean</b>"/>
71                      &lt;/bean>
72                   &lt;/property>
73                &lt;/bean>
74             &lt;/entry>
75          &lt;/map>
76       &lt;/property>
77    &lt;/bean>
78
79    &lt;-- the bean you want to remote using DWR -->
80    &lt;bean id="<b>myBean</b>" class="MyBean"/>
81    </pre></code>
82  *
83  * In the near future we want to provide a DWR namespace for Spring, which should allow you to
84  * something like the following:
85  * <code>
86  * <pre>
87    &lt;dwr:configuration>
88       &lt;debug/>
89    &lt;/dwr:configuration>
90
91    &lt;-- the bean you want to remote using DWR -->
92    &lt;bean id="<b>myBean</b>" class="MyBean">
93       &lt;dwr:remote javascript="<b>mybean</b>"/>
94    &lt;/bean>
95    </pre></code>
96  * Which should be equivalent to the previous example. Please note that this is still work in progress
97  * and is therefore subject to change.</p>
98  *
99  * @author Joe Walker [joe at getahead dot ltd dot uk]
100  * @author Bram Smeets
101  */

102 public class DwrController extends AbstractController implements BeanNameAware, InitializingBean, BeanFactoryAware
103 {
104     /**
105      * Is called by the Spring container to set the bean factory. <br/>
106      * This bean factory is then used to obtain the global DWR configuration from. This global configuration is
107      * optional as DWR will provide defaults where possible.
108      * @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory)
109      */

110     public void setBeanFactory(BeanFactory beanFactory) throws BeansException
111     {
112         container = new SpringContainer();
113         container.setBeanFactory(beanFactory);
114     }
115
116     /**
117      * Sets whether DWR should be in debug mode (default is <code>false</code>). <br/>
118      * This allows access to the debug pages provided by DWR under <code>/[app-ctx]/dwr/</code>.
119      * <b>NOTE</b>: make sure to not set this property to <code>true</code> in a production environment.
120      * @param debug the indication of whether to start DWR in debug mode
121      */

122     public void setDebug(boolean debug)
123     {
124         this.debug = debug;
125     }
126
127     /**
128      * Sets the configurators to apply to this controller. <br/>
129      * The configurators are used to set up DWR correctly.
130      * @param configurators the configurators to apply to this controller
131      */

132     public void setConfigurators(List JavaDoc configurators)
133     {
134         this.configurators = configurators;
135     }
136
137     /**
138      * Sets whether the default DWR configuration should be included (default is <code>true</code>). <br/>
139      * This default configuration contains all build-in creators and converters. You normally want this
140      * default configuration to be included.
141      * @param includeDefaultConfig the indication of whether to include the default configuration
142      */

143     public void setIncludeDefaultConfig(boolean includeDefaultConfig)
144     {
145         this.includeDefaultConfig = includeDefaultConfig;
146     }
147
148     /**
149      * Is called by the Spring container after all properties have been set. <br/>
150      * This method actually makes sure the container is correctly initialized and all configurators
151      * are processed.
152      * @throws Exception in case setting up fails
153      * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
154      */

155     public void afterPropertiesSet() throws Exception JavaDoc
156     {
157         ServletContext JavaDoc servletContext = getServletContext();
158
159         if (logger.isDebugEnabled()) {
160             logger.debug("afterPropertiesSet() called with servletContext '" + servletContext + "'");
161         }
162         
163         Assert.notNull(servletContext, "The servlet context has not been set on the controller");
164         Assert.notNull(configurators, "The required 'configurators' property should be set");
165
166         // Use a fake servlet config as Spring 1.x does not provide ServletConfigAware functionality
167
// Now only allow Controller to be configured using parameters
168

169         // We should remove adding the ContainerMap here, but that will break anyone
170
// who has used the spring container to configure the DwrController e.g:
171
// <bean name="pollAndCometEnabled" class="java.lang.String">
172
// <constructor-arg index="0"><value>true</value></constructor-arg>
173
// </bean>
174
configParams.putAll(new ContainerMap(container, true));
175         servletConfig = new FakeServletConfig(name, servletContext, configParams);
176         
177         try
178         {
179             ContainerUtil.setupDefaults(container, servletConfig);
180             ContainerUtil.setupFromServletConfig(container, servletConfig);
181             container.addParameter("debug", "" + debug);
182             container.setupFinished();
183
184             webContextBuilder = StartupUtil.initWebContext(servletConfig, servletContext, container);
185             StartupUtil.initServerContext(servletConfig, servletContext, container);
186
187             ContainerUtil.prepareForWebContextFilter(servletContext, servletConfig, container, webContextBuilder, null);
188
189             // The dwr.xml from within the JAR file.
190
if (includeDefaultConfig)
191             {
192                 ContainerUtil.configureFromSystemDwrXml(container);
193             }
194
195             ContainerUtil.configure(container, configurators);
196             ContainerUtil.publishContainer(container, servletConfig);
197         }
198         catch (InstantiationException JavaDoc ex)
199         {
200             throw new BeanCreationException("Failed to instansiate", ex);
201         }
202         catch (IllegalAccessException JavaDoc ex)
203         {
204             throw new BeanCreationException("Access error", ex);
205         }
206         catch (Exception JavaDoc ex)
207         {
208             log.fatal("init failed", ex);
209             throw ex;
210         }
211         finally
212         {
213             webContextBuilder.unset();
214         }
215     }
216
217     /**
218      * Handles all request to this controller. <br/>
219      * It delegates to the <code>UrlProcessor</code> and also takes case of setting and unsetting of the
220      * current <code>WebContext</code>.
221      * @param request the request to handle
222      * @param response the reponse to handle
223      * @throws Exception in case handling of the request fails unexpectedly
224      * @see org.directwebremoting.WebContext
225      */

226     protected ModelAndView handleRequestInternal(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc
227     {
228         try
229         {
230             // set up the web context and delegate to the processor
231
webContextBuilder.set(request, response, servletConfig, getServletContext(), container);
232
233             UrlProcessor processor = (UrlProcessor) container.getBean(UrlProcessor.class.getName());
234             processor.handle(request, response);
235         }
236         finally
237         {
238             webContextBuilder.unset();
239         }
240
241         // return null to inform the dispatcher servlet the request has already been handled
242
return null;
243     }
244
245     /**
246      * Is called by the Spring container to set the name of this bean.
247      * @param name the name of this bean in the Spring container
248      * @see BeanNameAware#setBeanName(String)
249      */

250     public void setBeanName(String JavaDoc name)
251     {
252         this.name = name;
253     }
254
255     /**
256      * Additional parameters such as pollAndCometEnabled. For a full list see:
257      * <a HREF="http://getahead.org/dwr/server/servlet">http://getahead.org/dwr/server/servlet</a>
258      * @param configParams the configParams to set
259      */

260     public void setConfigParams(Map JavaDoc configParams)
261     {
262         Assert.notNull(configParams, "configParams cannot be null");
263         this.configParams = configParams;
264     }
265     
266     
267     /**
268      * How is this deployed in Spring
269      */

270     private String JavaDoc name;
271
272     /**
273      * Whether to allow access to the debug pages
274      */

275     private boolean debug = false;
276
277     /**
278      * The builder for the <code>WebContext</code> that keeps http objects local to a thread
279      * @see org.directwebremoting.WebContext
280      */

281     protected WebContextBuilder webContextBuilder;
282
283     /**
284      * DWRs IoC container (that passes stuff to Spring in this case)
285      */

286     private SpringContainer container;
287
288     /**
289      * The fake ServletConfig
290      */

291     private ServletConfig JavaDoc servletConfig;
292
293     /**
294      * Do we prefix the list of Configurators with a default to read the system
295      * dwr.xml file?
296      */

297     private boolean includeDefaultConfig = true;
298
299     /**
300      * What Configurators exist for us to configure ourselves.
301      */

302     private List JavaDoc configurators;
303
304     /**
305      * Additional parameters such as pollAndCometEnabled. For a full list see:
306      * <a HREF="http://getahead.org/dwr/server/servlet">http://getahead.org/dwr/server/servlet</a>
307      */

308     private Map JavaDoc configParams = new HashMap JavaDoc();
309     
310     /**
311      * The log stream
312      */

313     private static final Logger log = Logger.getLogger(DwrController.class);
314 }
315
Popular Tags