KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > dispatcher > groovy > GroovyDispatcher


1 /**
2  * Copyright (c) 2003-2006, David A. Czarnecki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * Redistributions of source code must retain the above copyright notice, this list of conditions and the
9  * following disclaimer.
10  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
11  * following disclaimer in the documentation and/or other materials provided with the distribution.
12  * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
13  * endorse or promote products derived from this software without specific prior written permission.
14  * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
15  * without prior written permission of David A. Czarnecki.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */

31 package org.blojsom.dispatcher.groovy;
32
33 import groovy.lang.Binding;
34 import groovy.text.SimpleTemplateEngine;
35 import groovy.text.Template;
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.blojsom.BlojsomException;
39 import org.blojsom.blog.Blog;
40 import org.blojsom.dispatcher.Dispatcher;
41 import org.blojsom.util.BlojsomConstants;
42 import org.blojsom.util.BlojsomUtils;
43 import org.codehaus.groovy.syntax.SyntaxException;
44
45 import javax.servlet.ServletConfig JavaDoc;
46 import javax.servlet.ServletException JavaDoc;
47 import javax.servlet.ServletContext JavaDoc;
48 import javax.servlet.http.HttpServletRequest JavaDoc;
49 import javax.servlet.http.HttpServletResponse JavaDoc;
50 import java.io.IOException JavaDoc;
51 import java.io.InputStreamReader JavaDoc;
52 import java.io.Writer JavaDoc;
53 import java.util.Iterator JavaDoc;
54 import java.util.Map JavaDoc;
55 import java.util.Properties JavaDoc;
56
57 /**
58  * GroovyDispatcher
59  *
60  * @author David Czarnecki
61  * @since blojsom 3.0
62  * @version $Id: GroovyDispatcher.java,v 1.1 2006/03/23 14:27:56 czarneckid Exp $
63  */

