proper handling of exceptions all around. especially for the media stuff.
[mir.git] / source / mircoders / servlet / ServletModuleOpenIndy.java
1 package mircoders.servlet;
2
3 import java.io.*;
4 import java.lang.*;
5 import java.sql.*;
6 import java.util.*;
7 import java.net.*;
8 import java.lang.reflect.*;
9 import javax.servlet.*;
10 import javax.servlet.http.*;
11
12 import freemarker.template.*;
13 import com.oreilly.servlet.multipart.*;
14 import com.oreilly.servlet.*;
15
16 import mir.servlet.*;
17 import mir.module.*;
18 import mir.misc.*;
19 import mir.entity.*;
20 import mir.storage.*;
21 import mir.media.*;
22
23 import mircoders.entity.*;
24 import mircoders.storage.*;
25 import mircoders.module.*;
26 import mircoders.producer.*;
27
28 /*
29  *  ServletModuleOpenIndy -
30  *   is the open-access-servlet, which is responsible for
31  *    adding comments to articles &
32  *    open-postings to the newswire
33  *
34  * @author RK
35  */
36
37 public class ServletModuleOpenIndy extends ServletModule
38 {
39
40   private String          commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
41   private String          postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
42   private ModuleContent   contentModule;
43   private ModuleImages    imageModule;
44   private ModuleTopics    themenModule;
45   private String          directOp ="yes";
46
47   // Singelton / Kontruktor
48   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
49   public static ServletModule getInstance() { return instance; }
50
51   private ServletModuleOpenIndy() {
52     try {
53       theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
54       commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
55       commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
56       commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
57       postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
58       postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
59       postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
60       directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
61       mainModule = new ModuleComment(DatabaseComment.getInstance());
62       contentModule = new ModuleContent(DatabaseContent.getInstance());
63       themenModule = new ModuleTopics(DatabaseTopics.getInstance());
64       imageModule = new ModuleImages(DatabaseImages.getInstance());
65       defaultAction="addposting";
66     }
67     catch (StorageObjectException e) {
68         theLog.printError("servletmoduleopenindy could not be initialized");
69     }
70   }
71
72
73   /**
74    *  Method for making a comment
75    */
76
77   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
78   {
79     String aid = req.getParameter("aid"); // the article id the comment will belong to
80     if (aid!=null && !aid.equals(""))
81     {
82       SimpleHash mergeData = new SimpleHash();
83       // ok, article
84       mergeData.put("aid", aid);
85       deliver(req, res, mergeData, commentFormTemplate);
86     }
87     else throw new ServletModuleException("aid not set!");
88   }
89
90   /**
91    *  Method for inserting a comment into the Database and delivering
92    *  the commentDone Page
93    */
94
95   public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
96   {
97     String aid = req.getParameter("to_media"); // the article id the comment will belong to
98     if (aid!=null && !aid.equals(""))
99     {
100       // ok, collecting data from form
101       try {
102         HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
103        
104         //no html in comments(for now)
105         for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
106             String k=(String)i.next();
107             String v=(String)withValues.get(k);
108             
109             withValues.put(k,StringUtil.removeHTMLTags(v));
110         }
111         withValues.put("is_published","1");
112
113         // inserting into database
114         String id = mainModule.add(withValues);
115         theLog.printDebugInfo("id: "+id);
116         //insert was not successfull
117         if(id==null){
118           deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
119         }
120         
121         // producing new page
122         new ProducerContent().handle(null, null, true, false, aid);
123
124         // sync the server
125         int exitValue = Helper.rsync();
126         theLog.printDebugInfo("rsync:"+exitValue);
127
128         // redirecting to url
129         // should implement back to article
130         SimpleHash mergeData = new SimpleHash();
131         deliver(req, res, mergeData, commentFormDoneTemplate);
132       }
133       catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
134       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
135
136     }
137     else throw new ServletModuleException("aid not set!");
138
139   }
140
141   /**
142    *  Method for delivering the form-Page for open posting
143    */
144
145   public void addposting(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
146   {
147     SimpleHash mergeData = new SimpleHash();
148     String numOfMedia = req.getParameter("medianum");
149     if(numOfMedia==null||numOfMedia.equals("")){
150       numOfMedia="1";
151     }
152     
153     int mediaNum = Integer.parseInt(numOfMedia);
154     SimpleList mediaFields = new SimpleList();
155     for(int i =0; i<mediaNum;i++){
156       Integer mNum = new Integer(i+1);
157       mediaFields.add(mNum.toString());
158     }
159     mergeData.put("medianum",numOfMedia);
160     mergeData.put("mediafields",mediaFields);
161     
162     
163     /** @todo popups missing */
164     try{
165       mergeData.put("languagePopUpData",DatabaseLanguage.getInstance().getPopupData());
166       mergeData.put("themenPopupData", themenModule.getTopicsAsSimpleList());
167     } catch (Exception e) {
168       theLog.printError("languagePopUpData or getTopicslist failed");
169       throw new ServletModuleException("smod -- openindy -- getting language or topics failed: "+e.toString());
170     }
171     deliver(req, res, mergeData, postingFormTemplate);
172   }
173
174   /**
175    *  Method for inserting an open posting into the Database and delivering
176    *  the postingDone Page
177    */
178
179   public void insposting(HttpServletRequest req, HttpServletResponse res)
180     throws ServletModuleException, ServletModuleUserException
181   {
182     SimpleHash mergeData = new SimpleHash();
183     boolean setMedia=false;
184
185     try {
186       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
187           
188       HashMap withValues = mp.getParameters();
189
190       if ((((String)withValues.get("title")).length() == 0) ||
191           (((String)withValues.get("description")).length() == 0) ||
192           (((String)withValues.get("content_data")).length() == 0))
193             throw new ServletModuleUserException("Missing field");
194       
195       // call the routines that escape html
196
197       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
198         String k=(String)i.next();
199         String v=(String)withValues.get(k);
200         
201         if (k.equals("content_data")){
202           //this doesn't quite work yet, so for now, all html goes
203           //withValues.put(k,StringUtil.approveHTMLTags(v));
204           //withValues.put(k,StringUtil.removeHTMLTags(v));
205         } else {
206           withValues.put(k,StringUtil.removeHTMLTags(v));
207         }
208         
209       }
210
211       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
212       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
213       withValues.put("is_produced", "0");
214       // op-articles are not immediatly published
215       // we don't know that all is good yet (media, title is present, etc..)
216       withValues.put("is_published","0");
217       // if op direct article-type == newswire
218       if (directOp.equals("yes")) withValues.put("to_article_type","1");
219       
220       // owner is openposting user
221       withValues.put("to_publisher","1");
222       if (withValues.get("creator").toString().equals(""))
223         withValues.put("creator","Anonym");
224
225       // inserting  content into database
226       String cid = contentModule.add(withValues);
227       theLog.printDebugInfo("id: "+cid);
228       //insert was not successfull
229       if(cid==null){
230         //How do we know that it was not succesful cause of a 
231         //dupe, what if it failed cause of "No space left on device"?
232         //Or is there something I am missing? Wouldn't it be better
233         //to have an explicit dupe check and then insert? I have no
234         //idea what I am talking about. this comment is in case
235         //I forget to explicitely ask. -mh
236         deliver(req, res, mergeData, postingFormDupeTemplate);
237       }
238
239       String[] to_topicsArr = mp.getParameterValues("to_topic");
240       if (to_topicsArr != null && to_topicsArr.length > 0) {
241         try{
242           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
243           theLog.printError("setting content_x_topic success");
244         } catch (Exception e) {
245           theLog.printError("setting content_x_topic failed");
246           contentModule.deleteById(cid);
247           throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
248         } //end try
249       } //end if
250         
251       // if op contains uploaddata
252       String mediaId=null;
253       int i=1;
254       for(Iterator it = mp.requestList.iterator(); it.hasNext();){
255         MpRequest mpReq = (MpRequest)it.next();
256         String fileName = mpReq.getFilename();
257
258         //get the content-type from what the client browser
259         //sends us. (the "Oreilly method")
260         String contentType = mpReq.getContentType();
261
262         theLog.printError("FROM BROWSER: "+contentType);
263
264         //if the client browser sent us unknown (text/plain is default)
265         //or if we got application/octet-stream, it's possible that
266         //the browser is in error, better check against the file extension
267         if (contentType.equals("text/plain") || 
268             contentType.equals("application/octet-stream")) {
269             /** 
270              * This is just a temporary way to get the content-type via
271              * the .extension , we could maybe use a magic method, by looking
272              * at the header (first few bytes) of the file. (like the file(1)
273              * command).
274              * The Oreilly method  relies on the content-type that the client 
275              * browser sends and that sometimes is application-octet stream with
276              * broken/mis-configured browsers.
277              * 
278              * The map file should be Mir/content-types.properties, it's the 
279              * default Sun Java file with some additional entries that it did 
280              * not have. So if you support a new media type you have to make 
281              * sure that it is in this file -mh
282              */
283             contentType = FileUtil.guessContentTypeFromName(fileName);
284             theLog.printError("tYPE: "+contentType);
285             if (contentType==null)
286                 contentType = "text/plain"; // rfc1867 says this is the default
287         }
288         HashMap mediaValues = new HashMap();
289
290         theLog.printError("CONTENT TYPE IS: "+contentType);
291         
292         if (contentType.equals("text/plain") || 
293             contentType.equals("application/octet-stream")) {
294           throw new ServletModuleUserException("One or more files of unrecognized types");
295         }
296
297         String mediaTitle=(String)withValues.get("media_title"+i);
298         i++;
299
300         if (mediaTitle==null)
301             mediaTitle = (String)withValues.get("title");
302
303         mediaValues.put("title", mediaTitle);
304         mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
305         mediaValues.put("to_publisher", "1"); // op user
306         mediaValues.put("to_media_folder", "7"); // op media_folder
307         mediaValues.put("is_produced", "0");
308         mediaValues.put("is_published","0");
309
310         //the where clause to find the media_type entry
311         //from the content-type.
312         //we use the media type entry to lookup the 
313         //media Handler/Storage classes
314         String wc = " mime_type='"+contentType+"'";
315
316         EntityList mediaTypesList = DatabaseMediaType.getInstance().selectByWhereClause(wc);
317
318         String mediaTypeId = null;
319         String mediaStorageName = null;
320         String mediaHandlerName = null;
321  
322         //if we found an entry matching the
323         //content-type int the table.
324         if (mediaTypesList.size() > 0) {
325           //get the class names from the media_type table.
326           mediaTypeId = mediaTypesList.elementAt(0).getId();
327           mediaStorageName = mediaTypesList.elementAt(0).getValue("tablename");
328           mediaHandlerName = mediaTypesList.elementAt(0).getValue("classname");
329           mediaValues.put("to_media_type",mediaTypeId);
330          
331           //load the classes via reflection
332           String MediaId;
333           Entity mediaEnt = null;
334           try {
335             Class mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
336             Method m = mediaStorageClass.getMethod("getInstance", null);
337             Database mediaStorage = (Database)m.invoke(null, null);
338             mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
339             mediaEnt.setStorage(mediaStorage);
340             mediaEnt.setValues(mediaValues);
341             mediaId = mediaEnt.insert();
342
343             Class mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
344             MirMedia mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
345             //save and store the media data/metadata
346             mediaHandler.set(mpReq.getMedia(), mediaEnt,mediaTypesList.elementAt(0));
347
348             //were done with mpReq at this point, dereference it.
349             //as it contains mucho mem. -mh 01.10.2001
350             mpReq=null;
351               
352             //we got this far, associate the media to the article
353             theLog.printError("ID"+mediaId);
354             mediaEnt.setValueForProperty("is_published","1");
355             mediaEnt.update();
356             new ProducerMedia().handle(null,null,false,false,mediaId);
357             DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
358           } catch (Exception e) {
359             theLog.printError("setting media failed: "+e.toString());
360             contentModule.deleteById(cid);
361             throw new ServletModuleException("setting media failed: "+e.toString());
362           }
363
364         } else {
365           contentModule.deleteById(cid);
366           theLog.printDebugInfo("Wrong file type uploaded!: " + fileName);
367           throw new ServletModuleUserException("One or more files of unrecognized types");
368         } // end if-else mediaTypesList.size() > 0
369           
370       } //end for Iterator...
371
372       //if we're here all is ok...
373       EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
374       contentEnt.setValueForProperty("is_published","1");
375       contentEnt.update();
376
377       //dereference mp. -mh
378       mp=null;
379
380       // producing openpostinglist
381       new ProducerOpenPosting().handle(null,null,false,false);
382       // producing new page
383       new ProducerContent().handle(null, null, false, false,cid);
384       //if direct op producing startpage
385       if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
386       
387       // sync the server
388       //should be configureable
389       int exitValue = Helper.rsync();
390       theLog.printDebugInfo("rsync: "+exitValue);
391
392     }
393     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
394     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
395     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
396
397     deliver(req, res, mergeData, postingFormDoneTemplate);
398   }
399
400 }
401
402