language for comments now properly supported
[mir.git] / source / mircoders / servlet / ServletModuleOpenIndy.java
1 /*\r
2  * Copyright (C) 2001, 2002  The Mir-coders group\r
3  *\r
4  * This file is part of Mir.\r
5  *\r
6  * Mir is free software; you can redistribute it and/or modify\r
7  * it under the terms of the GNU General Public License as published by\r
8  * the Free Software Foundation; either version 2 of the License, or\r
9  * (at your option) any later version.\r
10  *\r
11  * Mir is distributed in the hope that it will be useful,\r
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14  * GNU General Public License for more details.\r
15  *\r
16  * You should have received a copy of the GNU General Public License\r
17  * along with Mir; if not, write to the Free Software\r
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
19  *\r
20  * In addition, as a special exception, The Mir-coders gives permission to link\r
21  * the code of this program with the com.oreilly.servlet library, any library\r
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
24  * the above that use the same license as the above), and distribute linked\r
25  * combinations including the two.  You must obey the GNU General Public\r
26  * License in all respects for all of the code used other than the above\r
27  * mentioned libraries.  If you modify this file, you may extend this exception\r
28  * to your version of the file, but you are not obligated to do so.  If you do\r
29  * not wish to do so, delete this exception statement from your version.\r
30  */\r
31 \r
32 package mircoders.servlet;\r
33 \r
34 import java.io.*;\r
35 import java.lang.*;\r
36 import java.sql.*;\r
37 import java.util.*;\r
38 import java.net.*;\r
39 import java.lang.reflect.*;\r
40 import javax.servlet.*;\r
41 import javax.servlet.http.*;\r
42 \r
43 import freemarker.template.*;\r
44 import com.oreilly.servlet.multipart.*;\r
45 import com.oreilly.servlet.*;\r
46 \r
47 import org.xml.sax.InputSource;\r
48 import org.xml.sax.XMLReader;\r
49 \r
50 import org.apache.fop.apps.Driver;\r
51 import org.apache.fop.apps.Version;\r
52 import org.apache.fop.apps.XSLTInputHandler;\r
53 \r
54 import org.apache.lucene.analysis.standard.StandardAnalyzer;\r
55 import org.apache.lucene.search.*;\r
56 import org.apache.lucene.document.Document;\r
57 import org.apache.lucene.document.Field;\r
58 import org.apache.lucene.analysis.standard.*;\r
59 import org.apache.lucene.queryParser.*;\r
60 \r
61 import org.apache.log.*;\r
62 \r
63 import mir.servlet.*;\r
64 import mir.module.*;\r
65 import mir.misc.*;\r
66 import mir.entity.*;\r
67 import mir.storage.*;\r
68 import mir.media.*;\r
69 import mir.log.*;\r
70 \r
71 import mircoders.entity.*;\r
72 import mircoders.storage.*;\r
73 import mircoders.module.*;\r
74 import mircoders.producer.*;\r
75 import mircoders.media.MediaRequest;\r
76 import mircoders.global.*;\r
77 import mircoders.localizer.*;\r
78 import mircoders.search.*;\r
79 \r
80 /*\r
81  *  ServletModuleOpenIndy -\r
82  *   is the open-access-servlet, which is responsible for\r
83  *    adding comments to articles &\r
84  *    open-postings to the newswire\r
85  *\r
86  * @author mir-coders group\r
87  * @version $Id: ServletModuleOpenIndy.java,v 1.50 2002/12/14 17:36:17 zapata Exp $\r
88  *\r
89  */\r
90 \r
91 public class ServletModuleOpenIndy extends ServletModule\r
92 {\r
93 \r
94   private String        commentFormTemplate, commentFormDoneTemplate,\r
95     commentFormDupeTemplate;\r
96   private String        postingFormTemplate, postingFormDoneTemplate,\r
97     postingFormDupeTemplate;\r
98   private String        searchResultsTemplate;\r
99   private ModuleContent contentModule;\r
100   private ModuleComment commentModule;\r
101   private ModuleImages  imageModule;\r
102   private ModuleTopics  themenModule;\r
103   private String        directOp ="yes";\r
104   private String        passwdProtection ="yes";\r
105   // Singelton / Kontruktor\r
106   private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();\r
107   public static ServletModule getInstance() { return instance; }\r
108 \r
109   private ServletModuleOpenIndy() {\r
110     try {\r
111       logger = new LoggerWrapper("ServletModule.OpenIndy");\r
112 \r
113       commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");\r
114       commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");\r
115       commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");\r
116       postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");\r
117       postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");\r
118       postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");\r
119       searchResultsTemplate = MirConfig.getProp("ServletModule.OpenIndy.SearchResultsTemplate");\r
120       directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();\r
121       passwdProtection = MirConfig.getProp("PasswdProtection").toLowerCase();\r
122       mainModule = new ModuleComment(DatabaseComment.getInstance());\r
123       contentModule = new ModuleContent(DatabaseContent.getInstance());\r
124       themenModule = new ModuleTopics(DatabaseTopics.getInstance());\r
125       imageModule = new ModuleImages(DatabaseImages.getInstance());\r
126       defaultAction="addposting";\r
127 \r
128     }\r
129     catch (StorageObjectException e) {\r
130       logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());\r
131     }\r
132   }\r
133 \r
134 \r
135   /**\r
136    *  Method for making a comment\r
137    */\r
138 \r
139   public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException\r
140   {\r
141     String aid = req.getParameter("aid"); // the article id the comment will belong to\r
142     String language = req.getParameter("language");\r
143 \r
144     if (aid!=null && !aid.equals("")) {\r
145       try {\r
146         SimpleHash mergeData = new SimpleHash();\r
147 \r
148         // onetimepasswd\r
149         if (passwdProtection.equals("yes")) {\r
150           String passwd = this.createOneTimePasswd();\r
151           System.out.println(passwd);\r
152           HttpSession session = req.getSession(false);\r
153           session.setAttribute("passwd", passwd);\r
154           mergeData.put("passwd", passwd);\r
155         }\r
156 \r
157         if (language != null) {\r
158           HttpSession session = req.getSession(false);\r
159           session.setAttribute("Locale", new Locale(language, ""));\r
160           session.setAttribute("passwd", language);\r
161         }\r
162 \r
163         mergeData.put("aid", aid);\r
164 \r
165         SimpleHash extraInfo = new SimpleHash();\r
166         extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());\r
167 \r
168         deliver(req, res, mergeData, extraInfo, commentFormTemplate);\r
169       }\r
170       catch (Throwable t) {\r
171         throw new ServletModuleException("ServletModuleOpenIndy.addcomment: " + t.getMessage());\r
172       }\r
173     }\r
174     else throw new ServletModuleException("aid not set!");\r
175   }\r
176 \r
177   /**\r
178    *  Method for inserting a comment into the Database and delivering\r
179    *  the commentDone Page\r
180    */\r
181 \r
182   public void inscomment(HttpServletRequest req, HttpServletResponse res)\r
183     throws ServletModuleException,ServletModuleUserException\r
184   {\r
185     String aid = req.getParameter("to_media"); // the article id the comment will belong to\r
186     if (aid!=null && !aid.equals(""))\r
187       {\r
188         // ok, collecting data from form\r
189         try {\r
190           HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());\r
191 \r
192           //no html in comments(for now)\r
193           for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){\r
194             String k=(String)i.next();\r
195             String v=(String)withValues.get(k);\r
196 \r
197             withValues.put(k,StringUtil.removeHTMLTags(v));\r
198           }\r
199           withValues.put("is_published","1");\r
200 \r
201           //checking the onetimepasswd\r
202           if(passwdProtection.equals("yes")){\r
203             HttpSession session = req.getSession(false);\r
204             String sessionPasswd = (String)session.getAttribute("passwd");\r
205             if ( sessionPasswd == null){\r
206               throw new ServletModuleUserException("Lost password");\r
207             }\r
208             String passwd = req.getParameter("passwd");\r
209             if ( passwd == null || (!sessionPasswd.equals(passwd))) {\r
210               throw new ServletModuleUserException("Missing password");\r
211             }\r
212             session.invalidate();\r
213           }\r
214 \r
215           // inserting into database\r
216           String id = mainModule.add(withValues);\r
217           logger.debug("id: "+id);\r
218           //insert was not successfull\r
219           if(id==null){\r
220             deliver(req, res, new SimpleHash(), commentFormDupeTemplate);\r
221           } else {\r
222             DatabaseContent.getInstance().setUnproduced("id="+aid);\r
223 \r
224             try {\r
225               EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);\r
226               MirGlobal.localizer().openPostings().afterCommentPosting(comment);\r
227             }\r
228             catch (Throwable t) {\r
229               throw new ServletModuleException(t.getMessage());\r
230             }\r
231           }\r
232 \r
233           // redirecting to url\r
234           // should implement back to article\r
235           SimpleHash mergeData = new SimpleHash();\r
236           deliver(req, res, mergeData, commentFormDoneTemplate);\r
237         }\r
238         catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}\r
239         catch (ModuleException e) { throw new ServletModuleException(e.toString());}\r
240 \r
241       }\r
242     else throw new ServletModuleException("aid not set!");\r
243 \r
244   }\r
245 \r
246   /**\r
247    *  Method for delivering the form-Page for open posting\r
248    */\r
249 \r
250   public void addposting(HttpServletRequest req, HttpServletResponse res)\r
251     throws ServletModuleException {\r
252     SimpleHash mergeData = new SimpleHash();\r
253 \r
254     // onetimepasswd\r
255     if(passwdProtection.equals("yes")){\r
256       String passwd = this.createOneTimePasswd();\r
257       System.out.println(passwd);\r
258       HttpSession session = req.getSession(false);\r
259       session.setAttribute("passwd",passwd);\r
260       mergeData.put("passwd", passwd);\r
261     }\r
262 \r
263     String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");\r
264     String numOfMedia = req.getParameter("medianum");\r
265     if(numOfMedia==null||numOfMedia.equals("")){\r
266       numOfMedia="1";\r
267     } else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {\r
268       numOfMedia = maxMedia;\r
269     }\r
270 \r
271     int mediaNum = Integer.parseInt(numOfMedia);\r
272     SimpleList mediaFields = new SimpleList();\r
273     for(int i =0; i<mediaNum;i++){\r
274       Integer mNum = new Integer(i+1);\r
275       mediaFields.add(mNum.toString());\r
276     }\r
277     mergeData.put("medianum",numOfMedia);\r
278     mergeData.put("mediafields",mediaFields);\r
279 \r
280 \r
281     SimpleHash extraInfo = new SimpleHash();\r
282     try{\r
283       extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData() );\r
284       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());\r
285 \r
286       extraInfo.put("topics", themenModule.getTopicsList());\r
287 \r
288     }\r
289     catch (Exception e) {\r
290       logger.error("languagePopUpData or getTopicslist failed "+e.toString());\r
291       throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());\r
292     }\r
293 \r
294 \r
295 \r
296     deliver(req, res, mergeData, extraInfo, postingFormTemplate);\r
297   }\r
298 \r
299   /**\r
300    *  Method for inserting an open posting into the Database and delivering\r
301    *  the postingDone Page\r
302    */\r
303 \r
304   public void insposting(HttpServletRequest req, HttpServletResponse res)\r
305     throws ServletModuleException, ServletModuleUserException\r
306   {\r
307     SimpleHash mergeData = new SimpleHash();\r
308     boolean setMedia=false;\r
309     boolean setTopic = false;\r
310 \r
311     try {\r
312 \r
313       WebdbMultipartRequest mp = null;\r
314       EntityList mediaList = null;\r
315       try {\r
316         // new MediaRequest, "1" is the id for the openPosting user\r
317         MediaRequest mediaReq = new MediaRequest("1", true, true);\r
318         mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);\r
319         mediaList = mediaReq.getEntityList();\r
320       }\r
321       catch (FileHandlerUserException e) {\r
322         throw new ServletModuleUserException(e.getMessage());\r
323       }\r
324 \r
325       HashMap withValues = mp.getParameters();\r
326 \r
327       //checking the onetimepasswd\r
328       if(passwdProtection.equals("yes")){\r
329         HttpSession session = req.getSession(false);\r
330         String sessionPasswd = (String)session.getAttribute("passwd");\r
331         if ( sessionPasswd == null){\r
332           throw new ServletModuleUserException("Lost password");\r
333         }\r
334         String passwd = (String)withValues.get("passwd");\r
335         if ( passwd == null || (!sessionPasswd.equals(passwd))) {\r
336           throw new ServletModuleUserException("Missing password");\r
337         }\r
338         session.invalidate();\r
339       }\r
340 \r
341       if ((((String)withValues.get("title")).length() == 0) ||\r
342           (((String)withValues.get("description")).length() == 0) ||\r
343           (((String)withValues.get("content_data")).length() == 0))\r
344         throw new ServletModuleUserException("Missing field");\r
345 \r
346       // call the routines that escape html\r
347 \r
348       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){\r
349         String k=(String)i.next();\r
350         String v=(String)withValues.get(k);\r
351 \r
352         if (k.equals("content_data")){\r
353           //this doesn't quite work yet, so for now, all html goes\r
354           //withValues.put(k,StringUtil.approveHTMLTags(v));\r
355           //withValues.put(k,StringUtil.removeHTMLTags(v));\r
356         } else {\r
357           withValues.put(k,StringUtil.removeHTMLTags(v));\r
358         }\r
359 \r
360       }\r
361 \r
362       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
363       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));\r
364       withValues.put("is_produced", "0");\r
365       // by default stuff is published, they can be un-published through the\r
366       // admin interface.\r
367       withValues.put("is_published","1");\r
368       // if op direct article-type == newswire\r
369       if (directOp.equals("yes")) withValues.put("to_article_type","1");\r
370 \r
371       withValues.put("to_publisher","1");\r
372 \r
373       // owner is openposting user\r
374       //      ML: this is not multi-language friendly and this can be done in a template\r
375       //      if (withValues.get("creator").toString().equals(""))\r
376       //        withValues.put("creator","Anonym");\r
377 \r
378       // inserting  content into database\r
379       String cid = contentModule.add(withValues);\r
380       logger.debug("id: "+cid);\r
381       //insert was not successfull\r
382       if(cid==null){\r
383         //How do we know that it was not succesful cause of a\r
384         //dupe, what if it failed cause of "No space left on device"?\r
385         //Or is there something I am missing? Wouldn't it be better\r
386         //to have an explicit dupe check and then insert? I have no\r
387         //idea what I am talking about. this comment is in case\r
388         //I forget to explicitely ask. -mh\r
389         deliver(req, res, mergeData, postingFormDupeTemplate);\r
390       }\r
391 \r
392       String[] to_topicsArr = mp.getParameterValues("to_topic");\r
393 \r
394       if (to_topicsArr != null && to_topicsArr.length > 0) {\r
395         try{\r
396           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);\r
397           setTopic = true;\r
398         }\r
399         catch (Exception e) {\r
400           logger.error("setting content_x_topic failed");\r
401           contentModule.deleteById(cid);\r
402           throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());\r
403         } //end try\r
404       } //end if\r
405 \r
406       //if we're here all is ok... associate the media to the article\r
407       for(int i=0;i<mediaList.size();i++) {\r
408         Entity mediaEnt = (Entity)mediaList.elementAt(i);\r
409         DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());\r
410       }\r
411 \r
412       try {\r
413         MirGlobal.localizer().openPostings().afterContentPosting(\r
414                                                                  (EntityContent)contentModule.getById(cid));\r
415       }\r
416       catch (Throwable t) {\r
417         throw new ServletModuleException(t.getMessage());\r
418       }\r
419     }\r
420     catch (FileHandlerException e) { throw new ServletModuleException("MediaException: "+ e.getMessage());}\r
421     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.getMessage());}\r
422     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.getMessage());}\r
423     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.getMessage());}\r
424 \r
425     deliver(req, res, mergeData, postingFormDoneTemplate);\r
426   }\r
427 \r
428   /*\r
429    * Method for querying a lucene index\r
430    */\r
431   public void search(HttpServletRequest req, HttpServletResponse res)\r
432     throws ServletModuleException, ServletModuleUserException {\r
433     try {\r
434       int increment=10;\r
435 \r
436       HttpSession session = req.getSession(false);\r
437 \r
438       String queryString="";\r
439 \r
440       SimpleHash mergeData = new SimpleHash();\r
441 \r
442       KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted","search_date","webdb_create_formatted","webdb_create_formatted","webdb_create_formatted");\r
443       UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("","","","where","where");\r
444       TextSearchTerm creatorTerm = new TextSearchTerm("creator","search_creator","creator","creator","creator");\r
445       TextSearchTerm titleTerm = new TextSearchTerm("title","search_content","title","title","title");\r
446       TextSearchTerm descriptionTerm =  new TextSearchTerm("description","search_content","description","description","description");\r
447       ContentSearchTerm contentTerm = new ContentSearchTerm("content_data","search_content","content","","");\r
448       TopicSearchTerm topicTerm = new TopicSearchTerm();\r
449       ImagesSearchTerm imagesTerm = new ImagesSearchTerm();\r
450       AudioSearchTerm audioTerm = new AudioSearchTerm();\r
451       VideoSearchTerm videoTerm = new VideoSearchTerm();\r
452 \r
453       //make the query available to subsequent iterations\r
454 \r
455       for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {\r
456         String pName=(String)theParams.nextElement();\r
457         if (pName.startsWith("search_")){\r
458           mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));\r
459         }\r
460       }\r
461 \r
462       try{\r
463         mergeData.put("topics", themenModule.getTopicsAsSimpleList());\r
464       }\r
465       catch(ModuleException e) {\r
466         logger.debug("Can't get topics: " + e.toString());\r
467       }\r
468 \r
469       String searchSubmitValue = req.getParameter("search_submit");\r
470 \r
471       if (searchSubmitValue != null && searchSubmitValue.equals("Back")){\r
472         int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
473         int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()-increment;\r
474         if (newPosition < 0 || newPosition >= totalHits){\r
475           throw new ServletModuleUserException("newPosition: index out bounds, value was:"+(new Integer(newPosition)).toString());\r
476         }\r
477         session.setAttribute("positionInResults",new Integer(newPosition));\r
478 \r
479       }\r
480       else {\r
481         if (searchSubmitValue != null && searchSubmitValue.equals("Forward")){\r
482           int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
483           int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment;\r
484           if (newPosition < 0 || newPosition >= totalHits){\r
485             throw new ServletModuleUserException("newPosition: index out bounds, value was:"+(new Integer(newPosition)).toString());\r
486           }\r
487           session.setAttribute("positionInResults",new Integer(newPosition));\r
488 \r
489         }\r
490         else {\r
491           String indexPath=MirConfig.getProp("IndexPath");\r
492 \r
493 \r
494           String creatorFragment = creatorTerm.makeTerm(req);\r
495           if (creatorFragment != null){\r
496             queryString = queryString + " +" + creatorFragment;\r
497           }\r
498 \r
499           // search title, description, and content for something\r
500           // the contentTerm uses param "search_boolean" to combine its terms\r
501           String contentFragment = contentTerm.makeTerm(req);\r
502           if (contentFragment != null){\r
503             logger.debug("contentFragment: " + contentFragment);\r
504             queryString = queryString + " +" + contentFragment;\r
505           }\r
506 \r
507           String topicFragment = topicTerm.makeTerm(req);\r
508           if (topicFragment != null){\r
509             queryString = queryString + " +" + topicFragment;\r
510           }\r
511 \r
512           String imagesFragment = imagesTerm.makeTerm(req);\r
513           if (imagesFragment != null){\r
514             queryString = queryString + " +" + imagesFragment;\r
515           }\r
516 \r
517           String audioFragment = audioTerm.makeTerm(req);\r
518           if (audioFragment != null){\r
519             queryString = queryString + " +" + audioFragment;\r
520           }\r
521 \r
522           String videoFragment = videoTerm.makeTerm(req);\r
523           if (videoFragment != null){\r
524             queryString = queryString + " +" + videoFragment;\r
525           }\r
526 \r
527           if (queryString == null || queryString == ""){\r
528             queryString = "";\r
529           }\r
530           else{\r
531             try{\r
532               Searcher searcher = null;\r
533               try {\r
534                 searcher = new IndexSearcher(indexPath);\r
535               }\r
536               catch(IOException e) {\r
537                 logger.debug("Can't open indexPath: " + indexPath);\r
538                 throw new ServletModuleUserException("Problem with Search Index! : "+ e.toString());\r
539               }\r
540 \r
541               Query query = null;\r
542               try {\r
543                 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());\r
544               }\r
545               catch(Exception e) {\r
546                 searcher.close();\r
547                 logger.debug("Query don't parse: " + queryString);\r
548                 throw new ServletModuleUserException("Problem with Query String! (was '"+queryString+"')");\r
549               }\r
550 \r
551               Hits hits = null;\r
552               try {\r
553                 hits = searcher.search(query);\r
554               }\r
555               catch(IOException e) {\r
556                 searcher.close();\r
557                 logger.debug("Can't get hits: " + e.toString());\r
558                 throw new ServletModuleUserException("Problem getting hits!");\r
559               }\r
560 \r
561               int start = 0;\r
562               int end = hits.length();\r
563 \r
564               String sortBy=req.getParameter("search_sort");\r
565               if (sortBy == null || sortBy.equals("")){\r
566                 throw new ServletModuleUserException("Please let me sort by something!(missing search_sort)");\r
567               }\r
568 \r
569               // here is where the documents will go for storage across sessions\r
570               ArrayList theDocumentsSorted = new ArrayList();\r
571 \r
572               if (sortBy.equals("score")){\r
573                 for(int i = start; i < end; i++) {\r
574                   theDocumentsSorted.add(hits.doc(i));\r
575                 }\r
576               }\r
577               else{\r
578                 // then we'll sort by date!\r
579                 HashMap dateToPosition = new HashMap(end,1.0F); //we know how big it will be\r
580                 for(int i = start; i < end; i++) {\r
581                   String creationDate=(hits.doc(i)).get("creationDate");\r
582                   // do a little dance in case two contents created at the same second!\r
583                   if (dateToPosition.containsKey(creationDate)){\r
584                     ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));\r
585                   }\r
586                   else{\r
587                     ArrayList thePositions = new ArrayList();\r
588                     thePositions.add(new Integer(i));\r
589                     dateToPosition.put(creationDate,thePositions);\r
590                   }\r
591                 }\r
592                 Set keys = dateToPosition.keySet();\r
593                 ArrayList keyList= new ArrayList(keys);\r
594                 Collections.sort(keyList);\r
595                 if (sortBy.equals("date_desc")){\r
596                   Collections.reverse(keyList);\r
597                 }\r
598                 else{\r
599                   if (!sortBy.equals("date_asc")){\r
600                     throw new ServletModuleUserException("don't know how to sort by: "+ sortBy);\r
601                   }\r
602                 }\r
603                 ListIterator keyTraverser = keyList.listIterator();\r
604                 while (keyTraverser.hasNext()){\r
605                   ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next()));\r
606                   ListIterator positionsTraverser=positions.listIterator();\r
607                   while (positionsTraverser.hasNext()){\r
608                     theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue()));\r
609                   }\r
610                 }\r
611               }\r
612 \r
613               try{\r
614                 searcher.close();\r
615               }\r
616               catch (IOException e){\r
617                 logger.debug("Can't close searcher: " + e.toString());\r
618                 throw new ServletModuleUserException("Problem closing searcher(normal)!");\r
619               }\r
620 \r
621 \r
622               session.removeAttribute("numberOfHits");\r
623               session.removeAttribute("theDocumentsSorted");\r
624               session.removeAttribute("positionInResults");\r
625 \r
626               session.setAttribute("numberOfHits",new Integer(end));\r
627               session.setAttribute("theDocumentsSorted",theDocumentsSorted);\r
628               session.setAttribute("positionInResults",new Integer(0));\r
629 \r
630             }\r
631             catch (IOException e){\r
632               logger.debug("Can't close searcher: " + e.toString());\r
633               throw new ServletModuleUserException("Problem closing searcher!");\r
634             }\r
635           }\r
636         }\r
637       }\r
638 \r
639       try {\r
640         ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted");\r
641         if (theDocs != null){\r
642 \r
643           mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString());\r
644           SimpleList theHits = new SimpleList();\r
645           int pIR=((Integer)session.getAttribute("positionInResults")).intValue();\r
646           int terminus;\r
647           int numHits=((Integer)session.getAttribute("numberOfHits")).intValue();\r
648 \r
649           if (!(pIR+increment>=numHits)){\r
650             mergeData.put("hasNext","y");\r
651           }\r
652           if (pIR-increment>=0){\r
653             mergeData.put("hasPrevious","y");\r
654           }\r
655 \r
656           if ((pIR+increment)>numHits){\r
657             terminus=numHits;\r
658           }\r
659           else {\r
660             terminus=pIR+increment;\r
661           }\r
662           for(int i = pIR; i < terminus; i++) {\r
663             SimpleHash h = new SimpleHash();\r
664             Document theHit = (Document)theDocs.get(i);\r
665             whereTerm.returnMeta(h,theHit);\r
666             creatorTerm.returnMeta(h,theHit);\r
667             titleTerm.returnMeta(h,theHit);\r
668             descriptionTerm.returnMeta(h,theHit);\r
669             dateTerm.returnMeta(h,theHit);\r
670             imagesTerm.returnMeta(h,theHit);\r
671             audioTerm.returnMeta(h,theHit);\r
672             videoTerm.returnMeta(h,theHit);\r
673             theHits.add(h);\r
674           }\r
675           mergeData.put("hits",theHits);\r
676         }\r
677       }\r
678       catch (Exception e) {\r
679         logger.debug("Can't iterate over hits: " + e.toString());\r
680         throw new ServletModuleUserException("Problem getting hits!");\r
681       }\r
682 \r
683       mergeData.put("queryString",queryString);\r
684       deliver(req,res,mergeData,searchResultsTemplate);\r
685     }\r
686     catch (NullPointerException n){\r
687       n.printStackTrace();\r
688       throw new ServletModuleUserException("Null Pointer"+n.toString());\r
689     }\r
690   }\r
691 \r
692   /*\r
693    * Method for dynamically generating a pdf from a fo file\r
694    */\r
695   public void getpdf(HttpServletRequest req, HttpServletResponse res)\r
696     throws ServletModuleException, ServletModuleUserException {\r
697     String ID_REQUEST_PARAM = "id";\r
698 \r
699     String generateFO=MirConfig.getProp("GenerateFO");\r
700     String generatePDF=MirConfig.getProp("GeneratePDF");\r
701 \r
702     //don't do anything if we are not making FO files, or if we are\r
703     //pregenerating PDF's\r
704     if (generateFO.equals("yes") && generatePDF.equals("no")){\r
705       //fop complains unless you do the logging this way\r
706       org.apache.log.Logger log = null;\r
707       Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();\r
708       log = hierarchy.getLoggerFor("fop");\r
709       log.setPriority(Priority.WARN);\r
710 \r
711       String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");\r
712       String producerDocRoot=MirConfig.getProp("Producer.DocRoot");\r
713       String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");\r
714       String xslSheet=templateDir + "/"\r
715         + MirConfig.getProp("Producer.PrintableContent.html2foStyleSheetName");\r
716       try {\r
717         String idParam = req.getParameter(ID_REQUEST_PARAM);\r
718         if (idParam != null) {\r
719           EntityContent contentEnt =\r
720             (EntityContent)contentModule.getById(idParam);\r
721           String publishPath = contentEnt.getValue("publish_path");\r
722           String foFile = producerStorageRoot + producerDocRoot + "/"\r
723             + publishPath + "/" + idParam + ".fo";\r
724           XSLTInputHandler input = new XSLTInputHandler(new File(foFile),\r
725                                                         new File(xslSheet));\r
726 \r
727           ByteArrayOutputStream out = new ByteArrayOutputStream();\r
728           res.setContentType("application/pdf");\r
729 \r
730           Driver driver = new Driver();\r
731           driver.setLogger(log);\r
732           driver.setRenderer(Driver.RENDER_PDF);\r
733           driver.setOutputStream(out);\r
734           driver.render(input.getParser(), input.getInputSource());\r
735 \r
736           byte[] content = out.toByteArray();\r
737           res.setContentLength(content.length);\r
738           res.getOutputStream().write(content);\r
739           res.getOutputStream().flush();\r
740         } else {\r
741           throw new ServletModuleUserException("Missing id parameter.");\r
742         }\r
743       } catch (Exception ex) {\r
744         throw new ServletModuleException(ex.toString());\r
745       }\r
746     } else {\r
747       throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");\r
748     }\r
749   }\r
750 \r
751   private void _throwBadContentType (String fileName, String contentType)\r
752     throws ServletModuleUserException {\r
753 \r
754     logger.error("Wrong file type uploaded!: " + fileName+" "\r
755                           +contentType);\r
756     throw new ServletModuleUserException("The file you uploaded is of the "\r
757                                          +"following mime-type: "+contentType\r
758                                          +", we do not support this mime-type. "\r
759                                          +"Error One or more files of unrecognized type. Sorry");\r
760   }\r
761 \r
762   protected String createOneTimePasswd(){\r
763     Random r = new Random();\r
764     int random = r.nextInt();\r
765     long l = System.currentTimeMillis();\r
766     l = (l*l*l*l)/random;\r
767     if(l<0) l = l * -1;\r
768     String returnString = ""+l;\r
769     return returnString.substring(5);\r
770   }\r
771 \r
772 \r
773   /* this is an overwritten method of ServletModule in order\r
774      to use different bundles for open and admin */\r
775   public void deliver(HttpServletRequest req, HttpServletResponse res,\r
776                       TemplateModelRoot rtm, TemplateModelRoot popups,\r
777                       String templateFilename)\r
778     throws ServletModuleException {\r
779     if (rtm == null) rtm = new SimpleHash();\r
780     try {\r
781       PrintWriter out = res.getWriter();\r
782       HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out,\r
783                                     getLocale(req), "bundles.open");\r
784       out.close();\r
785     }   catch (HTMLParseException e) {\r
786       throw new ServletModuleException(e.toString());\r
787     } catch (IOException e) {\r
788       throw new ServletModuleException(e.toString());\r
789     }\r
790   }\r
791 }\r
792 \r
793 \r
794 \r