2 * Copyright (C) 2001, 2002 The Mir-coders group
\r
4 * This file is part of Mir.
\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
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
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
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
32 package mircoders.servlet;
\r
34 import java.io.ByteArrayOutputStream;
\r
35 import java.io.File;
\r
36 import java.io.FileNotFoundException;
\r
37 import java.io.FileReader;
\r
38 import java.io.IOException;
\r
39 import java.io.PrintWriter;
\r
40 import java.io.StringWriter;
\r
41 import java.util.ArrayList;
\r
42 import java.util.Collections;
\r
43 import java.util.Enumeration;
\r
44 import java.util.GregorianCalendar;
\r
45 import java.util.HashMap;
\r
46 import java.util.Iterator;
\r
47 import java.util.ListIterator;
\r
48 import java.util.Locale;
\r
49 import java.util.Random;
\r
50 import java.util.Set;
\r
52 import javax.servlet.http.HttpServletRequest;
\r
53 import javax.servlet.http.HttpServletResponse;
\r
54 import javax.servlet.http.HttpSession;
\r
56 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
\r
57 import mir.entity.Entity;
\r
58 import mir.entity.EntityList;
\r
59 import mir.log.LoggerWrapper;
\r
60 import mir.misc.FileHandler;
\r
61 import mir.misc.FileHandlerException;
\r
62 import mir.misc.FileHandlerUserException;
\r
63 import mir.misc.HTMLParseException;
\r
64 import mir.misc.HTMLTemplateProcessor;
\r
65 import mir.misc.StringUtil;
\r
66 import mir.misc.WebdbMultipartRequest;
\r
67 import mir.module.ModuleException;
\r
68 import mir.servlet.ServletModule;
\r
69 import mir.servlet.ServletModuleException;
\r
70 import mir.servlet.ServletModuleUserException;
\r
71 import mir.storage.StorageObjectFailure;
\r
72 import mir.util.StringRoutines;
\r
73 import mircoders.entity.EntityComment;
\r
74 import mircoders.entity.EntityContent;
\r
75 import mircoders.global.MirGlobal;
\r
76 import mircoders.media.MediaRequest;
\r
77 import mircoders.module.ModuleComment;
\r
78 import mircoders.module.ModuleContent;
\r
79 import mircoders.module.ModuleImages;
\r
80 import mircoders.module.ModuleTopics;
\r
81 import mircoders.search.AudioSearchTerm;
\r
82 import mircoders.search.ContentSearchTerm;
\r
83 import mircoders.search.ImagesSearchTerm;
\r
84 import mircoders.search.KeywordSearchTerm;
\r
85 import mircoders.search.TextSearchTerm;
\r
86 import mircoders.search.TopicSearchTerm;
\r
87 import mircoders.search.UnIndexedSearchTerm;
\r
88 import mircoders.search.VideoSearchTerm;
\r
89 import mircoders.storage.DatabaseComment;
\r
90 import mircoders.storage.DatabaseContent;
\r
91 import mircoders.storage.DatabaseContentToMedia;
\r
92 import mircoders.storage.DatabaseContentToTopics;
\r
93 import mircoders.storage.DatabaseImages;
\r
94 import mircoders.storage.DatabaseLanguage;
\r
95 import mircoders.storage.DatabaseTopics;
\r
97 import org.apache.commons.net.smtp.SMTPClient;
\r
98 import org.apache.commons.net.smtp.SMTPReply;
\r
99 import org.apache.fop.apps.Driver;
\r
100 import org.apache.fop.apps.XSLTInputHandler;
\r
101 import org.apache.log.Hierarchy;
\r
102 import org.apache.log.Priority;
\r
103 import org.apache.lucene.analysis.standard.StandardAnalyzer;
\r
104 import org.apache.lucene.document.Document;
\r
105 import org.apache.lucene.queryParser.QueryParser;
\r
106 import org.apache.lucene.search.Hits;
\r
107 import org.apache.lucene.search.IndexSearcher;
\r
108 import org.apache.lucene.search.Query;
\r
109 import org.apache.lucene.search.Searcher;
\r
111 import freemarker.template.SimpleHash;
\r
112 import freemarker.template.SimpleList;
\r
113 import freemarker.template.SimpleScalar;
\r
114 import freemarker.template.TemplateModelRoot;
\r
117 * ServletModuleOpenIndy -
\r
118 * is the open-access-servlet, which is responsible for
\r
119 * adding comments to articles &
\r
120 * open-postings to the newswire
\r
122 * @author mir-coders group
\r
123 * @version $Id: ServletModuleOpenIndy.java,v 1.58 2003/01/25 17:50:36 idfx Exp $
\r
127 public class ServletModuleOpenIndy extends ServletModule
\r
130 private String commentFormTemplate, commentFormDoneTemplate,
\r
131 commentFormDupeTemplate;
\r
132 private String postingFormTemplate, postingFormDoneTemplate,
\r
133 postingFormDupeTemplate;
\r
134 private String searchResultsTemplate;
\r
135 private String prepareMailTemplate,sentMailTemplate;
\r
136 private ModuleContent contentModule;
\r
137 private ModuleComment commentModule;
\r
138 private ModuleImages imageModule;
\r
139 private ModuleTopics themenModule;
\r
140 private String directOp ="yes";
\r
141 private String passwdProtection ="yes";
\r
142 // Singelton / Kontruktor
\r
143 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
\r
144 public static ServletModule getInstance() { return instance; }
\r
146 private ServletModuleOpenIndy() {
\r
149 logger = new LoggerWrapper("ServletModule.OpenIndy");
\r
151 commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
\r
152 commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
\r
153 commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
\r
154 postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
\r
155 postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
\r
156 postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
\r
157 searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
\r
158 prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
\r
159 sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
\r
160 directOp = configuration.getString("DirectOpenposting").toLowerCase();
\r
161 passwdProtection = configuration.getString("PasswdProtection").toLowerCase();
\r
162 mainModule = new ModuleComment(DatabaseComment.getInstance());
\r
163 contentModule = new ModuleContent(DatabaseContent.getInstance());
\r
164 themenModule = new ModuleTopics(DatabaseTopics.getInstance());
\r
165 imageModule = new ModuleImages(DatabaseImages.getInstance());
\r
166 defaultAction="addposting";
\r
169 catch (StorageObjectFailure e) {
\r
170 logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
\r
176 * Method for making a comment
\r
179 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
\r
181 String aid = req.getParameter("aid"); // the article id the comment will belong to
\r
182 String language = req.getParameter("language");
\r
184 if (aid!=null && !aid.equals("")) {
\r
186 SimpleHash mergeData = new SimpleHash();
\r
189 if (passwdProtection.equals("yes")) {
\r
190 String passwd = this.createOneTimePasswd();
\r
191 System.out.println(passwd);
\r
192 HttpSession session = req.getSession(false);
\r
193 session.setAttribute("passwd", passwd);
\r
194 mergeData.put("passwd", passwd);
\r
197 if (language != null) {
\r
198 HttpSession session = req.getSession(false);
\r
199 session.setAttribute("Locale", new Locale(language, ""));
\r
200 session.setAttribute("passwd", language);
\r
203 mergeData.put("aid", aid);
\r
205 SimpleHash extraInfo = new SimpleHash();
\r
206 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
\r
208 deliver(req, res, mergeData, extraInfo, commentFormTemplate);
\r
210 catch (Throwable t) {
\r
211 throw new ServletModuleException("ServletModuleOpenIndy.addcomment: " + t.getMessage());
\r
214 else throw new ServletModuleException("aid not set!");
\r
218 * Method for inserting a comment into the Database and delivering
\r
219 * the commentDone Page
\r
222 public void inscomment(HttpServletRequest req, HttpServletResponse res)
\r
223 throws ServletModuleException,ServletModuleUserException
\r
225 String aid = req.getParameter("to_media"); // the article id the comment will belong to
\r
226 if (aid!=null && !aid.equals(""))
\r
228 // ok, collecting data from form
\r
230 HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
\r
232 //no html in comments(for now)
\r
233 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
\r
234 String k=(String)i.next();
\r
235 String v=(String)withValues.get(k);
\r
237 withValues.put(k,StringUtil.removeHTMLTags(v));
\r
239 withValues.put("is_published","1");
\r
240 withValues.put("to_comment_status","1");
\r
242 //checking the onetimepasswd
\r
243 if(passwdProtection.equals("yes")){
\r
244 HttpSession session = req.getSession(false);
\r
245 String sessionPasswd = (String)session.getAttribute("passwd");
\r
246 if ( sessionPasswd == null){
\r
247 throw new ServletModuleUserException("Lost password");
\r
249 String passwd = req.getParameter("passwd");
\r
250 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
\r
251 throw new ServletModuleUserException("Missing password");
\r
253 session.invalidate();
\r
256 // inserting into database
\r
257 String id = mainModule.add(withValues);
\r
258 logger.debug("id: "+id);
\r
259 //insert was not successfull
\r
261 deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
\r
263 DatabaseContent.getInstance().setUnproduced("id="+aid);
\r
266 EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
\r
267 MirGlobal.localizer().openPostings().afterCommentPosting(comment);
\r
269 catch (Throwable t) {
\r
270 throw new ServletModuleException(t.getMessage());
\r
274 // redirecting to url
\r
275 // should implement back to article
\r
276 SimpleHash mergeData = new SimpleHash();
\r
277 deliver(req, res, mergeData, commentFormDoneTemplate);
\r
279 catch (StorageObjectFailure e) { throw new ServletModuleException(e.toString());}
\r
280 catch (ModuleException e) { throw new ServletModuleException(e.toString());}
\r
283 else throw new ServletModuleException("aid not set!");
\r
288 * Method for delivering the form-Page for open posting
\r
291 public void addposting(HttpServletRequest req, HttpServletResponse res)
\r
292 throws ServletModuleException {
\r
293 SimpleHash mergeData = new SimpleHash();
\r
296 if(passwdProtection.equals("yes")){
\r
297 String passwd = this.createOneTimePasswd();
\r
298 System.out.println(passwd);
\r
299 HttpSession session = req.getSession(false);
\r
300 session.setAttribute("passwd",passwd);
\r
301 mergeData.put("passwd", passwd);
\r
304 String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
\r
305 String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
\r
306 String numOfMedia = req.getParameter("medianum");
\r
308 if(numOfMedia==null||numOfMedia.equals("")){
\r
309 numOfMedia=defaultMedia;
\r
311 else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
\r
312 numOfMedia = maxMedia;
\r
315 int mediaNum = Integer.parseInt(numOfMedia);
\r
316 SimpleList mediaFields = new SimpleList();
\r
317 for(int i =0; i<mediaNum;i++){
\r
318 Integer mNum = new Integer(i+1);
\r
319 mediaFields.add(mNum.toString());
\r
321 mergeData.put("medianum",numOfMedia);
\r
322 mergeData.put("mediafields",mediaFields);
\r
325 SimpleHash extraInfo = new SimpleHash();
\r
327 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData() );
\r
328 extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
\r
330 extraInfo.put("topics", themenModule.getTopicsList());
\r
333 catch (Exception e) {
\r
334 logger.error("languagePopUpData or getTopicslist failed "+e.toString());
\r
335 throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
\r
340 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
\r
344 * Method for inserting an open posting into the Database and delivering
\r
345 * the postingDone Page
\r
348 public void insposting(HttpServletRequest req, HttpServletResponse res)
\r
349 throws ServletModuleException, ServletModuleUserException
\r
351 SimpleHash mergeData = new SimpleHash();
\r
352 boolean setMedia=false;
\r
353 boolean setTopic = false;
\r
357 WebdbMultipartRequest mp = null;
\r
358 EntityList mediaList = null;
\r
360 // new MediaRequest, "1" is the id for the openPosting user
\r
361 MediaRequest mediaReq = new MediaRequest("1", true, true);
\r
362 mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);
\r
363 mediaList = mediaReq.getEntityList();
\r
365 catch (FileHandlerUserException e) {
\r
366 throw new ServletModuleUserException(e.getMessage());
\r
367 } catch (PropertiesConfigExc e) {
\r
368 throw new ServletModuleUserException(e.getMessage());
\r
371 HashMap withValues = mp.getParameters();
\r
373 //checking the onetimepasswd
\r
374 if(passwdProtection.equals("yes")){
\r
375 HttpSession session = req.getSession(false);
\r
376 String sessionPasswd = (String)session.getAttribute("passwd");
\r
377 if ( sessionPasswd == null){
\r
378 throw new ServletModuleUserException("Lost password");
\r
380 String passwd = (String)withValues.get("passwd");
\r
381 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
\r
382 throw new ServletModuleUserException("Missing password");
\r
384 session.invalidate();
\r
387 if ((((String)withValues.get("title")).length() == 0) ||
\r
388 (((String)withValues.get("description")).length() == 0) ||
\r
389 (((String)withValues.get("content_data")).length() == 0))
\r
390 throw new ServletModuleUserException("Missing field");
\r
392 // call the routines that escape html
\r
394 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
\r
395 String k=(String)i.next();
\r
396 String v=(String)withValues.get(k);
\r
398 if (k.equals("content_data")){
\r
399 //this doesn't quite work yet, so for now, all html goes
\r
400 //withValues.put(k,StringUtil.approveHTMLTags(v));
\r
401 withValues.put(k,StringUtil.deleteForbiddenTags(v));
\r
402 } else if (k.equals("description")) {
\r
403 String tmp = StringUtil.deleteForbiddenTags(v);
\r
404 withValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
\r
406 withValues.put(k,StringUtil.removeHTMLTags(v));
\r
411 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
\r
412 withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
\r
413 withValues.put("is_produced", "0");
\r
414 // by default stuff is published, they can be un-published through the
\r
415 // admin interface.
\r
416 withValues.put("is_published","1");
\r
417 // if op direct article-type == newswire
\r
418 if (directOp.equals("yes")) withValues.put("to_article_type","1");
\r
420 withValues.put("to_publisher","1");
\r
422 // owner is openposting user
\r
423 // ML: this is not multi-language friendly and this can be done in a template
\r
424 // if (withValues.get("creator").toString().equals(""))
\r
425 // withValues.put("creator","Anonym");
\r
427 // inserting content into database
\r
428 String cid = contentModule.add(withValues);
\r
429 logger.debug("id: "+cid);
\r
430 //insert was not successfull
\r
432 //How do we know that it was not succesful cause of a
\r
433 //dupe, what if it failed cause of "No space left on device"?
\r
434 //Or is there something I am missing? Wouldn't it be better
\r
435 //to have an explicit dupe check and then insert? I have no
\r
436 //idea what I am talking about. this comment is in case
\r
437 //I forget to explicitely ask. -mh
\r
438 deliver(req, res, mergeData, postingFormDupeTemplate);
\r
441 String[] to_topicsArr = mp.getParameterValues("to_topic");
\r
443 if (to_topicsArr != null && to_topicsArr.length > 0) {
\r
445 DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
\r
448 catch (Exception e) {
\r
449 logger.error("setting content_x_topic failed");
\r
450 contentModule.deleteById(cid);
\r
451 throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
\r
455 //if we're here all is ok... associate the media to the article
\r
456 for(int i=0;i<mediaList.size();i++) {
\r
457 Entity mediaEnt = (Entity)mediaList.elementAt(i);
\r
458 DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());
\r
462 MirGlobal.localizer().openPostings().afterContentPosting(
\r
463 (EntityContent)contentModule.getById(cid));
\r
465 catch (Throwable t) {
\r
466 throw new ServletModuleException(t.getMessage());
\r
469 catch (FileHandlerException e) {
\r
470 e.printStackTrace(System.out);
\r
471 throw new ServletModuleException("MediaException: "+ e.getMessage());
\r
473 catch (IOException e) { throw new ServletModuleException("IOException: "+ e.getMessage());}
\r
474 catch (StorageObjectFailure e) { throw new ServletModuleException("StorageObjectException" + e.getMessage());}
\r
475 catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.getMessage());}
\r
477 deliver(req, res, mergeData, postingFormDoneTemplate);
\r
481 * Method for preparing and sending a content as an email message
\r
484 public void mail(HttpServletRequest req, HttpServletResponse res)
\r
485 throws ServletModuleException, ServletModuleUserException {
\r
486 String aid = req.getParameter("mail_aid");
\r
488 throw new ServletModuleUserException("An article id must be specified in requests to email an article. Something therefore went badly wrong....");
\r
491 String to = req.getParameter("mail_to");
\r
492 String from = req.getParameter("mail_from");
\r
493 String from_name = req.getParameter("mail_from_name");
\r
494 String comment = req.getParameter("mail_comment");
\r
495 String mail_language = req.getParameter("mail_language");
\r
497 SimpleHash mergeData = new SimpleHash();
\r
499 if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
\r
501 for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {
\r
502 String pName=(String)theParams.nextElement();
\r
503 if (pName.startsWith("mail_")){
\r
504 mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));
\r
507 deliver(req,res,mergeData,prepareMailTemplate);
\r
510 //run checks on to and from and mail_language to make sure no monkey business occurring
\r
511 if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ){
\r
512 throw new ServletModuleUserException("Sorry, you've entered an illegal character into the language field. Go back and try again, asshole.");
\r
514 if (to.indexOf('\n') != -1
\r
515 || to.indexOf('\r') != -1
\r
516 || to.indexOf(',') != -1
\r
517 || from.indexOf('\n') != -1
\r
518 || from.indexOf('\r') != -1
\r
519 || from.indexOf(',') != -1 ){
\r
520 throw new ServletModuleUserException("Sorry, you've entered an illegal character into the from or to field. Go back and try again.");
\r
522 EntityContent contentEnt;
\r
524 contentEnt = (EntityContent)contentModule.getById(aid);
\r
526 catch (ModuleException e){
\r
527 throw new ServletModuleUserException("Couldn't get content for article "+aid);
\r
529 String producerStorageRoot=configuration.getString("Producer.StorageRoot");
\r
530 String producerDocRoot=configuration.getString("Producer.DocRoot");
\r
531 String publishPath = contentEnt.getValue("publish_path");
\r
532 String txtFilePath = producerStorageRoot + producerDocRoot + "/" + mail_language +
\r
533 publishPath + "/" + aid + ".txt";
\r
536 File inputFile = new File(txtFilePath);
\r
540 FileReader in = new FileReader(inputFile);
\r
541 StringWriter out = new StringWriter();
\r
543 while ((c = in.read()) != -1)
\r
546 content= out.toString();
\r
548 catch (FileNotFoundException e){
\r
549 throw new ServletModuleUserException("No text file found in " + txtFilePath);
\r
551 catch (IOException e){
\r
552 throw new ServletModuleUserException("Problem reading file in " + txtFilePath);
\r
554 // add some headers
\r
555 content = "To: " + to + "\nReply-To: "+ from + "\n" + content;
\r
556 // put in the comment where it should go
\r
557 if (comment != null) {
\r
558 String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
\r
560 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
\r
562 catch (Exception e){
\r
563 throw new ServletModuleUserException("Problem doing regular expression replacement " + e.toString());
\r
568 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
\r
570 catch (Exception e){
\r
571 throw new ServletModuleUserException("Problem doing regular expression replacement " + e.toString());
\r
575 SMTPClient client=new SMTPClient();
\r
578 client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
\r
579 System.out.print(client.getReplyString());
\r
581 reply = client.getReplyCode();
\r
583 if(!SMTPReply.isPositiveCompletion(reply)) {
\r
584 client.disconnect();
\r
585 throw new ServletModuleUserException("SMTP server refused connection.");
\r
588 client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"),to,content);
\r
590 client.disconnect();
\r
591 //mission accomplished
\r
592 deliver(req,res,mergeData,sentMailTemplate);
\r
593 } catch(IOException e) {
\r
594 if(client.isConnected()) {
\r
596 client.disconnect();
\r
597 } catch(IOException f) {
\r
601 throw new ServletModuleUserException(e.toString());
\r
608 * Method for querying a lucene index
\r
610 public void search(HttpServletRequest req, HttpServletResponse res)
\r
611 throws ServletModuleException, ServletModuleUserException {
\r
615 HttpSession session = req.getSession(false);
\r
617 String queryString="";
\r
619 SimpleHash mergeData = new SimpleHash();
\r
621 KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted","search_date","webdb_create_formatted","webdb_create_formatted","webdb_create_formatted");
\r
622 UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("","","","where","where");
\r
623 TextSearchTerm creatorTerm = new TextSearchTerm("creator","search_creator","creator","creator","creator");
\r
624 TextSearchTerm titleTerm = new TextSearchTerm("title","search_content","title","title","title");
\r
625 TextSearchTerm descriptionTerm = new TextSearchTerm("description","search_content","description","description","description");
\r
626 ContentSearchTerm contentTerm = new ContentSearchTerm("content_data","search_content","content","","");
\r
627 TopicSearchTerm topicTerm = new TopicSearchTerm();
\r
628 ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
\r
629 AudioSearchTerm audioTerm = new AudioSearchTerm();
\r
630 VideoSearchTerm videoTerm = new VideoSearchTerm();
\r
632 //make the query available to subsequent iterations
\r
634 for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {
\r
635 String pName=(String)theParams.nextElement();
\r
636 if (pName.startsWith("search_")){
\r
637 mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));
\r
642 mergeData.put("topics", themenModule.getTopicsAsSimpleList());
\r
644 catch(ModuleException e) {
\r
645 logger.debug("Can't get topics: " + e.toString());
\r
648 String searchBackValue = req.getParameter("search_back");
\r
649 String searchForwardValue = req.getParameter("search_forward");
\r
651 if (searchBackValue != null){
\r
652 int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();
\r
653 int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()-increment;
\r
656 if (newPosition >= totalHits)
\r
657 newPosition=totalHits-1;
\r
658 session.setAttribute("positionInResults",new Integer(newPosition));
\r
661 if (searchForwardValue != null){
\r
662 int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();
\r
663 int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment;
\r
666 if (newPosition >= totalHits)
\r
667 newPosition=totalHits-1;
\r
669 session.setAttribute("positionInResults",new Integer(newPosition));
\r
672 String indexPath=configuration.getString("IndexPath");
\r
675 String creatorFragment = creatorTerm.makeTerm(req);
\r
676 if (creatorFragment != null){
\r
677 queryString = queryString + " +" + creatorFragment;
\r
680 // search title, description, and content for something
\r
681 // the contentTerm uses param "search_boolean" to combine its terms
\r
682 String contentFragment = contentTerm.makeTerm(req);
\r
683 if (contentFragment != null){
\r
684 logger.debug("contentFragment: " + contentFragment);
\r
685 queryString = queryString + " +" + contentFragment;
\r
688 String topicFragment = topicTerm.makeTerm(req);
\r
689 if (topicFragment != null){
\r
690 queryString = queryString + " +" + topicFragment;
\r
693 String imagesFragment = imagesTerm.makeTerm(req);
\r
694 if (imagesFragment != null){
\r
695 queryString = queryString + " +" + imagesFragment;
\r
698 String audioFragment = audioTerm.makeTerm(req);
\r
699 if (audioFragment != null){
\r
700 queryString = queryString + " +" + audioFragment;
\r
703 String videoFragment = videoTerm.makeTerm(req);
\r
704 if (videoFragment != null){
\r
705 queryString = queryString + " +" + videoFragment;
\r
708 if (queryString == null || queryString == ""){
\r
713 Searcher searcher = null;
\r
715 searcher = new IndexSearcher(indexPath);
\r
717 catch(IOException e) {
\r
718 logger.debug("Can't open indexPath: " + indexPath);
\r
719 throw new ServletModuleUserException("Problem with Search Index! : "+ e.toString());
\r
722 Query query = null;
\r
724 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
\r
726 catch(Exception e) {
\r
728 logger.debug("Query don't parse: " + queryString);
\r
729 throw new ServletModuleUserException("Problem with Query String! (was '"+queryString+"')");
\r
734 hits = searcher.search(query);
\r
736 catch(IOException e) {
\r
738 logger.debug("Can't get hits: " + e.toString());
\r
739 throw new ServletModuleUserException("Problem getting hits!");
\r
743 int end = hits.length();
\r
745 String sortBy=req.getParameter("search_sort");
\r
746 if (sortBy == null || sortBy.equals("")){
\r
747 throw new ServletModuleUserException("Please let me sort by something!(missing search_sort)");
\r
750 // here is where the documents will go for storage across sessions
\r
751 ArrayList theDocumentsSorted = new ArrayList();
\r
753 if (sortBy.equals("score")){
\r
754 for(int i = start; i < end; i++) {
\r
755 theDocumentsSorted.add(hits.doc(i));
\r
759 // then we'll sort by date!
\r
760 HashMap dateToPosition = new HashMap(end,1.0F); //we know how big it will be
\r
761 for(int i = start; i < end; i++) {
\r
762 String creationDate=(hits.doc(i)).get("creationDate");
\r
763 // do a little dance in case two contents created at the same second!
\r
764 if (dateToPosition.containsKey(creationDate)){
\r
765 ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
\r
768 ArrayList thePositions = new ArrayList();
\r
769 thePositions.add(new Integer(i));
\r
770 dateToPosition.put(creationDate,thePositions);
\r
773 Set keys = dateToPosition.keySet();
\r
774 ArrayList keyList= new ArrayList(keys);
\r
775 Collections.sort(keyList);
\r
776 if (sortBy.equals("date_desc")){
\r
777 Collections.reverse(keyList);
\r
780 if (!sortBy.equals("date_asc")){
\r
781 throw new ServletModuleUserException("don't know how to sort by: "+ sortBy);
\r
784 ListIterator keyTraverser = keyList.listIterator();
\r
785 while (keyTraverser.hasNext()){
\r
786 ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next()));
\r
787 ListIterator positionsTraverser=positions.listIterator();
\r
788 while (positionsTraverser.hasNext()){
\r
789 theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue()));
\r
797 catch (IOException e){
\r
798 logger.debug("Can't close searcher: " + e.toString());
\r
799 throw new ServletModuleUserException("Problem closing searcher(normal)!");
\r
803 session.removeAttribute("numberOfHits");
\r
804 session.removeAttribute("theDocumentsSorted");
\r
805 session.removeAttribute("positionInResults");
\r
807 session.setAttribute("numberOfHits",new Integer(end));
\r
808 session.setAttribute("theDocumentsSorted",theDocumentsSorted);
\r
809 session.setAttribute("positionInResults",new Integer(0));
\r
812 catch (IOException e){
\r
813 logger.debug("Can't close searcher: " + e.toString());
\r
814 throw new ServletModuleUserException("Problem closing searcher!");
\r
821 ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted");
\r
822 if (theDocs != null){
\r
824 mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString());
\r
825 SimpleList theHits = new SimpleList();
\r
826 int pIR=((Integer)session.getAttribute("positionInResults")).intValue();
\r
828 int numHits=((Integer)session.getAttribute("numberOfHits")).intValue();
\r
830 if (!(pIR+increment>=numHits)){
\r
831 mergeData.put("hasNext","y");
\r
834 mergeData.put("hasPrevious","y");
\r
837 if ((pIR+increment)>numHits){
\r
841 terminus=pIR+increment;
\r
843 for(int i = pIR; i < terminus; i++) {
\r
844 SimpleHash h = new SimpleHash();
\r
845 Document theHit = (Document)theDocs.get(i);
\r
846 whereTerm.returnMeta(h,theHit);
\r
847 creatorTerm.returnMeta(h,theHit);
\r
848 titleTerm.returnMeta(h,theHit);
\r
849 descriptionTerm.returnMeta(h,theHit);
\r
850 dateTerm.returnMeta(h,theHit);
\r
851 imagesTerm.returnMeta(h,theHit);
\r
852 audioTerm.returnMeta(h,theHit);
\r
853 videoTerm.returnMeta(h,theHit);
\r
856 mergeData.put("hits",theHits);
\r
859 catch (Exception e) {
\r
860 logger.debug("Can't iterate over hits: " + e.toString());
\r
861 throw new ServletModuleUserException("Problem getting hits!");
\r
864 mergeData.put("queryString",queryString);
\r
865 deliver(req,res,mergeData,searchResultsTemplate);
\r
867 catch (NullPointerException n){
\r
868 n.printStackTrace();
\r
869 throw new ServletModuleUserException("Null Pointer"+n.toString());
\r
874 * Method for dynamically generating a pdf from a fo file
\r
876 public void getpdf(HttpServletRequest req, HttpServletResponse res)
\r
877 throws ServletModuleException, ServletModuleUserException {
\r
878 String ID_REQUEST_PARAM = "id";
\r
879 String language = req.getParameter("language");
\r
880 String generateFO=configuration.getString("GenerateFO");
\r
881 String generatePDF=configuration.getString("GeneratePDF");
\r
884 //don't do anything if we are not making FO files, or if we are
\r
885 //pregenerating PDF's
\r
886 if (generateFO.equals("yes") && generatePDF.equals("no")){
\r
887 //fop complains unless you do the logging this way
\r
888 org.apache.log.Logger log = null;
\r
889 Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
\r
890 log = hierarchy.getLoggerFor("fop");
\r
891 log.setPriority(Priority.WARN);
\r
893 String producerStorageRoot=configuration.getString("Producer.StorageRoot");
\r
894 String producerDocRoot=configuration.getString("Producer.DocRoot");
\r
895 // String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
\r
896 String xslSheet=configuration.getString("Producer.HTML2FOStyleSheet");
\r
898 String idParam = req.getParameter(ID_REQUEST_PARAM);
\r
899 if (idParam != null) {
\r
900 EntityContent contentEnt =
\r
901 (EntityContent)contentModule.getById(idParam);
\r
902 String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date"));
\r
905 if (language == null){
\r
906 foFile = producerStorageRoot + producerDocRoot + "/"
\r
907 + publishPath + idParam + ".fo";
\r
910 foFile = producerStorageRoot + producerDocRoot + "/"
\r
911 + language + publishPath + idParam + ".fo";
\r
913 logger.debug("USING FILES" + foFile + " and " + xslSheet);
\r
914 XSLTInputHandler input = new XSLTInputHandler(new File(foFile),
\r
915 new File(xslSheet));
\r
917 ByteArrayOutputStream out = new ByteArrayOutputStream();
\r
918 res.setContentType("application/pdf");
\r
920 Driver driver = new Driver();
\r
921 driver.setLogger(log);
\r
922 driver.setRenderer(Driver.RENDER_PDF);
\r
923 driver.setOutputStream(out);
\r
924 driver.render(input.getParser(), input.getInputSource());
\r
926 byte[] content = out.toByteArray();
\r
927 res.setContentLength(content.length);
\r
928 res.getOutputStream().write(content);
\r
929 res.getOutputStream().flush();
\r
931 throw new ServletModuleUserException("Missing id parameter.");
\r
933 } catch (Exception ex) {
\r
934 logger.error(ex.toString());
\r
935 throw new ServletModuleException(ex.toString());
\r
938 throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");
\r
942 private void _throwBadContentType (String fileName, String contentType)
\r
943 throws ServletModuleUserException {
\r
945 logger.error("Wrong file type uploaded!: " + fileName+" "
\r
947 throw new ServletModuleUserException("The file you uploaded is of the "
\r
948 +"following mime-type: "+contentType
\r
949 +", we do not support this mime-type. "
\r
950 +"Error One or more files of unrecognized type. Sorry");
\r
953 protected String createOneTimePasswd(){
\r
954 Random r = new Random();
\r
955 int random = r.nextInt();
\r
956 long l = System.currentTimeMillis();
\r
957 l = (l*l*l*l)/random;
\r
958 if(l<0) l = l * -1;
\r
959 String returnString = ""+l;
\r
960 return returnString.substring(5);
\r
964 /* this is an overwritten method of ServletModule in order
\r
965 to use different bundles for open and admin */
\r
966 public void deliver(HttpServletRequest req, HttpServletResponse res,
\r
967 TemplateModelRoot rtm, TemplateModelRoot popups,
\r
968 String templateFilename)
\r
969 throws ServletModuleException {
\r
970 if (rtm == null) rtm = new SimpleHash();
\r
972 PrintWriter out = res.getWriter();
\r
973 HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out,
\r
974 getLocale(req), "bundles.open");
\r
976 } catch (HTMLParseException e) {
\r
977 throw new ServletModuleException(e.toString());
\r
978 } catch (IOException e) {
\r
979 throw new ServletModuleException(e.toString());
\r