1 package mircoders.servlet;
8 import java.lang.reflect.*;
9 import javax.servlet.*;
10 import javax.servlet.http.*;
12 import freemarker.template.*;
13 import com.oreilly.servlet.multipart.*;
14 import com.oreilly.servlet.*;
23 import mircoders.entity.*;
24 import mircoders.storage.*;
25 import mircoders.module.*;
26 import mircoders.producer.*;
29 * ServletModuleOpenIndy -
30 * is the open-access-servlet, which is responsible for
31 * adding comments to articles &
32 * open-postings to the newswire
37 public class ServletModuleOpenIndy extends ServletModule
40 private String commentFormTemplate, commentFormDoneTemplate,
41 commentFormDupeTemplate;
42 private String postingFormTemplate, postingFormDoneTemplate,
43 postingFormDupeTemplate;
44 private ModuleContent contentModule;
45 private ModuleImages imageModule;
46 private ModuleTopics themenModule;
47 private String directOp ="yes";
49 // Singelton / Kontruktor
50 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
51 public static ServletModule getInstance() { return instance; }
53 private ServletModuleOpenIndy() {
55 theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.OpenIndy.Logfile"));
56 commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
57 commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
58 commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
59 postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
60 postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
61 postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
62 directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
63 mainModule = new ModuleComment(DatabaseComment.getInstance());
64 contentModule = new ModuleContent(DatabaseContent.getInstance());
65 themenModule = new ModuleTopics(DatabaseTopics.getInstance());
66 imageModule = new ModuleImages(DatabaseImages.getInstance());
67 defaultAction="addposting";
69 catch (StorageObjectException e) {
70 theLog.printError("servletmoduleopenindy could not be initialized");
76 * Method for making a comment
79 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
81 String aid = req.getParameter("aid"); // the article id the comment will belong to
82 if (aid!=null && !aid.equals(""))
84 SimpleHash mergeData = new SimpleHash();
86 mergeData.put("aid", aid);
87 deliver(req, res, mergeData, commentFormTemplate);
89 else throw new ServletModuleException("aid not set!");
93 * Method for inserting a comment into the Database and delivering
94 * the commentDone Page
97 public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
99 String aid = req.getParameter("to_media"); // the article id the comment will belong to
100 if (aid!=null && !aid.equals(""))
102 // ok, collecting data from form
104 HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
106 //no html in comments(for now)
107 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
108 String k=(String)i.next();
109 String v=(String)withValues.get(k);
111 withValues.put(k,StringUtil.removeHTMLTags(v));
113 withValues.put("is_published","1");
115 // inserting into database
116 String id = mainModule.add(withValues);
117 theLog.printDebugInfo("id: "+id);
118 //insert was not successfull
120 deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
123 // producing new page
124 new ProducerContent().handle(null, null, true, false, aid);
127 int exitValue = Helper.rsync();
128 theLog.printDebugInfo("rsync:"+exitValue);
130 // redirecting to url
131 // should implement back to article
132 SimpleHash mergeData = new SimpleHash();
133 deliver(req, res, mergeData, commentFormDoneTemplate);
135 catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
136 catch (ModuleException e) { throw new ServletModuleException(e.toString());}
139 else throw new ServletModuleException("aid not set!");
144 * Method for delivering the form-Page for open posting
147 public void addposting(HttpServletRequest req, HttpServletResponse res)
148 throws ServletModuleException {
149 SimpleHash mergeData = new SimpleHash();
150 String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
151 String numOfMedia = req.getParameter("medianum");
152 if(numOfMedia==null||numOfMedia.equals("")){
154 } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
155 numOfMedia = maxMedia;
158 int mediaNum = Integer.parseInt(numOfMedia);
159 SimpleList mediaFields = new SimpleList();
160 for(int i =0; i<mediaNum;i++){
161 Integer mNum = new Integer(i+1);
162 mediaFields.add(mNum.toString());
164 mergeData.put("medianum",numOfMedia);
165 mergeData.put("mediafields",mediaFields);
168 SimpleHash extraInfo = new SimpleHash();
169 /** @todo popups missing */
171 SimpleList popUpData = DatabaseLanguage.getInstance().getPopupData();
172 extraInfo.put("languagePopUpData", popUpData );
173 extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
174 } catch (Exception e) {
175 theLog.printError("languagePopUpData or getTopicslist failed "
177 throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
180 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
184 * Method for inserting an open posting into the Database and delivering
185 * the postingDone Page
188 public void insposting(HttpServletRequest req, HttpServletResponse res)
189 throws ServletModuleException, ServletModuleUserException
191 SimpleHash mergeData = new SimpleHash();
192 boolean setMedia=false;
193 boolean setTopic = false;
196 WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
198 HashMap withValues = mp.getParameters();
200 if ((((String)withValues.get("title")).length() == 0) ||
201 (((String)withValues.get("description")).length() == 0) ||
202 (((String)withValues.get("content_data")).length() == 0))
203 throw new ServletModuleUserException("Missing field");
205 // call the routines that escape html
207 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
208 String k=(String)i.next();
209 String v=(String)withValues.get(k);
211 if (k.equals("content_data")){
212 //this doesn't quite work yet, so for now, all html goes
213 //withValues.put(k,StringUtil.approveHTMLTags(v));
214 //withValues.put(k,StringUtil.removeHTMLTags(v));
216 withValues.put(k,StringUtil.removeHTMLTags(v));
221 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
222 withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
223 withValues.put("is_produced", "0");
224 // op-articles are not immediatly published
225 // we don't know that all is good yet (media, title is present, etc..)
226 withValues.put("is_published","0");
227 // if op direct article-type == newswire
228 if (directOp.equals("yes")) withValues.put("to_article_type","1");
230 // owner is openposting user
231 withValues.put("to_publisher","1");
232 if (withValues.get("creator").toString().equals(""))
233 withValues.put("creator","Anonym");
235 // inserting content into database
236 String cid = contentModule.add(withValues);
237 theLog.printDebugInfo("id: "+cid);
238 //insert was not successfull
240 //How do we know that it was not succesful cause of a
241 //dupe, what if it failed cause of "No space left on device"?
242 //Or is there something I am missing? Wouldn't it be better
243 //to have an explicit dupe check and then insert? I have no
244 //idea what I am talking about. this comment is in case
245 //I forget to explicitely ask. -mh
246 deliver(req, res, mergeData, postingFormDupeTemplate);
249 String[] to_topicsArr = mp.getParameterValues("to_topic");
251 if (to_topicsArr != null && to_topicsArr.length > 0) {
253 DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
255 } catch (Exception e) {
256 theLog.printError("setting content_x_topic failed");
257 contentModule.deleteById(cid);
258 throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
262 // if op contains uploaddata
265 for(Iterator it = mp.requestList.iterator(); it.hasNext();){
266 MpRequest mpReq = (MpRequest)it.next();
267 String fileName = mpReq.getFilename();
269 //get the content-type from what the client browser
270 //sends us. (the "Oreilly method")
271 String contentType = mpReq.getContentType();
273 theLog.printInfo("FROM BROWSER: "+contentType);
275 //if the client browser sent us unknown (text/plain is default)
276 //or if we got application/octet-stream, it's possible that
277 //the browser is in error, better check against the file extension
278 if (contentType.equals("text/plain") ||
279 contentType.equals("application/octet-stream")) {
281 * Fallback to finding the mime-type through the standard ServletApi
282 * ServletContext getMimeType() method.
284 * This is a way to get the content-type via the .extension,
285 * we could maybe use a magic method as an additional method of
286 * figuring out the content-type, by looking at the header (first
287 * few bytes) of the file. (like the file(1) command). We could
288 * also call the "file" command through Runtime. This is an
289 * option that I almost prefer as it is already implemented and
290 * exists with an up-to-date map on most modern Unix like systems.
291 * I haven't found a really nice implementation of the magic method
294 * The first method we try thought is the "Oreilly method". It
295 * relies on the content-type that the client browser sends and
296 * that sometimes is application-octet stream with
297 * broken/mis-configured browsers.
299 * The map file we use for the extensions is the standard web-app
300 * deployment descriptor file (web.xml). See Mir's web.xml or see
301 * your Servlet containers (most likely Tomcat) documentation.
302 * So if you support a new media type you have to make sure that
303 * it is in this file -mh
306 (ServletContext)MirConfig.getPropAsObject("ServletContext");
307 contentType = ctx.getMimeType(fileName);
308 if (contentType==null)
309 contentType = "text/plain"; // rfc1867 says this is the default
311 HashMap mediaValues = new HashMap();
313 theLog.printInfo("CONTENT TYPE IS: "+contentType);
315 if (contentType.equals("text/plain") ||
316 contentType.equals("application/octet-stream")) {
317 contentModule.deleteById(cid);
318 _throwBadContentType(fileName, contentType);
321 String mediaTitle=(String)withValues.get("media_title"+i);
324 if (mediaTitle==null)
325 mediaTitle = (String)withValues.get("title");
327 mediaValues.put("title", mediaTitle);
328 mediaValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
329 mediaValues.put("to_publisher", "1"); // op user
330 mediaValues.put("to_media_folder", "7"); // op media_folder
331 mediaValues.put("is_produced", "0");
332 mediaValues.put("is_published","0");
334 // @todo this should probably be moved to DatabaseMediaType -mh
335 String[] cTypeSplit = StringUtil.split(contentType, "/");
336 String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
338 DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
339 EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
341 String mediaTypeId = null;
342 MirMedia mediaHandler;
343 Database mediaStorage;
344 ProducerMedia mediaProducer;
346 //if we didn't find an entry matching the
347 //content-type int the table.
348 if (mediaTypesList.size() == 0) {
349 contentModule.deleteById(cid);
350 _throwBadContentType(fileName, contentType);
353 Entity mediaType = null;
354 Entity mediaType2 = null;
356 // find out if we an exact content-type match if so take it.
357 // otherwise try to match majortype/*
358 // @todo this should probably be moved to DatabaseMediaType -mh
359 for(int j=0;j<mediaTypesList.size();j++) {
360 if(contentType.equals(
361 mediaTypesList.elementAt(j).getValue("mime_type")))
362 mediaType = mediaTypesList.elementAt(j);
363 else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
364 cTypeSplit[0]+"/*") )
365 mediaType2= mediaTypesList.elementAt(j);
368 if ( (mediaType == null) && (mediaType2 == null) ) {
369 contentModule.deleteById(cid);
370 _throwBadContentType(fileName, contentType);
372 else if( (mediaType == null) && (mediaType2 != null) )
373 mediaType = mediaType2;
375 //get the class names from the media_type table.
376 mediaTypeId = mediaType.getId();
378 // ############### @todo: merge these and the getURL call into one
379 // getURL helper call that just takes the Entity as a parameter
380 // along with media_type
381 mediaHandler = MediaHelper.getHandler(mediaType);
382 mediaStorage = MediaHelper.getStorage(mediaType,
383 "mircoders.storage.Database");
384 Class prodCls = Class.forName("mircoders.producer.Producer"
385 +mediaType.getValue("tablename"));
386 mediaProducer = (ProducerMedia)prodCls.newInstance();
387 } catch (Exception e) {
388 theLog.printError("getting media handler failed: "+e.toString());
389 contentModule.deleteById(cid);
390 throw new ServletModuleException("getting media handler failed: "
394 mediaValues.put("to_media_type",mediaTypeId);
396 //load the classes via reflection
398 Entity mediaEnt = null;
400 mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
401 mediaEnt.setStorage(mediaStorage);
402 mediaEnt.setValues(mediaValues);
403 mediaId = mediaEnt.insert();
405 //save and store the media data/metadata
406 mediaHandler.set(mpReq.getMedia(), mediaEnt,
409 //were done with mpReq at this point, dereference it.
410 //as it contains mucho mem. -mh 01.10.2001
413 //we got this far, associate the media to the article
414 mediaEnt.setValueForProperty("is_published","1");
417 mediaProducer.handle(null, null, false, false, mediaId);
418 DatabaseContentToMedia.getInstance().addMedia(cid,mediaId);
419 } catch (Exception e) {
420 theLog.printError("setting media failed: "+e.toString());
421 contentModule.deleteById(cid);
422 throw new ServletModuleException("setting media failed: "
426 } //end for Iterator...
428 //if we're here all is ok...
429 EntityContent contentEnt = (EntityContent)contentModule.getById(cid);
430 contentEnt.setValueForProperty("is_published","1");
434 //dereference mp. -mh
437 // producing openpostinglist
438 new ProducerOpenPosting().handle(null,null,false,false);
439 // producing new page
440 new ProducerContent().handle(null, null, false, false,cid);
441 //if direct op producing startpage
442 if (directOp.equals("yes")) new ProducerStartPage().handle(null,null);
444 //produce the topicPages if set
445 //should be more intelligent
446 //if(setTopic==true) new ProducerTopics().handle(null,null);
449 //should be configureable
450 int exitValue = Helper.rsync();
451 theLog.printDebugInfo("rsync: "+exitValue);
454 catch (IOException e) { throw new ServletModuleException("IOException: "+ e.toString());}
455 catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
456 catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.toString());}
458 deliver(req, res, mergeData, postingFormDoneTemplate);
461 private void _throwBadContentType (String fileName, String contentType)
462 throws ServletModuleUserException {
464 theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
466 throw new ServletModuleUserException("The file you uploaded is of the "
467 +"following mime-type: "+contentType
468 +", we do not support this mime-type. "
469 +"Error One or more files of unrecognized type. Sorry");