2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
6 * Mir is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * Mir is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.f
16 * You should have received a copy of the GNU General Public License
17 * along with Mir; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * In addition, as a special exception, The Mir-coders gives permission to link
21 * the code of this program with any library licensed under the Apache Software License,
22 * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23 * (or with modified versions of the above that use the same license as the above),
24 * and distribute linked combinations including the two. You must obey the
25 * GNU General Public License in all respects for all of the code used other than
26 * the above mentioned libraries. If you modify this file, you may extend this
27 * exception to your version of the file, but you are not obligated to do so.
28 * If you do not wish to do so, delete this exception statement from your version.
31 package mircoders.servlet;
34 import gnu.regexp.REMatch;
35 import mir.bundle.Bundle;
36 import mir.entity.Entity;
37 import mir.generator.Generator;
38 import mir.log.LoggerWrapper;
39 import mir.misc.StringUtil;
40 import mir.servlet.ServletModule;
41 import mir.servlet.ServletModuleExc;
42 import mir.servlet.ServletModuleFailure;
43 import mir.servlet.ServletModuleUserExc;
45 import mir.storage.DatabaseFailure;
47 import mircoders.entity.EntityComment;
48 import mircoders.entity.EntityContent;
49 import mircoders.global.CacheKey;
50 import mircoders.global.MirGlobal;
51 import mircoders.media.MediaUploadProcessor;
52 import mircoders.media.UnsupportedMediaTypeExc;
53 import mircoders.module.ModuleComment;
54 import mircoders.module.ModuleContent;
55 import mircoders.pdf.PDFGenerator;
56 import mircoders.search.*;
57 import mircoders.storage.*;
58 import org.apache.commons.fileupload.FileItem;
59 import org.apache.commons.net.smtp.SMTPClient;
60 import org.apache.commons.net.smtp.SMTPReply;
61 import org.apache.lucene.analysis.standard.StandardAnalyzer;
62 import org.apache.lucene.document.Document;
63 import org.apache.lucene.queryParser.QueryParser;
64 import org.apache.lucene.search.Hits;
65 import org.apache.lucene.search.IndexSearcher;
66 import org.apache.lucene.search.Query;
67 import org.apache.lucene.search.Searcher;
68 import org.apache.lucene.store.FSDirectory;
70 import javax.servlet.http.HttpServletRequest;
71 import javax.servlet.http.HttpServletResponse;
72 import javax.servlet.http.HttpSession;
77 * ServletModuleOpenIndy -
78 * is the open-access-servlet, which is responsible for
79 * adding comments to articles &
80 * open-postings to the newswire
82 * @author mir-coders group
83 * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.18 2005/08/21 17:09:24 zapata Exp $
87 public class ServletModuleOpenIndy extends ServletModule
90 private String commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
91 private String postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
92 private String searchResultsTemplate;
93 private String prepareMailTemplate,sentMailTemplate,emailAnArticleTemplate;
94 private ModuleContent contentModule;
95 private ModuleComment commentModule;
96 private String directOp ="yes";
97 private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
99 public static ServletModule getInstance() {
103 private ServletModuleOpenIndy() {
106 logger = new LoggerWrapper("ServletModule.OpenIndy");
108 commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
109 commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
110 commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
112 postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
113 postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
114 postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
116 searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
117 prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
118 emailAnArticleTemplate = configuration.getString("ServletModule.OpenIndy.MailableArticleTemplate");
119 sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
120 directOp = configuration.getString("DirectOpenposting").toLowerCase();
121 commentModule = new ModuleComment();
122 mainModule = commentModule;
123 contentModule = new ModuleContent();
124 defaultAction = "defaultAction";
126 catch (DatabaseFailure e) {
127 logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
132 * Perform the default open posting action
134 public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
135 opensession(aRequest, aResponse);
139 * Method to return an out of service notice when open postings are disabled
143 * @throws ServletModuleExc
144 * @throws ServletModuleUserExc
145 * @throws ServletModuleFailure
147 public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
148 deliver(aRequest, aResponse, null, null, configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
152 * Method for making a comment
154 public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
155 if (MirGlobal.abuse().getOpenPostingDisabled()) {
156 openPostingDisabled(req, res);
161 String aid = req.getParameter("aid"); // the article id the comment will belong to
163 if (aid != null && !aid.equals("")) {
165 Map mergeData = new HashMap();
168 if (MirGlobal.abuse().getOpenPostingPassword()) {
169 String passwd = generateOnetimePassword();
170 HttpSession session = req.getSession(false);
171 session.setAttribute("passwd", passwd);
172 mergeData.put("passwd", passwd);
175 mergeData.put("passwd", null);
177 mergeData.put("aid", aid);
179 Map extraInfo = new HashMap();
180 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
182 deliver(req, res, mergeData, extraInfo, commentFormTemplate);
184 catch (Throwable t) {
185 throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
189 throw new ServletModuleExc("aid not set!");
193 * Method for inserting a comment into the Database and delivering
194 * the commentDone Page
197 public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
198 if (MirGlobal.abuse().getOpenPostingDisabled()) {
199 openPostingDisabled(req, res);
204 String aid = req.getParameter("to_media"); // the article id the comment will belong to
205 if (aid != null && !aid.equals("")) {
206 // ok, collecting data from form
208 Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
210 //no html in comments(for now)
211 for (Iterator i = withValues.keySet().iterator(); i.hasNext(); ) {
212 String k = (String) i.next();
213 String v = (String) withValues.get(k);
215 withValues.put(k, StringUtil.removeHTMLTags(v));
217 withValues.put("is_published", "1");
218 withValues.put("to_comment_status", "1");
219 withValues.put("is_html", "0");
221 //checking the onetimepasswd
222 HttpSession session = req.getSession(false);
223 String sessionPasswd = (String) session.getAttribute("passwd");
224 if (sessionPasswd != null) {
225 String passwd = req.getParameter("passwd");
226 if (passwd == null || passwd.length() == 0) {
227 throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});
229 if (!sessionPasswd.equals(passwd)) {
230 throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});
232 session.invalidate();
235 String id = mainModule.add(withValues);
237 SimpleResponse response = new SimpleResponse();
238 response.setResponseGenerator(commentFormDoneTemplate);
241 deliver(req, res, null, null, commentFormDupeTemplate);
244 DatabaseContent.getInstance().setUnproduced("id=" + aid);
247 EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
248 MirGlobal.localizer().openPostings().afterCommentPosting(comment);
249 MirGlobal.abuse().checkComment(
250 comment, new HTTPAdapters.HTTPRequestAdapter(req), res);
252 catch (Throwable t) {
253 throw new ServletModuleExc(t.getMessage());
257 // redirecting to url
258 // should implement back to article
259 deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());
261 catch (Throwable e) {
262 throw new ServletModuleFailure(e);
266 throw new ServletModuleExc("aid not set!");
271 * Method for delivering the form-Page for open posting
274 public void addposting(HttpServletRequest req, HttpServletResponse res)
275 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
277 if (MirGlobal.abuse().getOpenPostingDisabled()) {
278 openPostingDisabled(req, res);
283 Map mergeData = new HashMap();
286 if (MirGlobal.abuse().getOpenPostingPassword()) {
287 String passwd = generateOnetimePassword();
288 HttpSession session = req.getSession(false);
289 session.setAttribute("passwd", passwd);
290 mergeData.put("passwd", passwd);
293 mergeData.put("passwd", null);
296 String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
297 String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
298 String numOfMedia = req.getParameter("medianum");
300 if (numOfMedia == null || numOfMedia.equals("")) {
301 numOfMedia = defaultMedia;
303 else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
304 numOfMedia = maxMedia;
307 int mediaNum = Integer.parseInt(numOfMedia);
308 List mediaFields = new ArrayList();
309 for (int i = 0; i < mediaNum; i++) {
310 Integer mNum = new Integer(i + 1);
311 mediaFields.add(mNum.toString());
313 mergeData.put("medianum", numOfMedia);
314 mergeData.put("mediafields", mediaFields);
315 mergeData.put("to_topic", null);
317 Map extraInfo = new HashMap();
318 extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
319 extraInfo.put("themenPopupData", DatabaseTopics.getInstance().getPopupData());
321 deliver(req, res, mergeData, extraInfo, postingFormTemplate);
323 catch (Throwable t) {
324 throw new ServletModuleFailure(t);
329 * Method for inserting an open posting into the Database and delivering
330 * the postingDone Page
333 public void insposting(HttpServletRequest aRequest, HttpServletResponse aResponse) throws
334 ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
335 if (MirGlobal.abuse().getOpenPostingDisabled()) {
336 openPostingDisabled(aRequest, aResponse);
342 HTTPParsedRequest parsedRequest = new HTTPParsedRequest(
344 configuration.getString("Mir.DefaultEncoding"),
345 configuration.getInt("MaxMediaUploadSize")*1024,
346 configuration.getString("TempDir"));
348 Map mergeData = new HashMap();
350 HttpSession session = aRequest.getSession(false);
351 String sessionPasswd = (String) session.getAttribute("passwd");
352 if (sessionPasswd != null) {
353 String passwd = parsedRequest.getParameter("passwd");
355 if (passwd == null || passwd.length() == 0) {
356 throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});
358 if (!sessionPasswd.equals(passwd)) {
359 throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});
361 session.invalidate();
364 if (((parsedRequest.getParameter("title")).length() == 0) ||
365 ((parsedRequest.getParameter("description")).length() == 0) ||
366 ((parsedRequest.getParameter("content_data")).length() == 0))
367 throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
369 List mediaList = new ArrayList();
370 Iterator i = parsedRequest.getFiles().iterator();
372 while (i.hasNext()) {
373 UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
374 Map mediaValues = new HashMap();
376 String suffix = file.getFieldName().substring(5); // media${m}
377 logger.debug("media_title" + suffix);
378 String title = parsedRequest.getParameter("media_title" + suffix);
380 mediaValues.put("title", StringUtil.removeHTMLTags(title));
381 mediaValues.put("creator", StringUtil.removeHTMLTags(parsedRequest.getParameter("creator")));
382 mediaValues.put("to_publisher", "0");
383 mediaValues.put("is_published", "1");
384 mediaValues.put("to_media_folder", "7");
386 mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
389 Map withValues = new HashMap();
390 i = DatabaseContent.getInstance().getFieldNames().iterator();
391 while (i.hasNext()) {
392 String field = (String) i.next();
393 String value = parsedRequest.getParameter(field);
395 withValues.put(field, value);
399 for (i = withValues.keySet().iterator(); i.hasNext(); ) {
400 String k = (String) i.next();
401 String v = (String) withValues.get(k);
403 if (k.equals("content_data")) {
404 //this doesn't quite work yet, so for now, all html goes
405 //withValues.put(k,StringUtil.approveHTMLTags(v));
406 withValues.put(k, StringUtil.deleteForbiddenTags(v));
408 else if (k.equals("description")) {
409 String tmp = StringUtil.deleteForbiddenTags(v);
410 withValues.put(k, StringUtil.deleteHTMLTableTags(tmp));
413 withValues.put(k, StringUtil.removeHTMLTags(v));
417 withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
418 withValues.put("publish_path",
419 StringUtil.webdbDate2path( (String) withValues.get("date")));
420 withValues.put("is_produced", "0");
421 withValues.put("is_published", "1");
422 if (directOp.equals("yes"))
423 withValues.put("to_article_type", "1");
425 withValues.put("to_publisher", "1");
427 // inserting content into database
428 String cid = contentModule.add(withValues);
429 logger.debug("id: " + cid);
430 //insert was not successfull
432 deliver(aRequest, aResponse, mergeData, null, postingFormDupeTemplate);
436 List topics = parsedRequest.getParameterList("to_topic");
437 if (topics.size() > 0) {
439 DatabaseContentToTopics.getInstance().setTopics(cid, topics);
441 catch (Throwable e) {
442 logger.error("setting content_x_topic failed");
443 contentModule.deleteById(cid);
444 throw new ServletModuleFailure(
445 "smod - openindy :: insposting: setting content_x_topic failed: " +
450 i = mediaList.iterator();
451 while (i.hasNext()) {
452 Entity mediaEnt = (Entity) i.next();
453 DatabaseContentToMedia.getInstance().addMedia(cid, mediaEnt.getId());
456 EntityContent article = (EntityContent) contentModule.getById(cid);
458 MirGlobal.abuse().checkArticle(
459 article, new HTTPAdapters.HTTPRequestAdapter(aRequest), aResponse);
460 MirGlobal.localizer().openPostings().afterContentPosting(article);
462 catch (Throwable t) {
463 logger.error("Error while post-processing article: " + t.getMessage());
465 deliver(aRequest, aResponse, mergeData, null, postingFormDoneTemplate);
467 catch (Throwable e) {
468 e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
469 Throwable cause = ExceptionRoutines.traceCauseException(e);
471 if (cause instanceof UnsupportedMediaTypeExc) {
472 throw new ServletModuleUserExc("media.unsupportedformat", new String[] {});
474 throw new ServletModuleFailure(e);
479 * Due to a serious shortcoming of Tomcat 3.3, an extra sessionid parameter is
480 * generated into open session urls. Tomcat 3.3 makes it impossible to
481 * distinguish between sessions that are identified using a url and those
482 * that are identified using cookies: if both a sessionid cookie and a sessionid
483 * url are available, tomcat 3.3 pretends the url wasn't there...
485 private static final String SESSION_REQUEST_KEY="sessionid";
488 * Determines the Locale to be used for the current session
490 protected Locale getResponseLocale(HttpSession aSession, HttpServletRequest aRequest) {
491 String requestLanguage = aRequest.getParameter("language");
492 String sessionLanguage = (String) aSession.getAttribute("language");
493 String acceptLanguage = aRequest.getLocale().getLanguage();
494 String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
496 String language = requestLanguage;
499 language = sessionLanguage;
502 language = acceptLanguage;
505 language = defaultLanguage;
507 aSession.setAttribute("language", language);
509 return new Locale(language, "");
513 * Dispatch method for open sessions: a flexible extensible and customizable way
514 * for open access. Can be used for postings, but also for lots of other stuff.
518 * @throws ServletModuleExc
519 * @throws ServletModuleUserExc
520 * @throws ServletModuleFailure
522 public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse)
523 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
527 new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
528 configuration.getString("Mir.DefaultEncoding"),
529 configuration.getInt("MaxMediaUploadSize")*1024,
530 configuration.getString("TempDir")));
532 if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
533 !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
534 aRequest.getSession().invalidate();
536 Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
538 SimpleResponse response = new SimpleResponse(
539 ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getResponseLocale(aRequest.getSession(), aRequest), getFallbackLocale(aRequest)},
540 "etc/bundles/open"));
542 response.setResponseValue("actionURL", aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/OpenMir")+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
544 SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);
546 handler.processRequest(request, session, response);
547 ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
549 catch (Throwable t) {
550 logger.error(t.toString());
551 t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
553 throw new ServletModuleFailure(t);
558 * Method for preparing and sending a content as an email message
560 public void mail(HttpServletRequest req, HttpServletResponse res)
561 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
563 String aid = req.getParameter("mail_aid");
565 throw new ServletModuleExc("An article id must be specified in requests to email an article. Something therefore went badly wrong....");
568 String to = req.getParameter("mail_to");
569 String from = req.getParameter("mail_from");
570 String from_name = req.getParameter("mail_from_name");
571 String from_ip = req.getRemoteAddr();
572 String comment = req.getParameter("mail_comment");
573 String mail_language = req.getParameter("mail_language");
575 Map mergeData = new HashMap();
576 mergeData.put("mail_to",to);
577 mergeData.put("mail_from",from);
578 mergeData.put("mail_from_name",from_name);
579 mergeData.put("mail_comment",comment);
580 mergeData.put("mail_aid",aid);
581 mergeData.put("mail_language",mail_language);
584 if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
585 deliver(req, res, mergeData, null, prepareMailTemplate);
588 //run checks on to and from and mail_language to make sure no monkey business occurring
589 if (mail_language.indexOf('.') != -1 || mail_language.indexOf('/') != -1 ) {
590 throw new ServletModuleExc("Invalid language");
592 if (to.indexOf('\n') != -1
593 || to.indexOf('\r') != -1
594 || to.indexOf(',') != -1) {
595 throw new ServletModuleUserExc("email.error.invalidtoaddress", new String[] {to});
597 if (from.indexOf('\n') != -1 || from.indexOf('\r') != -1 || from.indexOf(',') != -1 ) {
598 throw new ServletModuleUserExc("email.error.invalidfromaddress", new String[] {from});
601 CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
604 if (MirGlobal.mruCache().hasObject(theCacheKey)){
605 logger.info("fetching email text for article "+aid+" from cache");
606 theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
609 EntityContent contentEnt;
611 contentEnt = (EntityContent) contentModule.getById(aid);
612 StringWriter theEMailTextWriter = new StringWriter();
613 PrintWriter dest = new PrintWriter(theEMailTextWriter);
614 Map articleData = new HashMap();
615 articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
616 articleData.put("languagecode", mail_language);
617 deliver(dest, req, res, articleData, null, emailAnArticleTemplate, mail_language);
618 theEmailText = theEMailTextWriter.toString();
619 MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
621 catch (Throwable e) {
622 throw new ServletModuleFailure("Couldn't get content for article " + aid + mail_language + ": " + e.getMessage(), e);
626 String content = theEmailText;
630 content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
631 // put in the comment where it should go
632 if (comment != null) {
633 String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
635 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!",commentTextToInsert);
638 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
643 content=StringRoutines.performRegularExpressionReplacement(content,"!COMMENT!","");
646 throw new ServletModuleFailure("Problem doing regular expression replacement " + e.toString(), e);
650 SMTPClient client=new SMTPClient();
653 client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
655 reply = client.getReplyCode();
657 if (!SMTPReply.isPositiveCompletion(reply)) {
659 throw new ServletModuleExc("SMTP server refused connection.");
662 client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
665 //mission accomplished
666 deliver(req, res, mergeData, null, sentMailTemplate);
668 catch(IOException e) {
669 if(client.isConnected()) {
672 } catch(IOException f) {
676 throw new ServletModuleFailure(e);
684 * Method for querying a lucene index
688 * @throws ServletModuleExc
689 * @throws ServletModuleUserExc
690 * @throws ServletModuleFailure
693 public void search(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
695 final String[] search_variables = {
696 "search_content", "search_boolean", "search_creator",
697 "search_topic", "search_hasImages", "search_hasAudio", "search_hasVideo", "search_sort",
698 "search_submit", "search_back", "search_forward"};
699 HTTPRequestParser requestParser = new HTTPRequestParser(req);
703 HttpSession session = req.getSession(false);
705 String queryString = "";
707 Map mergeData = new HashMap();
709 KeywordSearchTerm dateTerm = new KeywordSearchTerm("date_formatted", "search_date", "webdb_create_formatted", "webdb_create_formatted", "webdb_create_formatted");
710 UnIndexedSearchTerm whereTerm = new UnIndexedSearchTerm("", "", "", "where", "where");
711 TextSearchTerm creatorTerm = new TextSearchTerm("creator", "search_creator", "creator", "creator", "creator");
712 TextSearchTerm titleTerm = new TextSearchTerm("title", "search_content", "title", "title", "title");
713 TextSearchTerm descriptionTerm = new TextSearchTerm("description", "search_content", "description", "description", "description");
714 ContentSearchTerm contentTerm = new ContentSearchTerm("content_data", "search_content", "content", "", "");
715 TopicSearchTerm topicTerm = new TopicSearchTerm();
716 TopicMatrixSearchTerm topicMatrixTerm = new TopicMatrixSearchTerm();
717 ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
718 AudioSearchTerm audioTerm = new AudioSearchTerm();
719 VideoSearchTerm videoTerm = new VideoSearchTerm();
721 //make the query available to subsequent iterations
723 Iterator j = Arrays.asList(search_variables).iterator();
724 while (j.hasNext()) {
725 String variable = (String) j.next();
727 mergeData.put(variable, requestParser.getParameter(variable));
731 mergeData.put("topics", DatabaseTopics.getInstance().getPopupData());
733 catch (Throwable e) {
734 logger.debug("Can't get topics: " + e.toString());
737 String searchBackValue = req.getParameter("search_back");
738 String searchForwardValue = req.getParameter("search_forward");
740 if (searchBackValue != null) {
741 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
742 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() - increment;
745 if (newPosition >= totalHits)
746 newPosition = totalHits - 1;
747 session.setAttribute("positionInResults", new Integer(newPosition));
750 if (searchForwardValue != null) {
751 int totalHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
752 int newPosition = ( (Integer) session.getAttribute("positionInResults")).intValue() + increment;
755 if (newPosition >= totalHits)
756 newPosition = totalHits - 1;
758 session.setAttribute("positionInResults", new Integer(newPosition));
761 File indexFile = FileRoutines.getAbsoluteOrRelativeFile(configuration.getHome(), configuration.getString("IndexPath"));
763 String creatorFragment = creatorTerm.makeTerm(req);
764 if (creatorFragment != null) {
765 queryString = queryString + " +" + creatorFragment;
768 // search title, description, and content for something
769 // the contentTerm uses param "search_boolean" to combine its terms
770 String contentFragment = contentTerm.makeTerm(req);
771 if (contentFragment != null) {
772 logger.debug("contentFragment: " + contentFragment);
773 queryString = queryString + " +" + contentFragment;
776 String topicFragment = topicTerm.makeTerm(req);
777 if (topicFragment != null) {
778 queryString = queryString + " +" + topicFragment;
781 String topicMatrixFragment = topicMatrixTerm.makeTerm(req);
782 if (topicMatrixFragment != null) {
783 queryString = queryString + " +" + topicMatrixFragment;
786 String imagesFragment = imagesTerm.makeTerm(req);
787 if (imagesFragment != null) {
788 queryString = queryString + " +" + imagesFragment;
791 String audioFragment = audioTerm.makeTerm(req);
792 if (audioFragment != null) {
793 queryString = queryString + " +" + audioFragment;
796 String videoFragment = videoTerm.makeTerm(req);
797 if (videoFragment != null) {
798 queryString = queryString + " +" + videoFragment;
801 if (queryString == null || queryString.length()==0) {
806 Searcher searcher = null;
809 searcher = new IndexSearcher(FSDirectory.getDirectory(indexFile,false));
811 catch (IOException e) {
812 logger.debug("Can't open indexPath: " + indexFile.getAbsolutePath());
813 throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
818 query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
820 catch (Exception e) {
822 logger.debug("Query don't parse: " + queryString);
823 throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
828 hits = searcher.search(query);
830 catch (IOException e) {
832 logger.debug("Can't get hits: " + e.toString());
833 throw new ServletModuleExc("Problem getting hits!");
837 int end = hits.length();
839 String sortBy = req.getParameter("search_sort");
840 if (sortBy == null || sortBy.equals("")) {
841 throw new ServletModuleExc("Please let me sort by something!(missing search_sort)");
844 // here is where the documents will go for database across sessions
845 ArrayList theDocumentsSorted = new ArrayList();
847 if (sortBy.equals("score")) {
848 for (int i = start; i < end; i++) {
849 theDocumentsSorted.add(hits.doc(i));
853 // then we'll sort by date!
854 Map dateToPosition = new HashMap(end, 1.0F); //we know how big it will be
855 for (int i = start; i < end; i++) {
856 String creationDate = (hits.doc(i)).get("creationDate");
857 // do a little dance in case two contents created at the same second!
858 if (dateToPosition.containsKey(creationDate)) {
859 ( (ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i));
862 ArrayList thePositions = new ArrayList();
863 thePositions.add(new Integer(i));
864 dateToPosition.put(creationDate, thePositions);
867 Set keys = dateToPosition.keySet();
868 ArrayList keyList = new ArrayList(keys);
869 Collections.sort(keyList);
870 if (sortBy.equals("date_desc")) {
871 Collections.reverse(keyList);
874 if (!sortBy.equals("date_asc")) {
875 throw new ServletModuleExc("don't know how to sort by: " + sortBy);
878 ListIterator keyTraverser = keyList.listIterator();
879 while (keyTraverser.hasNext()) {
880 ArrayList positions = (ArrayList) dateToPosition.get( (keyTraverser.next()));
881 ListIterator positionsTraverser = positions.listIterator();
882 while (positionsTraverser.hasNext()) {
883 theDocumentsSorted.add(hits.doc( ( (Integer) (positionsTraverser.next())).intValue()));
891 catch (IOException e) {
892 logger.debug("Can't close searcher: " + e.toString());
893 throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
896 session.removeAttribute("numberOfHits");
897 session.removeAttribute("theDocumentsSorted");
898 session.removeAttribute("positionInResults");
900 session.setAttribute("numberOfHits", new Integer(end));
901 session.setAttribute("theDocumentsSorted", theDocumentsSorted);
902 session.setAttribute("positionInResults", new Integer(0));
905 catch (IOException e) {
906 logger.debug("Can't close searcher: " + e.toString());
907 throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
914 ArrayList theDocs = (ArrayList) session.getAttribute("theDocumentsSorted");
915 if (theDocs != null) {
917 mergeData.put("numberOfHits", (session.getAttribute("numberOfHits")).toString());
918 List theHits = new ArrayList();
919 int pIR = ( (Integer) session.getAttribute("positionInResults")).intValue();
921 int numHits = ( (Integer) session.getAttribute("numberOfHits")).intValue();
923 if (! (pIR + increment >= numHits)) {
924 mergeData.put("hasNext", "y");
927 mergeData.put("hasNext", null);
930 mergeData.put("hasPrevious", "y");
933 mergeData.put("hasPrevious", null);
936 if ( (pIR + increment) > numHits) {
940 terminus = pIR + increment;
942 for (int i = pIR; i < terminus; i++) {
943 Map h = new HashMap();
944 Document theHit = (Document) theDocs.get(i);
945 whereTerm.returnMeta(h, theHit);
946 creatorTerm.returnMeta(h, theHit);
947 titleTerm.returnMeta(h, theHit);
948 descriptionTerm.returnMeta(h, theHit);
949 dateTerm.returnMeta(h, theHit);
950 imagesTerm.returnMeta(h, theHit);
951 audioTerm.returnMeta(h, theHit);
952 videoTerm.returnMeta(h, theHit);
955 mergeData.put("hits", theHits);
958 catch (Throwable e) {
959 logger.error("Can't iterate over hits: " + e.toString());
961 throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
964 mergeData.put("queryString", queryString);
966 deliver(req, res, mergeData, null, searchResultsTemplate);
968 catch (NullPointerException n) {
969 throw new ServletModuleFailure("Null Pointer: " + n.toString(), n);
974 * Method for dynamically generating a pdf using iText
977 public void getpdf(HttpServletRequest req, HttpServletResponse res)
978 throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
979 long starttime = System.currentTimeMillis();
980 String ID_REQUEST_PARAM = "id";
981 int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
983 String idParam = req.getParameter(ID_REQUEST_PARAM);
984 if (idParam != null) {
986 RE re = new RE("[0-9]+");
988 REMatch[] idMatches = re.getAllMatches(idParam);
990 String cacheSelector = "";
992 for (int i = 0; i < idMatches.length; i++) {
993 cacheSelector = cacheSelector + "," + idMatches[i].toString();
996 String cacheType = "pdf";
998 CacheKey theCacheKey = new CacheKey(cacheType, cacheSelector);
1002 if (MirGlobal.mruCache().hasObject(theCacheKey)) {
1003 logger.info("fetching pdf from cache");
1004 thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
1007 logger.info("generating pdf and caching it");
1008 ByteArrayOutputStream out = new ByteArrayOutputStream();
1009 PDFGenerator pdfMaker = new PDFGenerator(out);
1011 if (idMatches.length > 1) {
1013 for (int i = 0; i < idMatches.length && i < maxArticlesInNewsleter; i++) {
1014 REMatch aMatch = idMatches[i];
1015 String id = aMatch.toString();
1016 EntityContent contentEnt = (EntityContent) contentModule.getById(id);
1017 pdfMaker.addIndexItem(contentEnt);
1021 for (int i = 0; i < idMatches.length; i++) {
1022 REMatch aMatch = idMatches[i];
1023 String id = aMatch.toString();
1024 EntityContent contentEnt = (EntityContent) contentModule.getById(id);
1026 pdfMaker.add(contentEnt);
1030 thePDF = out.toByteArray();
1032 //and save all our hard work!
1033 MirGlobal.mruCache().storeObject(theCacheKey, thePDF);
1036 res.setContentType("application/pdf");
1037 res.setContentLength(thePDF.length);
1038 res.getOutputStream().write(thePDF);
1039 res.getOutputStream().flush();
1040 String elapsedtime = (new Long(System.currentTimeMillis() - starttime)).toString();
1041 logger.info("pdf retireval took " + elapsedtime + " milliseconds");
1045 throw new ServletModuleExc("Missing id.");
1048 catch (Throwable t) {
1049 logger.error(t.toString());
1050 throw new ServletModuleFailure(t);
1055 public String generateOnetimePassword() {
1056 Random r = new Random();
1057 int random = r.nextInt();
1059 long l = System.currentTimeMillis();
1061 l = (l * l * l * l) / random;
1065 String returnString = "" + l;
1067 return returnString.substring(5);
1070 public void deliver(HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) throws ServletModuleFailure {
1072 deliver(aResponse.getWriter(), aRequest, aResponse, aData, anExtra, aGenerator);
1074 catch (Throwable t) {
1075 throw new ServletModuleFailure(t);
1079 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
1080 throws ServletModuleFailure {
1082 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "etc/bundles/open");
1083 responseData.put("data", aData);
1084 responseData.put("extra", anExtra);
1087 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1088 generator.generate(anOutputWriter, responseData, logger);
1090 anOutputWriter.close();
1092 catch (Throwable e) {
1093 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1095 throw new ServletModuleFailure(e);
1099 public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator,String aLocaleString)
1100 throws ServletModuleFailure {
1102 Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "etc/bundles/open");
1103 responseData.put("data", aData);
1104 responseData.put("extra", anExtra);
1107 Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
1108 generator.generate(anOutputWriter, responseData, logger);
1110 anOutputWriter.close();
1112 catch (Throwable e) {
1113 logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
1115 throw new ServletModuleFailure(e);
1120 public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
1122 logger.error("Error during open action", anException);
1123 Map data = new HashMap();
1125 data.put("errorstring", anException.getMessage());
1126 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1128 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
1130 catch (Throwable e) {
1131 throw new ServletModuleFailure(e);
1135 public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
1136 PrintWriter out, ServletModuleUserExc anException) {
1138 logger.warn("user error: " + anException.getMessage());
1139 Map data = new HashMap();
1142 MirGlobal.getBundleFactory().getBundle("etc/bundles/open", new
1143 String[] { getLocale(aRequest).getLanguage() });
1144 data.put("errorstring", bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters())));
1145 data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
1147 deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
1149 catch (Throwable e) {
1150 throw new ServletModuleFailure(e);