64 public class GroovyDispatcher implements Dispatcher {
65
66     private Log _logger = LogFactory.getLog(GroovyDispatcher.class);
67
68     private ServletConfig JavaDoc _servletConfig;
69     private Properties JavaDoc _blojsomProperties;
70
71     private String JavaDoc _templatesDirectory;
72     private String JavaDoc _blogsDirectory;
73
74     /**
75      * Default constructor
76      */

77     public GroovyDispatcher() {
78     }
79
80     /**
81      * Set the properties in use by blojsom
82      *
83      * @param blojsomProperties Properties in use by blojsom
84      */

85     public void setBlojsomProperties(Properties JavaDoc blojsomProperties) {
86         _blojsomProperties = blojsomProperties;
87     }
88
89     /**
90      * Set the {@link javax.servlet.ServletConfig}
91      *
92      * @param servletConfig {@link javax.servlet.ServletConfig}
93      */

94     public void setServletConfig(ServletConfig JavaDoc servletConfig) {
95         _servletConfig = servletConfig;
96     }
97
98     /**
99      * Initialization method for blojsom dispatchers
100      *
101      * @throws org.blojsom.BlojsomException If there is an error initializing the dispatcher
102      */

103     public void init() throws BlojsomException {
104         _templatesDirectory = _blojsomProperties.getProperty(BlojsomConstants.TEMPLATES_DIRECTORY_IP, BlojsomConstants.DEFAULT_TEMPLATES_DIRECTORY);
105         _blogsDirectory = _blojsomProperties.getProperty(BlojsomConstants.BLOGS_DIRECTORY_IP, BlojsomConstants.DEFAULT_BLOGS_DIRECTORY);
106     }
107
108     /**
109      * Dispatch a request and response. A context map is provided for the BlojsomServlet to pass
110      * any required information for use by the dispatcher. The dispatcher is also
111      * provided with the template for the requested flavor along with the content type for the
112      * specific flavor.
113      *
114      * @param httpServletRequest Request
115      * @param httpServletResponse Response
116      * @param blog {@link Blog}
117      * @param context Context map
118      * @param flavorTemplate Template to dispatch to for the requested flavor
119      * @param flavorContentType Content type for the requested flavor
120      * @throws java.io.IOException If there is an exception during IO
121      * @throws javax.servlet.ServletException If there is an exception in dispatching the request
122      */

123     public void dispatch(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map JavaDoc context, String JavaDoc flavorTemplate, String JavaDoc flavorContentType) throws IOException JavaDoc, ServletException JavaDoc {
124         httpServletResponse.setContentType(flavorContentType);
125
126         ServletContext JavaDoc servletContext = _servletConfig.getServletContext();
127
128         if (!flavorTemplate.startsWith("/")) {
129             flavorTemplate = '/' + flavorTemplate;
130         }
131
132         String JavaDoc flavorTemplateForPage = null;
133         String JavaDoc pageParameter = BlojsomUtils.getRequestValue(BlojsomConstants.PAGE_PARAM, httpServletRequest, true);
134
135         if (pageParameter != null) {
136             flavorTemplateForPage = BlojsomUtils.getTemplateForPage(flavorTemplate, pageParameter);
137             if (_logger.isDebugEnabled()) {
138                 _logger.debug("Retrieved template for page: " + flavorTemplateForPage);
139             }
140         }
141
142         Binding binding = new Binding();
143
144         // Populate the script context with context attributes from the blog
145
Iterator JavaDoc contextIterator = context.keySet().iterator();
146         String JavaDoc contextKey;
147         while (contextIterator.hasNext()) {
148             contextKey = (String JavaDoc) contextIterator.next();
149             binding.setVariable(contextKey, context.get(contextKey));
150         }
151
152         Writer JavaDoc responseWriter = httpServletResponse.getWriter();
153
154         SimpleTemplateEngine simpleTemplateEngine = new SimpleTemplateEngine();
155
156         // Try and look for the original flavor template with page for the individual user
157
if (flavorTemplateForPage != null) {
158             String JavaDoc templateToLoad = BlojsomConstants.DEFAULT_CONFIGURATION_BASE_DIRECTORY + _blogsDirectory + blog.getBlogId() + _templatesDirectory + BlojsomUtils.removeInitialSlash(flavorTemplateForPage);
159
160             if (servletContext.getResource(templateToLoad) != null) {
161                 InputStreamReader JavaDoc isr = new InputStreamReader JavaDoc(servletContext.getResourceAsStream(templateToLoad), BlojsomConstants.UTF8);
162
163                 try {
164                     Template groovyTemplate = simpleTemplateEngine.createTemplate(isr);
165                     groovyTemplate.setBinding(context);
166                     groovyTemplate.writeTo(responseWriter);
167                 } catch (SyntaxException e) {
168                     if (_logger.isErrorEnabled()) {
169                         _logger.error(e);
170                     }
171                 } catch (ClassNotFoundException JavaDoc e) {
172                     if (_logger.isErrorEnabled()) {
173                         _logger.error(e);
174                     }
175                 }
176
177                 if (_logger.isDebugEnabled()) {
178                     _logger.debug("Dispatched to flavor page template for user: " + templateToLoad);
179                 }
180
181                 return;
182             } else {
183                 templateToLoad = BlojsomConstants.DEFAULT_CONFIGURATION_BASE_DIRECTORY + BlojsomUtils.removeInitialSlash(_templatesDirectory) + BlojsomUtils.removeInitialSlash(flavorTemplateForPage);
184
185                 if (servletContext.getResource(templateToLoad) != null) {
186                     // Otherwise, fallback and look for the flavor template with page without including any user information
187
InputStreamReader JavaDoc isr = new InputStreamReader JavaDoc(servletContext.getResourceAsStream(templateToLoad), BlojsomConstants.UTF8);
188
189                     try {
190                         Template groovyTemplate = simpleTemplateEngine.createTemplate(isr);
191                         groovyTemplate.setBinding(context);
192                         groovyTemplate.writeTo(responseWriter);
193                     } catch (SyntaxException e) {
194                         if (_logger.isErrorEnabled()) {
195                             _logger.error(e);
196                         }
197                     } catch (ClassNotFoundException JavaDoc e) {
198                         if (_logger.isErrorEnabled()) {
199                             _logger.error(e);
200                         }
201                     }
202
203                     if (_logger.isDebugEnabled()) {
204                         _logger.debug("Dispatched to flavor page template for user: " + templateToLoad);
205                     }
206
207                     return;
208                 } else {
209                     if (_logger.isErrorEnabled()) {
210                         _logger.error("Unable to dispatch to flavor page template: " + templateToLoad);
211                     }
212                 }
213             }
214         } else {
215             // Otherwise, fallback and look for the flavor template for the individual user
216
String JavaDoc templateToLoad = BlojsomConstants.DEFAULT_CONFIGURATION_BASE_DIRECTORY + _blogsDirectory + blog.getBlogId() + _templatesDirectory + BlojsomUtils.removeInitialSlash(flavorTemplate);
217
218             if (servletContext.getResource(templateToLoad) != null) {
219                 InputStreamReader JavaDoc isr = new InputStreamReader JavaDoc(servletContext.getResourceAsStream(templateToLoad), BlojsomConstants.UTF8);
220
221                 try {
222                     Template groovyTemplate = simpleTemplateEngine.createTemplate(isr);
223                     groovyTemplate.setBinding(context);
224                     groovyTemplate.writeTo(responseWriter);
225                 } catch (SyntaxException e) {
226                     if (_logger.isErrorEnabled()) {
227                         _logger.error(e);
228                     }
229                 } catch (ClassNotFoundException JavaDoc e) {
230                     if (_logger.isErrorEnabled()) {
231                         _logger.error(e);
232                     }
233                 }
234
235                 if (_logger.isDebugEnabled()) {
236                     _logger.debug("Dispatched to flavor template for user: " + templateToLoad);
237                 }
238
239                 return;
240             } else {
241                 templateToLoad = BlojsomConstants.DEFAULT_CONFIGURATION_BASE_DIRECTORY + BlojsomUtils.removeInitialSlash(_templatesDirectory) + BlojsomUtils.removeInitialSlash(flavorTemplate);
242
243                 if (servletContext.getResource(templateToLoad) != null) {
244                     // Otherwise, fallback and look for the flavor template without including any user information
245
InputStreamReader JavaDoc isr = new InputStreamReader JavaDoc(servletContext.getResourceAsStream(templateToLoad), BlojsomConstants.UTF8);
246
247                     try {
248                         Template groovyTemplate = simpleTemplateEngine.createTemplate(isr);
249                         groovyTemplate.setBinding(context);
250                         groovyTemplate.writeTo(responseWriter);
251                     } catch (SyntaxException e) {
252                         if (_logger.isErrorEnabled()) {
253                             _logger.error(e);
254                         }
255                     } catch (ClassNotFoundException JavaDoc e) {
256                         if (_logger.isErrorEnabled()) {
257                             _logger.error(e);
258                         }
259                     }
260
261                     if (_logger.isDebugEnabled()) {
262                         _logger.debug("Dispatched to flavor template: " + templateToLoad);
263                     }
264
265                     return;
266                 } else {
267                     if (_logger.isErrorEnabled()) {
268                         _logger.error("Unable to dispatch to flavor template: " + templateToLoad);
269                     }
270                 }
271             }
272         }
273
274         responseWriter.flush();
275     }
276 }
277
Popular Tags