exception + misc. cleanup
[mir.git] / source / mircoders / servlet / ServletModuleContent.java
1 /*
2  * Copyright (C) 2001, 2002  The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
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.
10  *
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.
15  *
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
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package mircoders.servlet;
33
34 import java.util.GregorianCalendar;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42 import javax.servlet.http.HttpSession;
43
44 import mir.entity.adapter.EntityAdapterModel;
45 import mir.entity.adapter.EntityIteratorAdapter;
46 import mir.log.LoggerWrapper;
47 import mir.misc.StringUtil;
48 import mir.module.ModuleExc;
49 import mir.servlet.ServletModule;
50 import mir.servlet.ServletModuleExc;
51 import mir.servlet.ServletModuleFailure;
52 import mir.storage.StorageObjectFailure;
53 import mir.util.CachingRewindableIterator;
54 import mir.util.HTTPRequestParser;
55 import mir.util.JDBCStringRoutines;
56 import mir.util.SQLQueryBuilder;
57 import mir.util.URLBuilder;
58 import mircoders.entity.EntityContent;
59 import mircoders.entity.EntityUsers;
60 import mircoders.global.MirGlobal;
61 import mircoders.module.ModuleContent;
62 import mircoders.search.IndexUtil;
63 import mircoders.storage.DatabaseComment;
64 import mircoders.storage.DatabaseContent;
65 import mircoders.storage.DatabaseContentToTopics;
66
67 import org.apache.lucene.index.IndexReader;
68
69 import freemarker.template.SimpleHash;
70
71 /*
72  *  ServletModuleContent -
73  *  deliver html for the article admin form.
74  *
75  * @version $Id: ServletModuleContent.java,v 1.42 2003/03/09 03:53:11 zapata Exp $
76  * @author rk, mir-coders
77  *
78  */
79
80 public class ServletModuleContent extends ServletModule
81 {
82   private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");;
83   private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate");
84
85   private static ServletModuleContent instance = new ServletModuleContent();
86   public static ServletModule getInstance() { return instance; }
87
88   private ServletModuleContent() {
89     super();
90     logger = new LoggerWrapper("ServletModule.Content");
91     try {
92
93       templateListString = configuration.getString("ServletModule.Content.ListTemplate");
94       templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate");
95       templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate");
96
97       mainModule = new ModuleContent(DatabaseContent.getInstance());
98     }
99     catch (StorageObjectFailure e) {
100       logger.error("servletmodulecontent konnte nicht initialisiert werden");
101     }
102   }
103
104   public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
105   {
106     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
107
108     String where = requestParser.getParameter("where");
109     String order = requestParser.getParameterWithDefault("order", "webdb_create desc");
110     int offset = requestParser.getIntegerWithDefault("offset", 0);
111     String selectArticleUrl = requestParser.getParameter("selectarticleurl");
112
113     returnArticleList(aRequest, aResponse, where, order, offset, selectArticleUrl);
114   }
115
116   public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {
117     try {
118       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
119       SQLQueryBuilder queryBuilder = new SQLQueryBuilder();
120       String searchField = requestParser.getParameterWithDefault("searchfield", "");
121       String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim();
122       String searchOrder = requestParser.getParameterWithDefault("searchorder", "");
123       String searchispublished = requestParser.getParameterWithDefault("searchispublished", "");
124       String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");
125       String selectArticleUrl = requestParser.getParameter("selectarticleurl");
126
127       if (searchValue.length()>0) {
128         if (searchField.equals("contents"))
129           queryBuilder.appendAndCondition(
130             "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+
131             " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");
132         else
133           queryBuilder.appendAndCondition(
134             "lower("+ searchField + ") like " +
135             "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");
136       }
137
138       if (searchispublished.length()>0) {
139         if (searchispublished.equals("0"))
140           queryBuilder.appendAndCondition("is_published='f'");
141         else
142           queryBuilder.appendAndCondition("is_published='t'");
143       }
144
145       if (searchArticleType.length()>0) {
146         queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType));
147       }
148
149       if (searchOrder.length()>0) {
150         if (searchOrder.equals("datedesc"))
151           queryBuilder.appendAscendingOrder("webdb_create");
152         else if (searchOrder.equals("dateasc"))
153           queryBuilder.appendDescendingOrder("webdb_create");
154         else if (searchOrder.equals("title"))
155           queryBuilder.appendDescendingOrder("title");
156         else if (searchOrder.equals("creator"))
157           queryBuilder.appendDescendingOrder("creator");
158       }
159
160       returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);
161     }
162     catch (Throwable e) {
163       throw new ServletModuleFailure(e);
164     }
165   }
166
167   public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
168     _showObject(null, req, res);
169   }
170
171
172   public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
173   {
174 //theLog.printDebugInfo(":: content :: trying to insert");
175     try {
176       EntityUsers   user = _getUser(req);
177       Map withValues = getIntersectingValues(req, DatabaseContent.getInstance());
178
179       String now = StringUtil.date2webdbDate(new GregorianCalendar());
180       withValues.put("date", now);
181       withValues.put("publish_path", StringUtil.webdbDate2path(now));
182       withValues.put("to_publisher", user.getId());
183       withValues.put("is_produced", "0");
184       if (!withValues.containsKey("is_published"))
185         withValues.put("is_published","0");
186       if (!withValues.containsKey("is_html"))
187         withValues.put("is_html","0");
188
189       String id = mainModule.add(withValues);
190       DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic"));
191
192       _showObject(id, req, res);
193     }
194     catch (Throwable e) {
195       throw new ServletModuleFailure(e);
196     }
197   }
198
199   public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
200   {
201     EntityUsers   user = _getUser(req);
202
203     String idParam = req.getParameter("id");
204     if (idParam == null) throw new ServletModuleExc("Invalid call: id missing");
205
206     String confirmParam = req.getParameter("confirm");
207     String cancelParam = req.getParameter("cancel");
208
209     logger.info("where = " + req.getParameter("where"));
210
211     if (confirmParam == null && cancelParam == null) {
212
213       SimpleHash mergeData = new SimpleHash();
214       mergeData.put("module", "Content");
215       mergeData.put("infoString", "Content: " + idParam);
216       mergeData.put("id", idParam);
217       mergeData.put("where", req.getParameter("where"));
218       mergeData.put("order", req.getParameter("order"));
219       mergeData.put("offset", req.getParameter("offset"));
220       deliver(req, res, mergeData, templateConfirmString);
221     }
222     else {
223       if (confirmParam!= null && !confirmParam.equals("")) {
224         try {
225           mainModule.deleteById(idParam);
226
227           /** @todo the following two should be implied in
228            *  DatabaseContent */
229
230           //delete rows in the content_x_topic-table
231           DatabaseContentToTopics.getInstance().deleteByContentId(idParam);
232           //delete rows in the comment-table
233           DatabaseComment.getInstance().deleteByContentId(idParam);
234           //delete from lucene index, if any
235           String index = configuration.getString("IndexPath");
236           if (IndexReader.indexExists(index)){
237             IndexUtil.unindexID(idParam,index);
238           }
239
240         }
241         catch (Throwable e) {
242           throw new ServletModuleFailure(e);
243         }
244         list(req,res);
245       }
246       else {
247         // Datensatz anzeigen
248         _showObject(idParam, req, res);
249       }
250     }
251   }
252
253   public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
254   {
255     String idParam = req.getParameter("id");
256     if (idParam == null)
257       throw new ServletModuleExc("Invalid call: id not supplied ");
258     _showObject(idParam, req, res);
259   }
260
261 // methods for attaching media file
262   public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
263   {
264     String  mediaIdParam = req.getParameter("mid");
265     String  idParam = req.getParameter("cid");
266     if (idParam == null||mediaIdParam==null) throw new ServletModuleExc("smod content :: attach :: cid/mid missing");
267
268     try {
269       EntityContent entContent = (EntityContent)mainModule.getById(idParam);
270       entContent.attach(mediaIdParam);
271     }
272     catch(Throwable e) {
273       logger.error("smod content :: attach :: could not get entityContent");
274     }
275
276     _showObject(idParam, req, res);
277   }
278
279   public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
280   {
281     String  cidParam = req.getParameter("cid");
282     String  midParam = req.getParameter("mid");
283     if (cidParam == null)
284       throw new ServletModuleExc("smod content :: dettach :: cid missing");
285     if (midParam == null)
286       throw new ServletModuleExc("smod content :: dettach :: mid missing");
287
288     try {
289       EntityContent entContent = (EntityContent)mainModule.getById(cidParam);
290       entContent.dettach(cidParam,midParam);
291     }
292     catch(Throwable e) {
293       logger.error("smod content :: dettach :: could not get entityContent");
294     }
295
296     _showObject(cidParam, req, res);
297   }
298
299   public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
300   {
301     try {
302       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
303
304       String returnUrl = requestParser.getParameter("returnurl");
305
306       String idParam = aRequest.getParameter("id");
307       if (idParam == null)
308         throw new ServletModuleExc("Wrong call: (id) is missing");
309
310       Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
311       String[] topic_id = aRequest.getParameterValues("to_topic");
312       String content_id = aRequest.getParameter("id");
313
314       withValues.put("is_produced", "0");
315       if (!withValues.containsKey("is_published"))
316         withValues.put("is_published","0");
317       if (!withValues.containsKey("is_html"))
318         withValues.put("is_html","0");
319
320       String id = mainModule.set(withValues);
321       DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id);
322
323       String whereParam = aRequest.getParameter("where");
324       String orderParam = aRequest.getParameter("order");
325
326       if (returnUrl!=null){
327         redirect(aResponse, returnUrl);
328       }
329       else
330         _showObject(idParam, aRequest, aResponse);
331     }
332     catch (Throwable e) {
333       throw new ServletModuleFailure(e);
334     }
335   }
336
337 /*
338   * HelperMethod shows the basic article editing form.
339   *
340   * if the "id" parameter is null, it means show an empty form to add a new
341   * article.
342 */
343   public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse)
344       throws ServletModuleExc {
345     try {
346       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
347       Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));
348       EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
349       Map article;
350       URLBuilder urlBuilder = new URLBuilder();
351
352       urlBuilder.setValue("module", "Content");
353       urlBuilder.setValue("do", "edit");
354       urlBuilder.setValue("id", id);
355       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
356
357       if (id!=null) {
358         responseData.put("new", Boolean.FALSE);
359         article = model.makeEntityAdapter("content", mainModule.getById(id));
360       }
361       else {
362         List fields = DatabaseContent.getInstance().getFields();
363         responseData.put("new", Boolean.TRUE);
364         article = new HashMap();
365         Iterator i = fields.iterator();
366         while (i.hasNext()) {
367           article.put(i.next(), null);
368         }
369
370         article.put("to_topics", null);
371
372         MirGlobal.localizer().adminInterface().initializeArticle(article);
373       }
374       responseData.put("article", article);
375
376       responseData.put("returnurl", requestParser.getParameter("returnurl"));
377       responseData.put("thisurl", urlBuilder.getQuery());
378
379       ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate);
380     }
381     catch (Throwable e) {
382       throw new ServletModuleFailure(e);
383     }
384   }
385
386   public void returnArticleList(
387        HttpServletRequest aRequest,
388        HttpServletResponse aResponse,
389        String aWhereClause,
390        String anOrderByClause,
391        int anOffset,
392        String aSelectArticleUrl) throws ServletModuleExc {
393
394     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
395     URLBuilder urlBuilder = new URLBuilder();
396     EntityAdapterModel model;
397     int nrArticlesPerPage = 20;
398     int count;
399
400     try {
401       Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest));
402       model = MirGlobal.localizer().dataModel().adapterModel();
403
404       Object articleList =
405           new CachingRewindableIterator(
406             new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage,
407                MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset)
408       );
409
410       responseData.put("nexturl", null);
411       responseData.put("prevurl", null);
412
413       count=mainModule.getSize(aWhereClause);
414
415       urlBuilder.setValue("module", "Content");
416       urlBuilder.setValue("do", "list");
417       urlBuilder.setValue("where", aWhereClause);
418       urlBuilder.setValue("order", anOrderByClause);
419
420
421       urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
422       urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue"));
423       urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
424       urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
425       urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype"));
426       urlBuilder.setValue("selectarticleurl", aSelectArticleUrl);
427
428       responseData.put("searchfield", requestParser.getParameter("searchfield"));
429       responseData.put("searchvalue", requestParser.getParameter("searchvalue"));
430       responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
431       responseData.put("searchorder", requestParser.getParameter("searchorder"));
432       responseData.put("searcharticletype", requestParser.getParameter("searcharticletype"));
433       responseData.put("selectarticleurl", aSelectArticleUrl);
434
435       urlBuilder.setValue("offset", anOffset);
436       responseData.put("offset" , new Integer(anOffset).toString());
437       responseData.put("thisurl" , urlBuilder.getQuery());
438
439       if (count>=anOffset+nrArticlesPerPage) {
440         urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage));
441         responseData.put("nexturl" , urlBuilder.getQuery());
442       }
443
444       if (anOffset>0) {
445         urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0));
446         responseData.put("prevurl" , urlBuilder.getQuery());
447       }
448
449       responseData.put("articles", articleList);
450
451       responseData.put("from" , Integer.toString(anOffset+1));
452       responseData.put("count", Integer.toString(count));
453       responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count)));
454       responseData.put("offset" , Integer.toString(anOffset));
455       responseData.put("order", anOrderByClause);
456       responseData.put("where" , aWhereClause);
457
458       ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate);
459     }
460     catch (Throwable e) {
461       throw new ServletModuleFailure(e);
462     }
463   }
464
465   public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
466   {
467     try {
468       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
469       URLBuilder urlBuilder = new URLBuilder();
470
471       urlBuilder.setValue("module", "Content");
472       urlBuilder.setValue("do", "setparent");
473       urlBuilder.setValue("childid", requestParser.getParameter("id"));
474       urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
475
476       returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());
477     }
478     catch (Throwable e) {
479       throw new ServletModuleFailure(e);
480     }
481   }
482
483   public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
484   {
485     try {
486       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
487       String articleId = requestParser.getParameter("article_id");
488
489       if (articleId == null)
490         throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
491
492       returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);
493     }
494     catch (Throwable e) {
495       throw new ServletModuleFailure(e);
496     }
497   }
498
499   public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
500   {
501     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
502     String articleId = aRequest.getParameter("childid");
503     String parentId  = aRequest.getParameter("id");
504     String returnUrl = aRequest.getParameter("returnurl");
505
506     try {
507       EntityContent article = (EntityContent) mainModule.getById(articleId);
508       article.setValueForProperty("to_content", parentId);
509       article.setProduced(false);
510       article.update();
511     }
512     catch(Throwable e) {
513       logger.error("ServletModuleContent.setparent: " + e.getMessage());
514       throw new ServletModuleFailure(e);
515     }
516
517     redirect(aResponse, returnUrl);
518   }
519
520   public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
521   {
522     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
523     String articleId = requestParser.getParameter("id");
524     String returnUrl = requestParser.getParameter("returnurl");
525
526     try {
527       EntityContent article = (EntityContent) mainModule.getById(articleId);
528       article.setValueForProperty("to_content", "");
529       article.setProduced(false);
530       article.update();
531     }
532     catch(Throwable e) {
533       e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
534       logger.error("ServletModuleContent.clearparent: " + e.getMessage());
535
536       throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
537     }
538
539     redirect(aResponse, returnUrl);
540   }
541
542   private EntityUsers _getUser(HttpServletRequest req)
543   {
544     HttpSession session=req.getSession(false);
545
546     return (EntityUsers)session.getAttribute("login.uid");
547   }
548 }