68b92d01eb0dd0a7cfdfab612f1ef4d806108692
[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.51 2002/12/17 19:20:31 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           withValues.put("to_comment_status","1");\r
201 \r
202           //checking the onetimepasswd\r
203           if(passwdProtection.equals("yes")){\r
204             HttpSession session = req.getSession(false);\r
205             String sessionPasswd = (String)session.getAttribute("passwd");\r
206             if ( sessionPasswd == null){\r
207               throw new ServletModuleUserException("Lost password");\r
208             }\r
209             String passwd = req.getParameter("passwd");\r
210             if ( passwd == null || (!sessionPasswd.equals(passwd))) {\r
211               throw new ServletModuleUserException("Missing password");\r
212             }\r
213             session.invalidate();\r
214           }\r
215 \r
216           // inserting into database\r
217           String id = mainModule.add(withValues);\r
218           logger.debug("id: "+id);\r
219           //insert was not successfull\r
220           if(id==null){\r
221             deliver(req, res, new SimpleHash(), commentFormDupeTemplate);\r
222           } else {\r
223             DatabaseContent.getInstance().setUnproduced("id="+aid);\r
224 \r
225             try {\r
226               EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);\r
227               MirGlobal.localizer().openPostings().afterCommentPosting(comment);\r
228             }\r
229             catch (Throwable t) {\r
230               throw new ServletModuleException(t.getMessage());\r
231             }\r
232           }\r
233 \r
234           // redirecting to url\r
235           // should implement back to article\r
236           SimpleHash mergeData = new SimpleHash();\r
237           deliver(req, res, mergeData, commentFormDoneTemplate);\r
238         }\r
239         catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}\r
240         catch (ModuleException e) { throw new ServletModuleException(e.toString());}\r
241 \r
242       }\r
243     else throw new ServletModuleException("aid not set!");\r
244 \r
245   }\r
246 \r
247   /**\r
248    *  Method for delivering the form-Page for open posting\r
249    */\r
250 \r
251   public void addposting(HttpServletRequest req, HttpServletResponse res)\r
252     throws ServletModuleException {\r
253     SimpleHash mergeData = new SimpleHash();\r
254 \r
255     // onetimepasswd\r
256     if(passwdProtection.equals("yes")){\r
257       String passwd = this.createOneTimePasswd();\r
258       System.out.println(passwd);\r
259       HttpSession session = req.getSession(false);\r
260       session.setAttribute("passwd",passwd);\r
261       mergeData.put("passwd", passwd);\r
262     }\r
263 \r
264     String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");\r
265     String defaultMedia = MirConfig.getProp("ServletModule.OpenIndy.DefaultMediaUploadItems");\r
266     String numOfMedia = req.getParameter("medianum");\r
267 \r
268     if(numOfMedia==null||numOfMedia.equals("")){\r
269       numOfMedia=defaultMedia;\r
270     }\r
271     else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {\r
272       numOfMedia = maxMedia;\r
273     }\r
274 \r
275     int mediaNum = Integer.parseInt(numOfMedia);\r
276     SimpleList mediaFields = new SimpleList();\r
277     for(int i =0; i<mediaNum;i++){\r
278       Integer mNum = new Integer(i+1);\r
279       mediaFields.add(mNum.toString());\r
280     }\r
281     mergeData.put("medianum",numOfMedia);\r
282     mergeData.put("mediafields",mediaFields);\r
283 \r
284 \r
285     SimpleHash extraInfo = new SimpleHash();\r
286     try{\r
287       extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData() );\r
288       extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());\r
289 \r
290       extraInfo.put("topics", themenModule.getTopicsList());\r
291 \r
292     }\r
293     catch (Exception e) {\r
294       logger.error("languagePopUpData or getTopicslist failed "+e.toString());\r
295       throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());\r
296     }\r
297 \r
298 \r
299 \r
300     deliver(req, res, mergeData, extraInfo, postingFormTemplate);\r
301   }\r
302 \r
303   /**\r
304    *  Method for inserting an open posting into the Database and delivering\r
305    *  the postingDone Page\r
306    */\r
307 \r
308   public void insposting(HttpServletRequest req, HttpServletResponse res)\r
309     throws ServletModuleException, ServletModuleUserException\r
310   {\r
311     SimpleHash mergeData = new SimpleHash();\r
312     boolean setMedia=false;\r
313     boolean setTopic = false;\r
314 \r
315     try {\r
316 \r
317       WebdbMultipartRequest mp = null;\r
318       EntityList mediaList = null;\r
319       try {\r
320         // new MediaRequest, "1" is the id for the openPosting user\r
321         MediaRequest mediaReq = new MediaRequest("1", true, true);\r
322         mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);\r
323         mediaList = mediaReq.getEntityList();\r
324       }\r
325       catch (FileHandlerUserException e) {\r
326         throw new ServletModuleUserException(e.getMessage());\r
327       }\r
328 \r
329       HashMap withValues = mp.getParameters();\r
330 \r
331       //checking the onetimepasswd\r
332       if(passwdProtection.equals("yes")){\r
333         HttpSession session = req.getSession(false);\r
334         String sessionPasswd = (String)session.getAttribute("passwd");\r
335         if ( sessionPasswd == null){\r
336           throw new ServletModuleUserException("Lost password");\r
337         }\r
338         String passwd = (String)withValues.get("passwd");\r
339         if ( passwd == null || (!sessionPasswd.equals(passwd))) {\r
340           throw new ServletModuleUserException("Missing password");\r
341         }\r
342         session.invalidate();\r
343       }\r
344 \r
345       if ((((String)withValues.get("title")).length() == 0) ||\r
346           (((String)withValues.get("description")).length() == 0) ||\r
347           (((String)withValues.get("content_data")).length() == 0))\r
348         throw new ServletModuleUserException("Missing field");\r
349 \r
350       // call the routines that escape html\r
351 \r
352       for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){\r
353         String k=(String)i.next();\r
354         String v=(String)withValues.get(k);\r
355 \r
356         if (k.equals("content_data")){\r
357           //this doesn't quite work yet, so for now, all html goes\r
358           //withValues.put(k,StringUtil.approveHTMLTags(v));\r
359           //withValues.put(k,StringUtil.removeHTMLTags(v));\r
360         } else {\r
361           withValues.put(k,StringUtil.removeHTMLTags(v));\r
362         }\r
363 \r
364       }\r
365 \r
366       withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
367       withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));\r
368       withValues.put("is_produced", "0");\r
369       // by default stuff is published, they can be un-published through the\r
370       // admin interface.\r
371       withValues.put("is_published","1");\r
372       // if op direct article-type == newswire\r
373       if (directOp.equals("yes")) withValues.put("to_article_type","1");\r
374 \r
375       withValues.put("to_publisher","1");\r
376 \r
377       // owner is openposting user\r
378       //      ML: this is not multi-language friendly and this can be done in a template\r
379       //      if (withValues.get("creator").toString().equals(""))\r
380       //        withValues.put("creator","Anonym");\r
381 \r
382       // inserting  content into database\r
383       String cid = contentModule.add(withValues);\r
384       logger.debug("id: "+cid);\r
385       //insert was not successfull\r
386       if(cid==null){\r
387         //How do we know that it was not succesful cause of a\r
388         //dupe, what if it failed cause of "No space left on device"?\r
389         //Or is there something I am missing? Wouldn't it be better\r
390         //to have an explicit dupe check and then insert? I have no\r
391         //idea what I am talking about. this comment is in case\r
392         //I forget to explicitely ask. -mh\r
393         deliver(req, res, mergeData, postingFormDupeTemplate);\r
394       }\r
395 \r
396       String[] to_topicsArr = mp.getParameterValues("to_topic");\r
397 \r
398       if (to_topicsArr != null && to_topicsArr.length > 0) {\r
399         try{\r
400           DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);\r
401           setTopic = true;\r
402         }\r
403         catch (Exception e) {\r
404           logger.error("setting content_x_topic failed");\r
405           contentModule.deleteById(cid);\r
406           throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());\r
407         } //end try\r
408       } //end if\r
409 \r
410       //if we're here all is ok... associate the media to the article\r
411       for(int i=0;i<mediaList.size();i++) {\r
412         Entity mediaEnt = (Entity)mediaList.elementAt(i);\r
413         DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());\r
414       }\r
415 \r
416       try {\r
417         MirGlobal.localizer().openPostings().afterContentPosting(\r
418                                                                  (EntityContent)contentModule.getById(cid));\r
419       }\r
420       catch (Throwable t) {\r
421         throw new ServletModuleException(t.getMessage());\r
422       }\r
423     }\r
424     catch (FileHandlerException e) {\r
425       e.printStackTrace(System.out);\r
426       throw new ServletModuleException("MediaException: "+ e.getMessage());\r
427     }\r
428     catch (IOException e) { throw new ServletModuleException("IOException: "+ e.getMessage());}\r
429     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.getMessage());}\r
430     catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.getMessage());}\r
431 \r
432     deliver(req, res, mergeData, postingFormDoneTemplate);\r
433   }\r
434 \r
435   /*\r
436    * Method for querying a lucene index\r
437    */\r
438   public void search(HttpServletRequest req, HttpServletResponse res)\r
439     throws ServletModuleException, ServletModuleUserException {\r
440     try {\r
441       int increment=10;\r
442 \r
443       HttpSession session = req.getSession(false);\r
444 \r
445       String queryString="";\r
446 \r
447       SimpleHash mergeData = new SimpleHash();\r
448 \r
449       KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted","search_date","webdb_create_formatted","webdb_create_formatted","webdb_create_formatted");\r
450       UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("","","","where","where");\r
451       TextSearchTerm creatorTerm = new TextSearchTerm("creator","search_creator","creator","creator","creator");\r
452       TextSearchTerm titleTerm = new TextSearchTerm("title","search_content","title","title","title");\r
453       TextSearchTerm descriptionTerm =  new TextSearchTerm("description","search_content","description","description","description");\r
454       ContentSearchTerm contentTerm = new ContentSearchTerm("content_data","search_content","content","","");\r
455       TopicSearchTerm topicTerm = new TopicSearchTerm();\r
456       ImagesSearchTerm imagesTerm = new ImagesSearchTerm();\r
457       AudioSearchTerm audioTerm = new AudioSearchTerm();\r
458       VideoSearchTerm videoTerm = new VideoSearchTerm();\r
459 \r
460       //make the query available to subsequent iterations\r
461 \r
462       for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {\r
463         String pName=(String)theParams.nextElement();\r
464         if (pName.startsWith("search_")){\r
465           mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));\r
466         }\r
467       }\r
468 \r
469       try{\r
470         mergeData.put("topics", themenModule.getTopicsAsSimpleList());\r
471       }\r
472       catch(ModuleException e) {\r
473         logger.debug("Can't get topics: " + e.toString());\r
474       }\r
475 \r
476       String searchSubmitValue = req.getParameter("search_submit");\r
477 \r
478       if (searchSubmitValue != null && searchSubmitValue.equals("Back")){\r
479         int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
480         int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()-increment;\r
481         if (newPosition < 0 || newPosition >= totalHits){\r
482           throw new ServletModuleUserException("newPosition: index out bounds, value was:"+(new Integer(newPosition)).toString());\r
483         }\r
484         session.setAttribute("positionInResults",new Integer(newPosition));\r
485 \r
486       }\r
487       else {\r
488         if (searchSubmitValue != null && searchSubmitValue.equals("Forward")){\r
489           int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();\r
490           int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment;\r
491           if (newPosition < 0 || newPosition >= totalHits){\r
492             throw new ServletModuleUserException("newPosition: index out bounds, value was:"+(new Integer(newPosition)).toString());\r
493           }\r
494           session.setAttribute("positionInResults",new Integer(newPosition));\r
495 \r
496         }\r
497         else {\r
498           String indexPath=MirConfig.getProp("IndexPath");\r
499 \r
500 \r
501           String creatorFragment = creatorTerm.makeTerm(req);\r
502           if (creatorFragment != null){\r
503             queryString = queryString + " +" + creatorFragment;\r
504           }\r
505 \r
506           // search title, description, and content for something\r
507           // the contentTerm uses param "search_boolean" to combine its terms\r
508           String contentFragment = contentTerm.makeTerm(req);\r
509           if (contentFragment != null){\r
510             logger.debug("contentFragment: " + contentFragment);\r
511             queryString = queryString + " +" + contentFragment;\r
512           }\r
513 \r
514           String topicFragment = topicTerm.makeTerm(req);\r
515           if (topicFragment != null){\r
516             queryString = queryString + " +" + topicFragment;\r
517           }\r
518 \r
519           String imagesFragment = imagesTerm.makeTerm(req);\r
520           if (imagesFragment != null){\r
521             queryString = queryString + " +" + imagesFragment;\r
522           }\r
523 \r
524           String audioFragment = audioTerm.makeTerm(req);\r
525           if (audioFragment != null){\r
526             queryString = queryString + " +" + audioFragment;\r
527           }\r
528 \r
529           String videoFragment = videoTerm.makeTerm(req);\r
530           if (videoFragment != null){\r
531             queryString = queryString + " +" + videoFragment;\r
532           }\r
533 \r
534           if (queryString == null || queryString == ""){\r
535             queryString = "";\r
536           }\r
537           else{\r
538             try{\r
539               Searcher searcher = null;\r
540               try {\r
541                 searcher = new IndexSearcher(indexPath);\r
542               }\r
543               catch(IOException e) {\r
544                 logger.debug("Can't open indexPath: " + indexPath);\r
545                 throw new ServletModuleUserException("Problem with Search Index! : "+ e.toString());\r
546               }\r
547 \r
548               Query query = null;\r
549               try {\r
550                 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());\r
551               }\r
552               catch(Exception e) {\r
553                 searcher.close();\r
554                 logger.debug("Query don't parse: " + queryString);\r
555                 throw new ServletModuleUserException("Problem with Query String! (was '"+queryString+"')");\r
556               }\r
557 \r
558               Hits hits = null;\r
559               try {\r
560                 hits = searcher.search(query);\r
561               }\r
562               catch(IOException e) {\r
563                 searcher.close();\r
564                 logger.debug("Can't get hits: " + e.toString());\r
565                 throw new ServletModuleUserException("Problem getting hits!");\r
566               }\r
567 \r
568               int start = 0;\r
569               int end = hits.length();\r
570 \r
571               String sortBy=req.getParameter("search_sort");\r
572               if (sortBy == null || sortBy.equals("")){\r
573                 throw new ServletModuleUserException("Please let me sort by something!(missing search_sort)");\r
574               }\r
575 \r
576               // here is where the documents will go for storage across sessions\r
577               ArrayList theDocumentsSorted = new ArrayList();\r
578 \r
579               if (sortBy.equals("score")){\r
580                 for(int i = start; i < end; i++) {\r
581                   theDocumentsSorted.add(hits.doc(i));\r
582                 }\r
583               }\r
584               else{\r
585                 // then we'll sort by date!\r
586                 HashMap dateToPosition = new HashMap(end,1.0F); //we know how big it will be\r
587                 for(int i = start; i < end; i++) {\r
588                   String creationDate=(hits.doc(i)).get("creationDate");\r
589                   // do a little dance in case two contents created at the same second!\r
590                   if (dateToPosition.containsKey(creationDate)){\r
591                     ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));\r
592                   }\r
593                   else{\r
594                     ArrayList thePositions = new ArrayList();\r
595                     thePositions.add(new Integer(i));\r
596                     dateToPosition.put(creationDate,thePositions);\r
597                   }\r
598                 }\r
599                 Set keys = dateToPosition.keySet();\r
600                 ArrayList keyList= new ArrayList(keys);\r
601                 Collections.sort(keyList);\r
602                 if (sortBy.equals("date_desc")){\r
603                   Collections.reverse(keyList);\r
604                 }\r
605                 else{\r
606                   if (!sortBy.equals("date_asc")){\r
607                     throw new ServletModuleUserException("don't know how to sort by: "+ sortBy);\r
608                   }\r
609                 }\r
610                 ListIterator keyTraverser = keyList.listIterator();\r
611                 while (keyTraverser.hasNext()){\r
612                   ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next()));\r
613                   ListIterator positionsTraverser=positions.listIterator();\r
614                   while (positionsTraverser.hasNext()){\r
615                     theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue()));\r
616                   }\r
617                 }\r
618               }\r
619 \r
620               try{\r
621                 searcher.close();\r
622               }\r
623               catch (IOException e){\r
624                 logger.debug("Can't close searcher: " + e.toString());\r
625                 throw new ServletModuleUserException("Problem closing searcher(normal)!");\r
626               }\r
627 \r
628 \r
629               session.removeAttribute("numberOfHits");\r
630               session.removeAttribute("theDocumentsSorted");\r
631               session.removeAttribute("positionInResults");\r
632 \r
633               session.setAttribute("numberOfHits",new Integer(end));\r
634               session.setAttribute("theDocumentsSorted",theDocumentsSorted);\r
635               session.setAttribute("positionInResults",new Integer(0));\r
636 \r
637             }\r
638             catch (IOException e){\r
639               logger.debug("Can't close searcher: " + e.toString());\r
640               throw new ServletModuleUserException("Problem closing searcher!");\r
641             }\r
642           }\r
643         }\r
644       }\r
645 \r
646       try {\r
647         ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted");\r
648         if (theDocs != null){\r
649 \r
650           mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString());\r
651           SimpleList theHits = new SimpleList();\r
652           int pIR=((Integer)session.getAttribute("positionInResults")).intValue();\r
653           int terminus;\r
654           int numHits=((Integer)session.getAttribute("numberOfHits")).intValue();\r
655 \r
656           if (!(pIR+increment>=numHits)){\r
657             mergeData.put("hasNext","y");\r
658           }\r
659           if (pIR-increment>=0){\r
660             mergeData.put("hasPrevious","y");\r
661           }\r
662 \r
663           if ((pIR+increment)>numHits){\r
664             terminus=numHits;\r
665           }\r
666           else {\r
667             terminus=pIR+increment;\r
668           }\r
669           for(int i = pIR; i < terminus; i++) {\r
670             SimpleHash h = new SimpleHash();\r
671             Document theHit = (Document)theDocs.get(i);\r
672             whereTerm.returnMeta(h,theHit);\r
673             creatorTerm.returnMeta(h,theHit);\r
674             titleTerm.returnMeta(h,theHit);\r
675             descriptionTerm.returnMeta(h,theHit);\r
676             dateTerm.returnMeta(h,theHit);\r
677             imagesTerm.returnMeta(h,theHit);\r
678             audioTerm.returnMeta(h,theHit);\r
679             videoTerm.returnMeta(h,theHit);\r
680             theHits.add(h);\r
681           }\r
682           mergeData.put("hits",theHits);\r
683         }\r
684       }\r
685       catch (Exception e) {\r
686         logger.debug("Can't iterate over hits: " + e.toString());\r
687         throw new ServletModuleUserException("Problem getting hits!");\r
688       }\r
689 \r
690       mergeData.put("queryString",queryString);\r
691       deliver(req,res,mergeData,searchResultsTemplate);\r
692     }\r
693     catch (NullPointerException n){\r
694       n.printStackTrace();\r
695       throw new ServletModuleUserException("Null Pointer"+n.toString());\r
696     }\r
697   }\r
698 \r
699   /*\r
700    * Method for dynamically generating a pdf from a fo file\r
701    */\r
702   public void getpdf(HttpServletRequest req, HttpServletResponse res)\r
703     throws ServletModuleException, ServletModuleUserException {\r
704     String ID_REQUEST_PARAM = "id";\r
705 \r
706     String generateFO=MirConfig.getProp("GenerateFO");\r
707     String generatePDF=MirConfig.getProp("GeneratePDF");\r
708 \r
709     //don't do anything if we are not making FO files, or if we are\r
710     //pregenerating PDF's\r
711     if (generateFO.equals("yes") && generatePDF.equals("no")){\r
712       //fop complains unless you do the logging this way\r
713       org.apache.log.Logger log = null;\r
714       Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();\r
715       log = hierarchy.getLoggerFor("fop");\r
716       log.setPriority(Priority.WARN);\r
717 \r
718       String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");\r
719       String producerDocRoot=MirConfig.getProp("Producer.DocRoot");\r
720       String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");\r
721       String xslSheet=templateDir + "/"\r
722         + MirConfig.getProp("Producer.PrintableContent.html2foStyleSheetName");\r
723       try {\r
724         String idParam = req.getParameter(ID_REQUEST_PARAM);\r
725         if (idParam != null) {\r
726           EntityContent contentEnt =\r
727             (EntityContent)contentModule.getById(idParam);\r
728           String publishPath = contentEnt.getValue("publish_path");\r
729           String foFile = producerStorageRoot + producerDocRoot + "/"\r
730             + publishPath + "/" + idParam + ".fo";\r
731           XSLTInputHandler input = new XSLTInputHandler(new File(foFile),\r
732                                                         new File(xslSheet));\r
733 \r
734           ByteArrayOutputStream out = new ByteArrayOutputStream();\r
735           res.setContentType("application/pdf");\r
736 \r
737           Driver driver = new Driver();\r
738           driver.setLogger(log);\r
739           driver.setRenderer(Driver.RENDER_PDF);\r
740           driver.setOutputStream(out);\r
741           driver.render(input.getParser(), input.getInputSource());\r
742 \r
743           byte[] content = out.toByteArray();\r
744           res.setContentLength(content.length);\r
745           res.getOutputStream().write(content);\r
746           res.getOutputStream().flush();\r
747         } else {\r
748           throw new ServletModuleUserException("Missing id parameter.");\r
749         }\r
750       } catch (Exception ex) {\r
751         throw new ServletModuleException(ex.toString());\r
752       }\r
753     } else {\r
754       throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");\r
755     }\r
756   }\r
757 \r
758   private void _throwBadContentType (String fileName, String contentType)\r
759     throws ServletModuleUserException {\r
760 \r
761     logger.error("Wrong file type uploaded!: " + fileName+" "\r
762                           +contentType);\r
763     throw new ServletModuleUserException("The file you uploaded is of the "\r
764                                          +"following mime-type: "+contentType\r
765                                          +", we do not support this mime-type. "\r
766                                          +"Error One or more files of unrecognized type. Sorry");\r
767   }\r
768 \r
769   protected String createOneTimePasswd(){\r
770     Random r = new Random();\r
771     int random = r.nextInt();\r
772     long l = System.currentTimeMillis();\r
773     l = (l*l*l*l)/random;\r
774     if(l<0) l = l * -1;\r
775     String returnString = ""+l;\r
776     return returnString.substring(5);\r
777   }\r
778 \r
779 \r
780   /* this is an overwritten method of ServletModule in order\r
781      to use different bundles for open and admin */\r
782   public void deliver(HttpServletRequest req, HttpServletResponse res,\r
783                       TemplateModelRoot rtm, TemplateModelRoot popups,\r
784                       String templateFilename)\r
785     throws ServletModuleException {\r
786     if (rtm == null) rtm = new SimpleHash();\r
787     try {\r
788       PrintWriter out = res.getWriter();\r
789       HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out,\r
790                                     getLocale(req), "bundles.open");\r
791       out.close();\r
792     }   catch (HTMLParseException e) {\r
793       throw new ServletModuleException(e.toString());\r
794     } catch (IOException e) {\r
795       throw new ServletModuleException(e.toString());\r
796     }\r
797   }\r
798 }\r
799 \r
800 \r
801 \r