ed0a12d5dd6ccfb2329275d0f1937d93ed2b1e2d
[mir.git] / source / mircoders / localizer / basic / MirBasicPostingSessionHandler.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30 package mircoders.localizer.basic;
31
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Random;
37 import java.util.Vector;
38
39 import mir.config.MirPropertiesConfiguration;
40 import mir.log.LoggerWrapper;
41 import mir.session.Request;
42 import mir.session.Response;
43 import mir.session.Session;
44 import mir.session.SessionExc;
45 import mir.session.SessionFailure;
46 import mir.session.SessionHandler;
47 import mir.session.UploadedFile;
48 import mir.session.ValidationError;
49 import mir.session.ValidationHelper;
50 import mir.storage.StorageObject;
51 import mir.util.ExceptionFunctions;
52 import mircoders.global.MirGlobal;
53 import mircoders.module.ModuleMediaType;
54
55 /**
56  *
57  * <p>Title: Experimental session handler for comment postings </p>
58  * <p>Description: </p>
59  * <p>Copyright: Copyright (c) 2003</p>
60  * <p>Company: </p>
61  * @author not attributable
62  * @version 1.0
63  */
64
65 public abstract class MirBasicPostingSessionHandler implements SessionHandler {
66   protected LoggerWrapper logger;
67   protected MirPropertiesConfiguration configuration;
68
69   private String normalResponseGenerator;
70   private String dupeResponseGenerator;
71   private String unsupportedMediaTypeResponseGenerator;
72   private String finalResponseGenerator;
73
74
75   public MirBasicPostingSessionHandler() {
76     logger = new LoggerWrapper("Localizer.OpenPosting");
77     try {
78       configuration = MirPropertiesConfiguration.instance();
79     }
80     catch (Throwable t) {
81       logger.fatal("Cannot load configuration: " + t.toString());
82
83       throw new RuntimeException("Cannot load configuration: " + t.toString());
84     }
85   }
86
87   protected void setNormalResponseGenerator(String aGenerator) {
88     normalResponseGenerator = aGenerator;
89   }
90
91   protected void setResponseGenerators(String aNormalResponseGenerator, String aDupeResponseGenerator,
92         String anUnsupportedMediaTypeResponseGenerator, String aFinalResponseGenerator) {
93     setNormalResponseGenerator(aNormalResponseGenerator);
94     dupeResponseGenerator = aDupeResponseGenerator;
95     unsupportedMediaTypeResponseGenerator = anUnsupportedMediaTypeResponseGenerator;
96     finalResponseGenerator = aFinalResponseGenerator;
97   }
98
99   public void processRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
100     if (MirGlobal.abuse().getOpenPostingDisabled()) {
101       makeOpenPostingDisabledResponse(aRequest, aSession, aResponse);
102       aSession.terminate();
103     }
104     else {
105       if (aSession.getAttribute("initialRequest") == null) {
106         initialRequest(aRequest, aSession, aResponse);
107         aSession.setAttribute("initialRequest", "no");
108       }
109       else {
110         subsequentRequest(aRequest, aSession, aResponse);
111       }
112     }
113   };
114
115   protected void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
116     initializeSession(aRequest, aSession);
117     initializeResponseData(aRequest, aSession, aResponse);
118     makeInitialResponse(aRequest, aSession, aResponse);
119   }
120
121   public void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
122     try {
123
124       try {
125         List validationErrors = new Vector();
126
127         if (!shouldProcessRequest(aRequest, aSession, validationErrors)) {
128           initializeResponseData(aRequest, aSession, aResponse);
129           makeResponse(aRequest, aSession, aResponse, validationErrors);
130         }
131         else {
132           preProcessRequest(aRequest, aSession);
133           Iterator i = aRequest.getUploadedFiles().iterator();
134           while (i.hasNext()) {
135             processUploadedFile(aRequest, aSession, (UploadedFile) i.next());
136           }
137           postProcessRequest(aRequest, aSession);
138           initializeResponseData(aRequest, aSession, aResponse);
139           makeFinalResponse(aRequest, aSession, aResponse);
140           aSession.terminate();
141         }
142       }
143       catch (Throwable t) {
144         initializeResponseData(aRequest, aSession, aResponse);
145         makeErrorResponse(aRequest, aSession, aResponse, t);
146         aSession.terminate();
147       }
148     }
149     catch (Throwable t) {
150       aSession.terminate();
151
152       throw new SessionFailure(t);
153     }
154   }
155
156   protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
157     if (MirGlobal.abuse().getOpenPostingPassword()) {
158       String password = (String) aSession.getAttribute("password");
159       if (password==null) {
160         password = generateOnetimePassword();
161         aSession.setAttribute("password", password);
162       }
163     }
164     else {
165       aSession.deleteAttribute("password");
166     }
167
168     logger.debug("referrer = " + aRequest.getHeader("Referer"));
169
170     aSession.setAttribute("referer", aRequest.getHeader("Referer"));
171     aSession.setAttribute("nrmediaitems",
172         new Integer(configuration.getInt("ServletModule.OpenIndy.DefaultMediaUploadItems")));
173   }
174
175   protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
176     int nrMediaItems = ((Integer) aSession.getAttribute("nrmediaitems")).intValue();
177     List mediaItems = new Vector();
178     int i=0;
179
180     while (i<nrMediaItems) {
181       i++;
182       mediaItems.add(new Integer(i));
183     }
184
185     aResponse.setResponseValue("nrmediaitems", new Integer(nrMediaItems));
186     aResponse.setResponseValue("mediaitems", mediaItems);
187     aResponse.setResponseValue("password", aSession.getAttribute("password"));
188     aResponse.setResponseValue("referer", aSession.getAttribute("referer"));
189     aResponse.setResponseValue("errors", null);
190   }
191
192   protected void makeInitialResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
193     aResponse.setResponseGenerator(normalResponseGenerator);
194   };
195
196   protected void makeResponse(Request aRequest, Session aSession, Response aResponse, List anErrors) throws SessionExc, SessionFailure {
197     aResponse.setResponseValue("errors", anErrors);
198     aResponse.setResponseGenerator(normalResponseGenerator);
199   };
200
201   protected void makeFinalResponse(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
202     aResponse.setResponseGenerator(finalResponseGenerator);
203   };
204
205   protected void makeErrorResponse(Request aRequest, Session aSession, Response aResponse, Throwable anError) throws SessionExc, SessionFailure {
206     anError.printStackTrace();
207     Throwable rootCause = ExceptionFunctions.traceCauseException(anError);
208
209     if (rootCause instanceof DuplicatePostingExc)
210       aResponse.setResponseGenerator(dupeResponseGenerator);
211     if (rootCause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
212       aResponse.setResponseValue("mimetype", ((ModuleMediaType.UnsupportedMimeTypeExc) rootCause).getMimeType());
213       aResponse.setResponseGenerator(unsupportedMediaTypeResponseGenerator);
214     }
215     else {
216       aResponse.setResponseValue("errorstring", anError.getMessage());
217       aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.ErrorTemplate"));
218     }
219   };
220
221   protected void makeOpenPostingDisabledResponse(Request aRequest, Session aSession, Response aResponse) {
222     aResponse.setResponseGenerator(configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
223   }
224
225   protected void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
226   };
227   public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {
228   };
229   protected void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
230   };
231
232   protected boolean shouldProcessRequest(Request aRequest, Session aSession, List aValidationErrors) throws SessionExc, SessionFailure {
233     int nrMediaItems = ((Integer) aSession.getAttribute("nrmediaitems")).intValue();
234     try {
235       nrMediaItems = Math.min(configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems"), Integer.parseInt(aRequest.getParameter("nrmediaitems")));
236     }
237     catch (Throwable t) {
238     }
239
240     aSession.setAttribute("nrmediaitems", new Integer(nrMediaItems));
241
242     if (aRequest.getParameter("post")==null)
243       return false;
244     else {
245       validate(aValidationErrors, aRequest, aSession);
246       return (aValidationErrors == null || aValidationErrors.size() == 0);
247     }
248   }
249
250   protected void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {
251     String password = (String) aSession.getAttribute("password");
252
253     if (password!=null) {
254       String submittedPassword= aRequest.getParameter("password").trim();
255
256       if (!password.equals(submittedPassword)) {
257         aResults.add(new ValidationError("password", "passwordmismatch"));
258       }
259     }
260   }
261
262
263   /**
264    * Method to generate a one-time password
265    *
266    * @return a password, to be used once
267    */
268
269   protected String generateOnetimePassword() {
270     Random r = new Random();
271     int random = r.nextInt();
272
273     long l = System.currentTimeMillis();
274
275     l = (l*l*l*l)/random;
276     if (l<0)
277       l = l * -1;
278
279     String returnString = ""+l;
280
281     return returnString.substring(5);
282   }
283
284
285   /**
286    *
287    * @param aRequest
288    * @param aStorage
289    * @return
290    * @throws SessionExc
291    * @throws SessionFailure
292    */
293
294   protected static final Map getIntersectingValues(Request aRequest, StorageObject aStorage) throws SessionExc, SessionFailure {
295     Map result = new HashMap();
296
297     Iterator i = aStorage.getFields().iterator();
298
299     while (i.hasNext()) {
300       String fieldName = (String) i.next();
301       Object value = aRequest.getParameter(fieldName);
302       if (value != null)
303         result.put(fieldName, value);
304     }
305
306     return result;
307   }
308
309   protected static class DuplicatePostingExc extends SessionExc {
310     public DuplicatePostingExc(String aMessage) {
311       super(aMessage);
312     }
313   }
314
315 }