Organizing import, refresh the license (zapata deleted cos.jar)
[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.Arrays;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Random;
38 import java.util.Vector;
39
40 import mir.config.MirPropertiesConfiguration;
41 import mir.entity.Entity;
42 import mir.log.LoggerWrapper;
43 import mir.session.Request;
44 import mir.session.Response;
45 import mir.session.Session;
46 import mir.session.SessionExc;
47 import mir.session.SessionFailure;
48 import mir.session.SessionHandler;
49 import mir.session.UploadedFile;
50 import mir.storage.StorageObject;
51 import mir.util.ExceptionFunctions;
52 import mircoders.entity.EntityComment;
53 import mircoders.global.MirGlobal;
54 import mircoders.media.MediaUploadProcessor;
55 import mircoders.module.ModuleComment;
56 import mircoders.storage.DatabaseComment;
57 import mircoders.storage.DatabaseCommentToMedia;
58 import mircoders.storage.DatabaseContent;
59
60 /**
61  *
62  * <p>Title: Experimental session handler for comment postings </p>
63  * <p>Description: </p>
64  * <p>Copyright: Copyright (c) 2003</p>
65  * <p>Company: </p>
66  * @author not attributable
67  * @version 1.0
68  */
69
70 public class MirBasicPostingSessionHandler implements SessionHandler {
71   protected LoggerWrapper logger;
72   protected MirPropertiesConfiguration configuration;
73   protected ModuleComment commentModule;
74   protected DatabaseCommentToMedia commentToMedia = DatabaseCommentToMedia.getInstance();
75
76   public MirBasicPostingSessionHandler() {
77     logger = new LoggerWrapper("Localizer.OpenPosting");
78     try {
79       configuration = MirPropertiesConfiguration.instance();
80     }
81     catch (Throwable t) {
82       logger.fatal("Cannot load configuration: " + t.toString());
83
84       throw new RuntimeException("Cannot load configuration: " + t.toString());
85     }
86     commentModule= new ModuleComment(DatabaseComment.getInstance());
87   }
88
89   public void processRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
90     if (aSession.getAttribute("initialRequest")==null) {
91       initialRequest(aRequest, aSession, aResponse);
92       aSession.setAttribute("initialRequest", "no");
93     }
94     else {
95       subsequentRequest(aRequest, aSession, aResponse);
96     }
97   };
98
99   protected Map getIntersectingValues(Request aRequest, StorageObject aStorage) throws SessionExc, SessionFailure {
100     Map result = new HashMap();
101
102     Iterator i = aStorage.getFields().iterator();
103
104     while (i.hasNext()) {
105       String fieldName = (String) i.next();
106       Object value = aRequest.getParameter(fieldName);
107       if (value != null)
108         result.put(fieldName, value);
109     }
110
111     return result;
112   }
113
114
115   protected String generateOnetimePassword() {
116     Random r = new Random();
117     int random = r.nextInt();
118
119     long l = System.currentTimeMillis();
120
121     l = (l*l*l*l)/random;
122     if (l<0)
123       l = l * -1;
124
125     String returnString = ""+l;
126
127     return returnString.substring(5);
128   }
129
130   protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
131     if (MirGlobal.abuse().getOpenPostingPassword()) {
132       String password = (String) aSession.getAttribute("password");
133       if (password==null) {
134         password = generateOnetimePassword();
135         aSession.setAttribute("password", password);
136       }
137       aResponse.setResponseValue("password", password);
138     }
139     else {
140       aResponse.setResponseValue("password", null);
141       aSession.deleteAttribute("password");
142     }
143
144     aResponse.setResponseValue("errors", null);
145   };
146
147   protected void initialRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure{
148     Iterator i = DatabaseComment.getInstance().getFields().iterator();
149     while (i.hasNext()) {
150       aResponse.setResponseValue( (String) i.next(), null);
151     }
152
153     String articleId = aRequest.getParameter("to_media");
154
155     if (articleId == null)
156       throw new SessionExc("MirBasicPostingSessionHandler.initialRequest: article id not set!");
157
158     aSession.setAttribute("to_media", articleId);
159
160     initializeResponseData(aRequest, aSession, aResponse);
161
162     try {
163       aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate"));
164     }
165     catch (Throwable e) {
166       throw new SessionFailure("Can't get configuration: " + e.getMessage(), e);
167     }
168
169   }
170
171   protected boolean testFieldEntered(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
172     Object value = aRequest.getParameter(aFieldName);
173     if (value==null || !(value instanceof String) || ((String) value).trim().length()==0) {
174       logger.debug("  missing field " + aFieldName + " value = " + value);
175       aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
176       return false;
177     }
178     else
179       return true;
180   }
181
182   protected boolean testFieldIsNumeric(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
183     Object value = aRequest.getParameter(aFieldName);
184     if (value!=null) {
185       try {
186         Integer.parseInt((String) value);
187         return true;
188       }
189       catch (Throwable t) {
190         logger.debug("  field not numeric: " + aFieldName + " value = " + value);
191         aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
192         return false;
193       }
194     }
195     return true;
196   }
197
198   public void validate(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
199
200   }
201
202   public List validate(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
203     List result = new Vector();
204
205     testFieldEntered(aRequest, "title", "validationerror.missing", result);
206     testFieldEntered(aRequest, "description", "validationerror.missing", result);
207     testFieldEntered(aRequest, "creator", "validationerror.missing", result);
208
209     return result;
210   }
211
212   public void subsequentRequest(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
213     try {
214       Map commentFields = new HashMap();
215
216       Iterator i = DatabaseContent.getInstance().getFields().iterator();
217       while (i.hasNext()) {
218         String field = (String) i.next();
219         aResponse.setResponseValue(field, aRequest.getParameter(field));
220         if (aRequest.getParameter(field)!=null) {
221           commentFields.put(field, aRequest.getParameter(field));
222         }
223       }
224
225       initializeResponseData(aRequest, aSession, aResponse);
226
227       List validationErrors = validate(aRequest, aSession);
228
229       if (validationErrors != null && validationErrors.size()>0) {
230         returnValidationErrors(aRequest, aSession, aResponse, validationErrors);
231       }
232       else {
233 //        finish(aRequest, aSession, aResponse);
234
235         EntityComment comment = (EntityComment) commentModule.createNew ();
236 //        comment.setValues(getIntersectingValues(aRequest, ));
237
238         finishComment(aRequest, aSession, comment);
239
240         String id = comment.insert();
241         if(id==null){
242           afterDuplicateCommentPosting(aRequest, aSession, aResponse, comment);
243           logger.info("Dupe comment rejected");
244           aSession.terminate();
245         }
246         else {
247           i = aRequest.getUploadedFiles().iterator();
248           while (i.hasNext()) {
249             UploadedFile file = (UploadedFile) i.next();
250             processMediaFile(aRequest, aSession, comment, file);
251           }
252
253           afterCommentPosting(aRequest, aSession, aResponse, comment);
254           MirGlobal.abuse().checkComment(comment, aRequest, null);
255           MirGlobal.localizer().openPostings().afterCommentPosting(comment);
256           logger.info("Comment posted");
257           aSession.terminate();
258         }
259       }
260     }
261     catch (Throwable t) {
262       ExceptionFunctions.traceCauseException(t).printStackTrace();
263
264       throw new SessionFailure("MirBasicPostingSessionHandler.subsequentRequest: " + t.getMessage(), t);
265     }
266   }
267
268   public void initializeCommentPosting(Request aRequest, Session aSession, Response aResponse) throws SessionFailure, SessionExc {
269     String articleId = aRequest.getParameter("to_media");
270     if (articleId==null)
271       articleId = aRequest.getParameter("aid");
272
273     if (articleId==null)
274       throw new SessionExc("initializeCommentPosting: article id not set!");
275
276     aSession.setAttribute("to_media", articleId);
277     processCommentPosting(aRequest, aSession, aResponse);
278   };
279
280   public void returnValidationErrors(Request aRequest, Session aSession, Response aResponse, List aValidationErrors) throws SessionFailure, SessionExc {
281     aResponse.setResponseValue("errors", aValidationErrors);
282     aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate"));
283   };
284
285   public void processCommentPosting(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
286     if (MirGlobal.abuse().getOpenPostingPassword()) {
287       String password = generateOnetimePassword();
288       aSession.setAttribute("password", password);
289       aResponse.setResponseValue("password", password);
290       aResponse.setResponseValue("passwd", password);
291     }
292     else {
293       aResponse.setResponseValue("password", null);
294     }
295
296     aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.EditTemplate"));
297   };
298
299   public void processMediaFile(Request aRequest, Session aSession, EntityComment aComment, UploadedFile aFile) throws SessionExc, SessionFailure {
300     try {
301       Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, new HashMap());
302       finishMedia(aRequest, aSession, aFile, mediaItem);
303       mediaItem.update();
304       commentToMedia.addMedia(aComment.getId(), mediaItem.getId());
305     }
306     catch (Throwable t) {
307       throw new SessionFailure(t);
308     }
309   }
310
311   public void finishMedia(Request aRequest, Session aSession, UploadedFile aFile, Entity aMedia) throws SessionExc, SessionFailure {
312   }
313
314   public void finishComment(Request aRequest, Session aSession, EntityComment aComment) throws SessionExc, SessionFailure {
315     if (aSession.getAttribute("to_media") == null)
316       throw new SessionExc("missing to_media");
317
318     aComment.setValueForProperty("is_published", "1");
319     aComment.setValueForProperty("to_comment_status", "1");
320     aComment.setValueForProperty("is_html","0");
321     aComment.setValueForProperty("to_media", (String) aSession.getAttribute("to_media"));
322   };
323
324   public void addMedia(Request aRequest, Session aSession, EntityComment aComment)  throws SessionExc, SessionFailure {
325   }
326
327   public void afterCommentPosting(Request aRequest, Session aSession, Response aResponse, EntityComment aComment) {
328     DatabaseContent.getInstance().setUnproduced("id=" + aComment.getValue("to_media"));
329     aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.DoneTemplate"));
330   };
331
332   public void afterDuplicateCommentPosting(Request aRequest, Session aSession, Response aResponse, EntityComment aComment) {
333     aResponse.setResponseGenerator(configuration.getString("Localizer.OpenSession.comment.DupeTemplate"));
334   };
335
336   public class ValidationError {
337     private String field;
338     private String message;
339     private List parameters;
340
341     public ValidationError(String aField, String aMessage) {
342       this (aField, aMessage, new String[] {});
343     }
344
345     public ValidationError(String aField, String aMessage, Object aParameter) {
346       this (aField, aMessage, new Object[] {aParameter});
347     }
348
349     public ValidationError(String aField, String aMessage, Object[] aParameters) {
350       field = aField;
351       message = aMessage;
352       parameters = Arrays.asList(aParameters);
353     }
354
355     public String getMessage() {
356       return message;
357     }
358
359     public String getField() {
360       return field;
361     }
362
363     public List getParameters() {
364       return parameters;
365     }
366   }
367
368
369
370 }