a new servletfilter, which controls the caching-values in the http-header.\ra new...
[mir.git] / source / mir / core / ui / servlet / TemplateServlet.java
1 /*
2  * TemplateServlet.java created on 01.09.2003
3  * 
4  * Copyright (C) 2001, 2002, 2003 The Mir-coders group
5  *
6  * This file is part of Mir.
7  *
8  * Mir is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * Mir is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Mir; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  * In addition, as a special exception, The Mir-coders gives permission to link
23  * the code of this program with  any library licensed under the Apache Software License,
24  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
25  * (or with modified versions of the above that use the same license as the above),
26  * and distribute linked combinations including the two.  You must obey the
27  * GNU General Public License in all respects for all of the code used other than
28  * the above mentioned libraries.  If you modify this file, you may extend this
29  * exception to your version of the file, but you are not obligated to do so.
30  * If you do not wish to do so, delete this exception statement from your version.
31  */
32 package mir.core.ui.servlet;
33
34 import java.io.IOException;
35 import java.io.PrintWriter;
36 import java.util.ArrayList;
37 import java.util.Date;
38 import java.util.Enumeration;
39 import java.util.HashMap;
40 import java.util.Iterator;
41 import java.util.List;
42 import java.util.Locale;
43 import java.util.Map;
44 import java.util.Vector;
45
46 import javax.servlet.ServletConfig;
47 import javax.servlet.ServletContext;
48 import javax.servlet.ServletException;
49 import javax.servlet.http.HttpServlet;
50 import javax.servlet.http.HttpServletRequest;
51 import javax.servlet.http.HttpServletResponse;
52 import javax.servlet.http.HttpSession;
53
54 import mir.config.MirPropertiesConfiguration;
55 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
56 import mir.servlet.ServletModuleExc;
57 import mir.util.GeneratorDateTimeFunctions;
58 import mir.util.GeneratorExpressionFunctions;
59 import mir.util.GeneratorHTMLFunctions;
60 import mir.util.GeneratorIntegerFunctions;
61 import mir.util.GeneratorListFunctions;
62 import mir.util.GeneratorRegularExpressionFunctions;
63 import mir.util.GeneratorStringFunctions;
64 import mir.util.ResourceBundleGeneratorFunction;
65 import mir.util.StringRoutines;
66 import mircoders.global.MirGlobal;
67 import mircoders.servlet.ServletHelper;
68 import multex.Failure;
69
70 import org.apache.struts.util.MessageResources;
71
72 /**
73  * TemplateServlet
74  * @author idefix
75  * @version $Id: TemplateServlet.java,v 1.3 2003/09/18 21:42:17 idfx Exp $
76  */
77 public class TemplateServlet extends HttpServlet {
78         private MirPropertiesConfiguration _configuration;
79         
80         /**
81          * 
82          */
83         public TemplateServlet() {
84                 super();
85                 try {
86                         _configuration = MirPropertiesConfiguration.instance();
87                 } catch (PropertiesConfigExc e) {
88                         throw new Failure("could not load config", e);
89                 }
90         }
91         
92         
93         
94         /**
95          * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
96          */
97         protected final void doGet(HttpServletRequest request, HttpServletResponse response) 
98         throws ServletException, IOException {
99                 process(request, response);
100         }
101
102         /**
103          * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
104          */
105         protected final void doPost(HttpServletRequest request, HttpServletResponse response) 
106                 throws ServletException, IOException {
107                 process(request, response);
108         }
109         
110         /**
111          * Processes the request and invokes the presentation
112          * @param request
113          * @param response
114          */
115         protected void process(HttpServletRequest request, HttpServletResponse response) 
116                 throws IOException, ServletException {
117                 try {
118                         setLoginLanguages(this.getServletContext());
119                         
120                         Map requestData = new HashMap();
121                         Enumeration keys = request.getAttributeNames();
122                         while(keys.hasMoreElements()){
123                                 final String key = (String)keys.nextElement();
124                                 requestData.put(key, request.getAttribute(key));
125                         }
126                         requestData.putAll(request.getParameterMap());
127                         
128                         Map sessionData = new HashMap();
129                         HttpSession httpSession = request.getSession();
130                         keys = httpSession.getAttributeNames();
131                         while(keys.hasMoreElements()){
132                                 final String key = (String)keys.nextElement();
133                                 sessionData.put(key, httpSession.getAttribute(key));
134                         }
135                         
136                         Map applicationData = new HashMap();
137                         ServletContext servletContext = getServletContext();
138                         keys = servletContext.getAttributeNames();
139                         while(keys.hasMoreElements()){
140                                 final String key = (String)keys.nextElement();
141                                 applicationData.put(key, servletContext.getAttribute(key));
142                         }               
143                         
144                         Map utilityMap = new HashMap();
145                         utilityMap.put("compressWhitespace", 
146                                 new freemarker.template.utility.CompressWhitespace());
147                         utilityMap.put("encodeHTML", 
148                                 new GeneratorHTMLFunctions.encodeHTMLGeneratorFunction());
149                         utilityMap.put("encodeXML", 
150                                 new GeneratorHTMLFunctions.encodeXMLGeneratorFunction());
151                         utilityMap.put("encodeURI", 
152                                 new GeneratorHTMLFunctions.encodeURIGeneratorFunction());
153                         utilityMap.put("subString", 
154                                 new GeneratorStringFunctions.subStringFunction());
155                         utilityMap.put("subList", 
156                                 new GeneratorListFunctions.subListFunction());
157                         utilityMap.put("isOdd", 
158                                 new GeneratorIntegerFunctions.isOddFunction());
159                         utilityMap.put("increment", 
160                                 new GeneratorIntegerFunctions.incrementFunction());
161                         utilityMap.put("evaluate", 
162                                 new GeneratorExpressionFunctions.evaluateExpressionFunction());
163                         utilityMap.put("constructString", 
164                                 new GeneratorStringFunctions.constructStructuredStringFunction());
165                         utilityMap.put("escapeJDBCString", 
166                                 new GeneratorStringFunctions.jdbcStringEscapeFunction());
167                         utilityMap.put("regexpreplace", 
168                                 new GeneratorRegularExpressionFunctions.regularExpressionReplaceFunction());
169                         utilityMap.put("datetime", 
170                                 new GeneratorDateTimeFunctions.DateTimeFunctions(
171                                         MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
172                         utilityMap.put("encodeLink", 
173                                 new GeneratorHTMLFunctions.encodeLinksGeneratorFunction(response));
174
175                         Map configData = MirPropertiesConfiguration.instance().allSettings();
176                         configData.put("docRoot", request.getContextPath());
177                         configData.put("now", new Date());
178                         
179                         //administeroperations
180                         List administerOperations = new Vector();
181                         String settings[] = MirPropertiesConfiguration.instance().getStringArray("Mir.Localizer.Admin.AdministerOperations");
182                         if (settings!=null) {
183                                 for (int i = 0; i < settings.length; i++) {
184                                         String setting = settings[i].trim();
185
186                                         if (setting.length() > 0) {
187                                                 List parts = StringRoutines.splitString(setting, ":");
188                                                 if (parts.size() != 2) {
189 //                                                      logger.error("config error: " + settings[i] + ", 2 parts expected");
190                                                 }
191                                                 else {
192                                                         Map entry = new HashMap();
193                                                         entry.put("name", (String) parts.get(0));
194                                                         entry.put("url", (String) parts.get(1));
195                                                         administerOperations.add(entry);
196                                                 }
197                                         }
198                                 }
199                         }
200                                                 
201                         Map templateData = new HashMap();
202                         templateData.put("request", requestData);
203                         templateData.put("session", sessionData);
204                         templateData.put("application", applicationData);
205                         templateData.put("utility", utilityMap);
206                         templateData.put("config", configData);
207                         templateData.put("administeroperations", administerOperations);
208                         
209                         String templateName = generateTemplateString(request);
210                         System.out.println(templateName);
211                         Locale[] locales = new Locale[2];
212                         locales[0] = request.getLocale();
213                         locales[1] = request.getLocale();
214                 
215                         //write the servlet
216                         PrintWriter printWriter = response.getWriter();
217                         generateResponse(printWriter, templateData, templateName, locales);
218                 } catch (Throwable e) {
219                         throw new ServletException(e);
220                 }
221         }
222         
223         private String generateTemplateString(HttpServletRequest request){
224                 String returnString = request.getServletPath();
225                 returnString = returnString.substring(0, returnString.indexOf("."));
226                 return returnString + ".tmpl";
227         }
228         
229         private void generateResponse(PrintWriter printWriter, Map map, 
230                 String templateString, Locale[] locales) 
231                 throws ServletModuleExc{
232                 if(templateString.startsWith("/admin")){
233                         map.put( "lang",
234                                         new ResourceBundleGeneratorFunction( locales,
235                                                  new MessageResources[] { 
236                                                                 MessageResources.getMessageResources("bundles.admin"),
237                                                                 MessageResources.getMessageResources("bundles.adminlocal")
238                                                                 }));
239                                                                 
240                         templateString = templateString.substring(templateString.lastIndexOf('/'));
241                         ServletHelper.generateResponse(printWriter, map, templateString);       
242                 }
243                 if(templateString.startsWith("/open")){
244                         map.put( "lang",
245                                 new ResourceBundleGeneratorFunction( locales,
246                                         new MessageResources[] { 
247                                                 MessageResources.getMessageResources("bundles.open"),
248                                                 MessageResources.getMessageResources("bundles.open")
249                                         }));
250                                                                 
251                         templateString = templateString.substring(templateString.lastIndexOf('/'));
252                         ServletHelper.generateOpenPostingResponse(printWriter, map, templateString);    
253                 }               
254         }
255         
256         private void setLoginLanguages(ServletContext context) throws ServletException {
257                 List loginLanguages = 
258                         (List) context.getAttribute(ServletConstants.LOGIN_LANGUAGES);  
259                 try {
260                         if (loginLanguages == null) {
261                                 MessageResources messageResources =
262                                         MessageResources.getMessageResources("bundles.adminlocal");
263                                 MessageResources messageResources2 =
264                                         MessageResources.getMessageResources("bundles.admin");
265
266                                 List languages =
267                                         StringRoutines.splitString(
268                                                 MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
269
270                                 loginLanguages = new ArrayList();
271                                 Iterator i = languages.iterator();
272                                 while (i.hasNext()) {
273                                         String code = (String) i.next();
274                                         Locale locale = new Locale(code, "");
275                                         String name = messageResources.getMessage(locale, "languagename");
276
277                                         if (name == null) {
278                                                 name = messageResources2.getMessage(locale, "languagename");
279                                         }
280
281                                         if (name == null) {
282                                                 name = code;
283                                         }
284
285                                         Map record = new HashMap();
286                                         record.put("name", name);
287                                         record.put("code", code);
288                                         loginLanguages.add(record);
289                                 }
290                                 context.setAttribute(ServletConstants.LOGIN_LANGUAGES, 
291                                         loginLanguages);
292                                 context.setAttribute(ServletConstants.DEFAULT_LANGUAGE, 
293                                         _configuration.getString("Mir.Login.DefaultLanguage"));
294                         }
295                 } catch (Throwable t) {
296                         throw new ServletException(t.getMessage());
297                 }
298         }
299
300         /**
301          * @see javax.servlet.Servlet#destroy()
302          */
303         public void destroy() {
304                 super.destroy();
305         }
306
307         /**
308          * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
309          */
310         public void init(ServletConfig servletConfig) throws ServletException {
311                 super.init(servletConfig);
312                 MirPropertiesConfiguration.setContext(servletConfig.getServletContext());
313                 try {
314                         MirPropertiesConfiguration.instance();
315                 }
316                 catch (Throwable t) {
317                         throw new ServletException("can't read configuration: " + t.toString());
318                 }
319         }
320 }