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
39 import java.lang.reflect.*;
\r
40 import javax.servlet.*;
\r
41 import javax.servlet.http.*;
\r
43 import freemarker.template.*;
\r
44 import com.oreilly.servlet.multipart.*;
\r
45 import com.oreilly.servlet.*;
\r
47 import org.apache.commons.net.smtp.*;
\r
49 import org.xml.sax.InputSource;
\r
50 import org.xml.sax.XMLReader;
\r
52 import org.apache.fop.apps.Driver;
\r
53 import org.apache.fop.apps.Version;
\r
54 import org.apache.fop.apps.XSLTInputHandler;
\r
56 import org.apache.lucene.analysis.standard.StandardAnalyzer;
\r
57 import org.apache.lucene.search.*;
\r
58 import org.apache.lucene.document.Document;
\r
59 import org.apache.lucene.document.Field;
\r
60 import org.apache.lucene.analysis.standard.*;
\r
61 import org.apache.lucene.queryParser.*;
\r
63 import org.apache.log.*;
\r
65 import mir.servlet.*;
\r
66 import mir.module.*;
\r
68 import mir.entity.*;
\r
69 import mir.storage.*;
\r
72 import mir.util.StringRoutines;
\r
74 import mircoders.entity.*;
\r
75 import mircoders.storage.*;
\r
76 import mircoders.module.*;
\r
77 import mircoders.producer.*;
\r
78 import mircoders.media.MediaRequest;
\r
79 import mircoders.global.*;
\r
80 import mircoders.localizer.*;
\r
81 import mircoders.search.*;
\r
84 * ServletModuleOpenIndy -
\r
85 * is the open-access-servlet, which is responsible for
\r
86 * adding comments to articles &
\r
87 * open-postings to the newswire
\r
89 * @author mir-coders group
\r
90 * @version $Id: ServletModuleOpenIndy.java,v 1.54 2003/01/13 16:08:32 john Exp $
\r
94 public class ServletModuleOpenIndy extends ServletModule
\r
97 private String commentFormTemplate, commentFormDoneTemplate,
\r
98 commentFormDupeTemplate;
\r
99 private String postingFormTemplate, postingFormDoneTemplate,
\r
100 postingFormDupeTemplate;
\r
101 private String searchResultsTemplate;
\r
102 private String prepareMailTemplate,sentMailTemplate;
\r
103 private ModuleContent contentModule;
\r
104 private ModuleComment commentModule;
\r
105 private ModuleImages imageModule;
\r
106 private ModuleTopics themenModule;
\r
107 private String directOp ="yes";
\r
108 private String passwdProtection ="yes";
\r
109 // Singelton / Kontruktor
\r
110 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
\r
111 public static ServletModule getInstance() { return instance; }
\r
113 private ServletModuleOpenIndy() {
\r
115 logger = new LoggerWrapper("ServletModule.OpenIndy");
\r
117 commentFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentTemplate");
\r
118 commentFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDoneTemplate");
\r
119 commentFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.CommentDupeTemplate");
\r
120 postingFormTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingTemplate");
\r
121 postingFormDoneTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDoneTemplate");
\r
122 postingFormDupeTemplate = MirConfig.getProp("ServletModule.OpenIndy.PostingDupeTemplate");
\r
123 searchResultsTemplate = MirConfig.getProp("ServletModule.OpenIndy.SearchResultsTemplate");
\r
124 prepareMailTemplate = MirConfig.getProp("ServletModule.OpenIndy.PrepareMailTemplate");
\r
125 sentMailTemplate = MirConfig.getProp("ServletModule.OpenIndy.SentMailTemplate");
\r
126 directOp = MirConfig.getProp("DirectOpenposting").toLowerCase();
\r
127 passwdProtection = MirConfig.getProp("PasswdProtection").toLowerCase();
\r
128 mainModule = new ModuleComment(DatabaseComment.getInstance());
\r
129 contentModule = new ModuleContent(DatabaseContent.getInstance());
\r
130 themenModule = new ModuleTopics(DatabaseTopics.getInstance());
\r
131 imageModule = new ModuleImages(DatabaseImages.getInstance());
\r
132 defaultAction="addposting";
\r
135 catch (StorageObjectException e) {
\r
136 logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
\r
142 * Method for making a comment
\r
145 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
\r
147 String aid = req.getParameter("aid"); // the article id the comment will belong to
\r
148 String language = req.getParameter("language");
\r
150 if (aid!=null && !aid.equals("")) {
\r
152 SimpleHash mergeData = new SimpleHash();
\r
155 if (passwdProtection.equals("yes")) {
\r
156 String passwd = this.createOneTimePasswd();
\r
157 System.out.println(passwd);
\r
158 HttpSession session = req.getSession(false);
\r
159 session.setAttribute("passwd", passwd);
\r
160 mergeData.put("passwd", passwd);
\r
163 if (language != null) {
\r
164 HttpSession session = req.getSession(false);
\r
165 session.setAttribute("Locale", new Locale(language, ""));
\r
166 session.setAttribute("passwd", language);
\r
169 mergeData.put("aid", aid);
\r
171 SimpleHash extraInfo = new SimpleHash();
\r
172 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
\r
174 deliver(req, res, mergeData, extraInfo, commentFormTemplate);
\r
176 catch (Throwable t) {
\r
177 throw new ServletModuleException("ServletModuleOpenIndy.addcomment: " + t.getMessage());
\r
180 else throw new ServletModuleException("aid not set!");
\r
184 * Method for inserting a comment into the Database and delivering
\r
185 * the commentDone Page
\r
188 public void inscomment(HttpServletRequest req, HttpServletResponse res)
\r
189 throws ServletModuleException,ServletModuleUserException
\r
191 String aid = req.getParameter("to_media"); // the article id the comment will belong to
\r
192 if (aid!=null && !aid.equals(""))
\r
194 // ok, collecting data from form
\r
196 HashMap withValues = getIntersectingValues(req, DatabaseComment.getInstance());
\r
198 //no html in comments(for now)
\r
199 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
\r
200 String k=(String)i.next();
\r
201 String v=(String)withValues.get(k);
\r
203 withValues.put(k,StringUtil.removeHTMLTags(v));
\r
205 withValues.put("is_published","1");
\r
206 withValues.put("to_comment_status","1");
\r
208 //checking the onetimepasswd
\r
209 if(passwdProtection.equals("yes")){
\r
210 HttpSession session = req.getSession(false);
\r
211 String sessionPasswd = (String)session.getAttribute("passwd");
\r
212 if ( sessionPasswd == null){
\r
213 throw new ServletModuleUserException("Lost password");
\r
215 String passwd = req.getParameter("passwd");
\r
216 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
\r
217 throw new ServletModuleUserException("Missing password");
\r
219 session.invalidate();
\r
222 // inserting into database
\r
223 String id = mainModule.add(withValues);
\r
224 logger.debug("id: "+id);
\r
225 //insert was not successfull
\r
227 deliver(req, res, new SimpleHash(), commentFormDupeTemplate);
\r
229 DatabaseContent.getInstance().setUnproduced("id="+aid);
\r
232 EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
\r
233 MirGlobal.localizer().openPostings().afterCommentPosting(comment);
\r
235 catch (Throwable t) {
\r
236 throw new ServletModuleException(t.getMessage());
\r
240 // redirecting to url
\r
241 // should implement back to article
\r
242 SimpleHash mergeData = new SimpleHash();
\r
243 deliver(req, res, mergeData, commentFormDoneTemplate);
\r
245 catch (StorageObjectException e) { throw new ServletModuleException(e.toString());}
\r
246 catch (ModuleException e) { throw new ServletModuleException(e.toString());}
\r
249 else throw new ServletModuleException("aid not set!");
\r
254 * Method for delivering the form-Page for open posting
\r
257 public void addposting(HttpServletRequest req, HttpServletResponse res)
\r
258 throws ServletModuleException {
\r
259 SimpleHash mergeData = new SimpleHash();
\r
262 if(passwdProtection.equals("yes")){
\r
263 String passwd = this.createOneTimePasswd();
\r
264 System.out.println(passwd);
\r
265 HttpSession session = req.getSession(false);
\r
266 session.setAttribute("passwd",passwd);
\r
267 mergeData.put("passwd", passwd);
\r
270 String maxMedia = MirConfig.getProp("ServletModule.OpenIndy.MaxMediaUploadItems");
\r
271 String defaultMedia = MirConfig.getProp("ServletModule.OpenIndy.DefaultMediaUploadItems");
\r
272 String numOfMedia = req.getParameter("medianum");
\r
274 if(numOfMedia==null||numOfMedia.equals("")){
\r
275 numOfMedia=defaultMedia;
\r
277 else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
\r
278 numOfMedia = maxMedia;
\r
281 int mediaNum = Integer.parseInt(numOfMedia);
\r
282 SimpleList mediaFields = new SimpleList();
\r
283 for(int i =0; i<mediaNum;i++){
\r
284 Integer mNum = new Integer(i+1);
\r
285 mediaFields.add(mNum.toString());
\r
287 mergeData.put("medianum",numOfMedia);
\r
288 mergeData.put("mediafields",mediaFields);
\r
291 SimpleHash extraInfo = new SimpleHash();
\r
293 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData() );
\r
294 extraInfo.put("themenPopupData", themenModule.getTopicsAsSimpleList());
\r
296 extraInfo.put("topics", themenModule.getTopicsList());
\r
299 catch (Exception e) {
\r
300 logger.error("languagePopUpData or getTopicslist failed "+e.toString());
\r
301 throw new ServletModuleException("OpenIndy -- failed getting language or topics: "+e.toString());
\r
306 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
\r
310 * Method for inserting an open posting into the Database and delivering
\r
311 * the postingDone Page
\r
314 public void insposting(HttpServletRequest req, HttpServletResponse res)
\r
315 throws ServletModuleException, ServletModuleUserException
\r
317 SimpleHash mergeData = new SimpleHash();
\r
318 boolean setMedia=false;
\r
319 boolean setTopic = false;
\r
323 WebdbMultipartRequest mp = null;
\r
324 EntityList mediaList = null;
\r
326 // new MediaRequest, "1" is the id for the openPosting user
\r
327 MediaRequest mediaReq = new MediaRequest("1", true, true);
\r
328 mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq);
\r
329 mediaList = mediaReq.getEntityList();
\r
331 catch (FileHandlerUserException e) {
\r
332 throw new ServletModuleUserException(e.getMessage());
\r
335 HashMap withValues = mp.getParameters();
\r
337 //checking the onetimepasswd
\r
338 if(passwdProtection.equals("yes")){
\r
339 HttpSession session = req.getSession(false);
\r
340 String sessionPasswd = (String)session.getAttribute("passwd");
\r
341 if ( sessionPasswd == null){
\r
342 throw new ServletModuleUserException("Lost password");
\r
344 String passwd = (String)withValues.get("passwd");
\r
345 if ( passwd == null || (!sessionPasswd.equals(passwd))) {
\r
346 throw new ServletModuleUserException("Missing password");
\r
348 session.invalidate();
\r
351 if ((((String)withValues.get("title")).length() == 0) ||
\r
352 (((String)withValues.get("description")).length() == 0) ||
\r
353 (((String)withValues.get("content_data")).length() == 0))
\r
354 throw new ServletModuleUserException("Missing field");
\r
356 // call the routines that escape html
\r
358 for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){
\r
359 String k=(String)i.next();
\r
360 String v=(String)withValues.get(k);
\r
362 if (k.equals("content_data")){
\r
363 //this doesn't quite work yet, so for now, all html goes
\r
364 //withValues.put(k,StringUtil.approveHTMLTags(v));
\r
365 withValues.put(k,StringUtil.deleteForbiddenTags(v));
\r
366 } else if (k.equals("description")) {
\r
367 String tmp = StringUtil.deleteForbiddenTags(v);
\r
368 withValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
\r
370 withValues.put(k,StringUtil.removeHTMLTags(v));
\r
375 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
\r
376 withValues.put("publish_path", StringUtil.webdbDate2path((String)withValues.get("date")));
\r
377 withValues.put("is_produced", "0");
\r
378 // by default stuff is published, they can be un-published through the
\r
379 // admin interface.
\r
380 withValues.put("is_published","1");
\r
381 // if op direct article-type == newswire
\r
382 if (directOp.equals("yes")) withValues.put("to_article_type","1");
\r
384 withValues.put("to_publisher","1");
\r
386 // owner is openposting user
\r
387 // ML: this is not multi-language friendly and this can be done in a template
\r
388 // if (withValues.get("creator").toString().equals(""))
\r
389 // withValues.put("creator","Anonym");
\r
391 // inserting content into database
\r
392 String cid = contentModule.add(withValues);
\r
393 logger.debug("id: "+cid);
\r
394 //insert was not successfull
\r
396 //How do we know that it was not succesful cause of a
\r
397 //dupe, what if it failed cause of "No space left on device"?
\r
398 //Or is there something I am missing? Wouldn't it be better
\r
399 //to have an explicit dupe check and then insert? I have no
\r
400 //idea what I am talking about. this comment is in case
\r
401 //I forget to explicitely ask. -mh
\r
402 deliver(req, res, mergeData, postingFormDupeTemplate);
\r
405 String[] to_topicsArr = mp.getParameterValues("to_topic");
\r
407 if (to_topicsArr != null && to_topicsArr.length > 0) {
\r
409 DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr);
\r
412 catch (Exception e) {
\r
413 logger.error("setting content_x_topic failed");
\r
414 contentModule.deleteById(cid);
\r
415 throw new ServletModuleException("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString());
\r
419 //if we're here all is ok... associate the media to the article
\r
420 for(int i=0;i<mediaList.size();i++) {
\r
421 Entity mediaEnt = (Entity)mediaList.elementAt(i);
\r
422 DatabaseContentToMedia.getInstance().addMedia(cid,mediaEnt.getId());
\r
426 MirGlobal.localizer().openPostings().afterContentPosting(
\r
427 (EntityContent)contentModule.getById(cid));
\r
429 catch (Throwable t) {
\r
430 throw new ServletModuleException(t.getMessage());
\r
433 catch (FileHandlerException e) {
\r
434 e.printStackTrace(System.out);
\r
435 throw new ServletModuleException("MediaException: "+ e.getMessage());
\r
437 catch (IOException e) { throw new ServletModuleException("IOException: "+ e.getMessage());}
\r
438 catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.getMessage());}
\r
439 catch (ModuleException e) { throw new ServletModuleException("ModuleException"+e.getMessage());}
\r
441 deliver(req, res, mergeData, postingFormDoneTemplate);
\r
445 * Method for preparing and sending a content as an email message
\r
448 public void mail(HttpServletRequest req, HttpServletResponse res)
\r
449 throws ServletModuleException, ServletModuleUserException {
\r
450 String aid = req.getParameter("mail_aid");
\r
452 throw new ServletModuleUserException("An article id must be specified in requests to email an article. Something therefore went badly wrong....");
\r
455 String to = req.getParameter("mail_to");
\r
456 String from = req.getParameter("mail_from");
\r
457 String from_name = req.getParameter("mail_from_name");
\r
458 String comment = req.getParameter("mail_comment");
\r
459 String mail_language = req.getParameter("mail_language");
\r
461 SimpleHash mergeData = new SimpleHash();
\r
463 if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
\r
465 for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {
\r
466 String pName=(String)theParams.nextElement();
\r
467 if (pName.startsWith("mail_")){
\r
468 mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));
\r
471 deliver(req,res,mergeData,prepareMailTemplate);
\r
474 //run checks on to and from and mail_language to make sure no monkey business occurring
\r
475 if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ){
\r
476 throw new ServletModuleUserException("Sorry, you've entered an illegal character into the language field. Go back and try again, asshole.");
\r
478 if (to.indexOf('\n') != -1
\r
479 || to.indexOf('\r') != -1
\r
480 || to.indexOf(',') != -1
\r
481 || from.indexOf('\n') != -1
\r
482 || from.indexOf('\r') != -1
\r
483 || from.indexOf(',') != -1 ){
\r
484 throw new ServletModuleUserException("Sorry, you've entered an illegal character into the from or to field. Go back and try again.");
\r
486 EntityContent contentEnt;
\r
488 contentEnt = (EntityContent)contentModule.getById(aid);
\r
490 catch (ModuleException e){
\r
491 throw new ServletModuleUserException("Couldn't get content for article "+aid);
\r
493 String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");
\r
494 String producerDocRoot=MirConfig.getProp("Producer.DocRoot");
\r
495 String publishPath = contentEnt.getValue("publish_path");
\r
496 String txtFilePath = producerStorageRoot + producerDocRoot + "/" + mail_language +
\r
497 publishPath + "/" + aid + ".txt";
\r
500 File inputFile = new File(txtFilePath);
\r
504 FileReader in = new FileReader(inputFile);
\r
505 StringWriter out = new StringWriter();
\r
507 while ((c = in.read()) != -1)
\r
510 content= out.toString();
\r
512 catch (FileNotFoundException e){
\r
513 throw new ServletModuleUserException("No text file found in " + txtFilePath);
\r
515 catch (IOException e){
\r
516 throw new ServletModuleUserException("Problem reading file in " + txtFilePath);
\r
518 // add some headers
\r
519 content = "To: " + to + "\nReply-To: "+ from + "\n" + content;
\r
520 // put in the comment where it should go
\r
521 if (comment != null) {
\r
522 String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
\r
524 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
\r
526 catch (Exception e){
\r
527 throw new ServletModuleUserException("Problem doing regular expression replacement " + e.toString());
\r
532 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
\r
534 catch (Exception e){
\r
535 throw new ServletModuleUserException("Problem doing regular expression replacement " + e.toString());
\r
539 SMTPClient client=new SMTPClient();
\r
542 client.connect("localhost");
\r
543 System.out.print(client.getReplyString());
\r
545 reply = client.getReplyCode();
\r
547 if(!SMTPReply.isPositiveCompletion(reply)) {
\r
548 client.disconnect();
\r
549 throw new ServletModuleUserException("SMTP server refused connection.");
\r
552 client.sendSimpleMessage(MirConfig.getProp("ServletModule.OpenIndy.EmailIsFrom"),to,content);
\r
554 client.disconnect();
\r
555 //mission accomplished
\r
556 deliver(req,res,mergeData,sentMailTemplate);
\r
558 } catch(IOException e) {
\r
559 if(client.isConnected()) {
\r
561 client.disconnect();
\r
562 } catch(IOException f) {
\r
566 throw new ServletModuleUserException(e.toString());
\r
573 * Method for querying a lucene index
\r
575 public void search(HttpServletRequest req, HttpServletResponse res)
\r
576 throws ServletModuleException, ServletModuleUserException {
\r
580 HttpSession session = req.getSession(false);
\r
582 String queryString="";
\r
584 SimpleHash mergeData = new SimpleHash();
\r
586 KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted","search_date","webdb_create_formatted","webdb_create_formatted","webdb_create_formatted");
\r
587 UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("","","","where","where");
\r
588 TextSearchTerm creatorTerm = new TextSearchTerm("creator","search_creator","creator","creator","creator");
\r
589 TextSearchTerm titleTerm = new TextSearchTerm("title","search_content","title","title","title");
\r
590 TextSearchTerm descriptionTerm = new TextSearchTerm("description","search_content","description","description","description");
\r
591 ContentSearchTerm contentTerm = new ContentSearchTerm("content_data","search_content","content","","");
\r
592 TopicSearchTerm topicTerm = new TopicSearchTerm();
\r
593 ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
\r
594 AudioSearchTerm audioTerm = new AudioSearchTerm();
\r
595 VideoSearchTerm videoTerm = new VideoSearchTerm();
\r
597 //make the query available to subsequent iterations
\r
599 for (Enumeration theParams = req.getParameterNames(); theParams.hasMoreElements() ;) {
\r
600 String pName=(String)theParams.nextElement();
\r
601 if (pName.startsWith("search_")){
\r
602 mergeData.put(pName,new SimpleScalar(req.getParameter(pName)));
\r
607 mergeData.put("topics", themenModule.getTopicsAsSimpleList());
\r
609 catch(ModuleException e) {
\r
610 logger.debug("Can't get topics: " + e.toString());
\r
613 String searchSubmitValue = req.getParameter("search_submit");
\r
615 if (searchSubmitValue != null && searchSubmitValue.equals("Back")){
\r
616 int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();
\r
617 int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()-increment;
\r
618 if (newPosition < 0 || newPosition >= totalHits){
\r
619 throw new ServletModuleUserException("newPosition: index out bounds, value was:"+(new Integer(newPosition)).toString());
\r
621 session.setAttribute("positionInResults",new Integer(newPosition));
\r
625 if (searchSubmitValue != null && searchSubmitValue.equals("Forward")){
\r
626 int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue();
\r
627 int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment;
\r
628 if (newPosition < 0 || newPosition >= totalHits){
\r
629 throw new ServletModuleUserException("newPosition: index out bounds, value was:"+(new Integer(newPosition)).toString());
\r
631 session.setAttribute("positionInResults",new Integer(newPosition));
\r
635 String indexPath=MirConfig.getProp("IndexPath");
\r
638 String creatorFragment = creatorTerm.makeTerm(req);
\r
639 if (creatorFragment != null){
\r
640 queryString = queryString + " +" + creatorFragment;
\r
643 // search title, description, and content for something
\r
644 // the contentTerm uses param "search_boolean" to combine its terms
\r
645 String contentFragment = contentTerm.makeTerm(req);
\r
646 if (contentFragment != null){
\r
647 logger.debug("contentFragment: " + contentFragment);
\r
648 queryString = queryString + " +" + contentFragment;
\r
651 String topicFragment = topicTerm.makeTerm(req);
\r
652 if (topicFragment != null){
\r
653 queryString = queryString + " +" + topicFragment;
\r
656 String imagesFragment = imagesTerm.makeTerm(req);
\r
657 if (imagesFragment != null){
\r
658 queryString = queryString + " +" + imagesFragment;
\r
661 String audioFragment = audioTerm.makeTerm(req);
\r
662 if (audioFragment != null){
\r
663 queryString = queryString + " +" + audioFragment;
\r
666 String videoFragment = videoTerm.makeTerm(req);
\r
667 if (videoFragment != null){
\r
668 queryString = queryString + " +" + videoFragment;
\r
671 if (queryString == null || queryString == ""){
\r
676 Searcher searcher = null;
\r
678 searcher = new IndexSearcher(indexPath);
\r
680 catch(IOException e) {
\r
681 logger.debug("Can't open indexPath: " + indexPath);
\r
682 throw new ServletModuleUserException("Problem with Search Index! : "+ e.toString());
\r
685 Query query = null;
\r
687 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
\r
689 catch(Exception e) {
\r
691 logger.debug("Query don't parse: " + queryString);
\r
692 throw new ServletModuleUserException("Problem with Query String! (was '"+queryString+"')");
\r
697 hits = searcher.search(query);
\r
699 catch(IOException e) {
\r
701 logger.debug("Can't get hits: " + e.toString());
\r
702 throw new ServletModuleUserException("Problem getting hits!");
\r
706 int end = hits.length();
\r
708 String sortBy=req.getParameter("search_sort");
\r
709 if (sortBy == null || sortBy.equals("")){
\r
710 throw new ServletModuleUserException("Please let me sort by something!(missing search_sort)");
\r
713 // here is where the documents will go for storage across sessions
\r
714 ArrayList theDocumentsSorted = new ArrayList();
\r
716 if (sortBy.equals("score")){
\r
717 for(int i = start; i < end; i++) {
\r
718 theDocumentsSorted.add(hits.doc(i));
\r
722 // then we'll sort by date!
\r
723 HashMap dateToPosition = new HashMap(end,1.0F); //we know how big it will be
\r
724 for(int i = start; i < end; i++) {
\r
725 String creationDate=(hits.doc(i)).get("creationDate");
\r
726 // do a little dance in case two contents created at the same second!
\r
727 if (dateToPosition.containsKey(creationDate)){
\r
728 ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
\r
731 ArrayList thePositions = new ArrayList();
\r
732 thePositions.add(new Integer(i));
\r
733 dateToPosition.put(creationDate,thePositions);
\r
736 Set keys = dateToPosition.keySet();
\r
737 ArrayList keyList= new ArrayList(keys);
\r
738 Collections.sort(keyList);
\r
739 if (sortBy.equals("date_desc")){
\r
740 Collections.reverse(keyList);
\r
743 if (!sortBy.equals("date_asc")){
\r
744 throw new ServletModuleUserException("don't know how to sort by: "+ sortBy);
\r
747 ListIterator keyTraverser = keyList.listIterator();
\r
748 while (keyTraverser.hasNext()){
\r
749 ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next()));
\r
750 ListIterator positionsTraverser=positions.listIterator();
\r
751 while (positionsTraverser.hasNext()){
\r
752 theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue()));
\r
760 catch (IOException e){
\r
761 logger.debug("Can't close searcher: " + e.toString());
\r
762 throw new ServletModuleUserException("Problem closing searcher(normal)!");
\r
766 session.removeAttribute("numberOfHits");
\r
767 session.removeAttribute("theDocumentsSorted");
\r
768 session.removeAttribute("positionInResults");
\r
770 session.setAttribute("numberOfHits",new Integer(end));
\r
771 session.setAttribute("theDocumentsSorted",theDocumentsSorted);
\r
772 session.setAttribute("positionInResults",new Integer(0));
\r
775 catch (IOException e){
\r
776 logger.debug("Can't close searcher: " + e.toString());
\r
777 throw new ServletModuleUserException("Problem closing searcher!");
\r
784 ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted");
\r
785 if (theDocs != null){
\r
787 mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString());
\r
788 SimpleList theHits = new SimpleList();
\r
789 int pIR=((Integer)session.getAttribute("positionInResults")).intValue();
\r
791 int numHits=((Integer)session.getAttribute("numberOfHits")).intValue();
\r
793 if (!(pIR+increment>=numHits)){
\r
794 mergeData.put("hasNext","y");
\r
796 if (pIR-increment>=0){
\r
797 mergeData.put("hasPrevious","y");
\r
800 if ((pIR+increment)>numHits){
\r
804 terminus=pIR+increment;
\r
806 for(int i = pIR; i < terminus; i++) {
\r
807 SimpleHash h = new SimpleHash();
\r
808 Document theHit = (Document)theDocs.get(i);
\r
809 whereTerm.returnMeta(h,theHit);
\r
810 creatorTerm.returnMeta(h,theHit);
\r
811 titleTerm.returnMeta(h,theHit);
\r
812 descriptionTerm.returnMeta(h,theHit);
\r
813 dateTerm.returnMeta(h,theHit);
\r
814 imagesTerm.returnMeta(h,theHit);
\r
815 audioTerm.returnMeta(h,theHit);
\r
816 videoTerm.returnMeta(h,theHit);
\r
819 mergeData.put("hits",theHits);
\r
822 catch (Exception e) {
\r
823 logger.debug("Can't iterate over hits: " + e.toString());
\r
824 throw new ServletModuleUserException("Problem getting hits!");
\r
827 mergeData.put("queryString",queryString);
\r
828 deliver(req,res,mergeData,searchResultsTemplate);
\r
830 catch (NullPointerException n){
\r
831 n.printStackTrace();
\r
832 throw new ServletModuleUserException("Null Pointer"+n.toString());
\r
837 * Method for dynamically generating a pdf from a fo file
\r
839 public void getpdf(HttpServletRequest req, HttpServletResponse res)
\r
840 throws ServletModuleException, ServletModuleUserException {
\r
841 String ID_REQUEST_PARAM = "id";
\r
842 String language = req.getParameter("language");
\r
844 String generateFO=MirConfig.getProp("GenerateFO");
\r
845 String generatePDF=MirConfig.getProp("GeneratePDF");
\r
847 //don't do anything if we are not making FO files, or if we are
\r
848 //pregenerating PDF's
\r
849 if (generateFO.equals("yes") && generatePDF.equals("no")){
\r
850 //fop complains unless you do the logging this way
\r
851 org.apache.log.Logger log = null;
\r
852 Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
\r
853 log = hierarchy.getLoggerFor("fop");
\r
854 log.setPriority(Priority.WARN);
\r
856 String producerStorageRoot=MirConfig.getProp("Producer.StorageRoot");
\r
857 String producerDocRoot=MirConfig.getProp("Producer.DocRoot");
\r
858 // String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir");
\r
859 String xslSheet=MirConfig.getProp("Producer.HTML2FOStyleSheet");
\r
861 String idParam = req.getParameter(ID_REQUEST_PARAM);
\r
862 if (idParam != null) {
\r
863 EntityContent contentEnt =
\r
864 (EntityContent)contentModule.getById(idParam);
\r
865 String publishPath = contentEnt.getValue("publish_path");
\r
868 if (language == null){
\r
869 foFile = producerStorageRoot + producerDocRoot + "/"
\r
870 + publishPath + idParam + ".fo";
\r
873 foFile = producerStorageRoot + producerDocRoot + "/"
\r
874 + language + publishPath + idParam + ".fo";
\r
876 logger.debug("USING FILES" + foFile + " and " + xslSheet);
\r
877 XSLTInputHandler input = new XSLTInputHandler(new File(foFile),
\r
878 new File(xslSheet));
\r
880 ByteArrayOutputStream out = new ByteArrayOutputStream();
\r
881 res.setContentType("application/pdf");
\r
883 Driver driver = new Driver();
\r
884 driver.setLogger(log);
\r
885 driver.setRenderer(Driver.RENDER_PDF);
\r
886 driver.setOutputStream(out);
\r
887 driver.render(input.getParser(), input.getInputSource());
\r
889 byte[] content = out.toByteArray();
\r
890 res.setContentLength(content.length);
\r
891 res.getOutputStream().write(content);
\r
892 res.getOutputStream().flush();
\r
894 throw new ServletModuleUserException("Missing id parameter.");
\r
896 } catch (Exception ex) {
\r
897 logger.error(ex.toString());
\r
898 throw new ServletModuleException(ex.toString());
\r
901 throw new ServletModuleUserException("Can't generate a PDF because the config tells me not to.");
\r
905 private void _throwBadContentType (String fileName, String contentType)
\r
906 throws ServletModuleUserException {
\r
908 logger.error("Wrong file type uploaded!: " + fileName+" "
\r
910 throw new ServletModuleUserException("The file you uploaded is of the "
\r
911 +"following mime-type: "+contentType
\r
912 +", we do not support this mime-type. "
\r
913 +"Error One or more files of unrecognized type. Sorry");
\r
916 protected String createOneTimePasswd(){
\r
917 Random r = new Random();
\r
918 int random = r.nextInt();
\r
919 long l = System.currentTimeMillis();
\r
920 l = (l*l*l*l)/random;
\r
921 if(l<0) l = l * -1;
\r
922 String returnString = ""+l;
\r
923 return returnString.substring(5);
\r
927 /* this is an overwritten method of ServletModule in order
\r
928 to use different bundles for open and admin */
\r
929 public void deliver(HttpServletRequest req, HttpServletResponse res,
\r
930 TemplateModelRoot rtm, TemplateModelRoot popups,
\r
931 String templateFilename)
\r
932 throws ServletModuleException {
\r
933 if (rtm == null) rtm = new SimpleHash();
\r
935 PrintWriter out = res.getWriter();
\r
936 HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out,
\r
937 getLocale(req), "bundles.open");
\r
939 } catch (HTMLParseException e) {
\r
940 throw new ServletModuleException(e.toString());
\r
941 } catch (IOException e) {
\r
942 throw new ServletModuleException(e.toString());
\r