bugfix
[mir.git] / source / mircoders / servlet / ServletModuleUploadedMedia.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  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.
29  */
30
31 package mircoders.servlet;
32
33 import java.io.InputStream;
34 import java.net.URLEncoder;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Vector;
40
41 import javax.servlet.ServletContext;
42 import javax.servlet.ServletOutputStream;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.servlet.http.HttpServletResponse;
45 import javax.servlet.http.HttpSession;
46
47 import mir.config.MirPropertiesConfiguration;
48 import mir.entity.Entity;
49 import mir.entity.EntityList;
50 import mir.log.LoggerWrapper;
51 import mir.media.MediaHelper;
52 import mir.media.MirMedia;
53 import mir.servlet.ServletModule;
54 import mir.servlet.ServletModuleExc;
55 import mir.servlet.ServletModuleFailure;
56 import mir.servlet.ServletModuleUserExc;
57 import mir.session.UploadedFile;
58 import mir.util.ExceptionFunctions;
59 import mir.util.HTTPParsedRequest;
60 import mircoders.entity.EntityComment;
61 import mircoders.entity.EntityContent;
62 import mircoders.entity.EntityUploadedMedia;
63 import mircoders.entity.EntityUsers;
64 import mircoders.media.MediaUploadProcessor;
65 import mircoders.module.*;
66 import mircoders.storage.DatabaseComment;
67 import mircoders.storage.DatabaseContent;
68 import mircoders.storage.DatabaseMediafolder;
69
70 import org.apache.commons.fileupload.FileItem;
71
72 import freemarker.template.SimpleHash;
73 import freemarker.template.SimpleList;
74
75 /*
76  *  ServletModuleBilder -
77  *  liefert HTML fuer Bilder
78  *
79  * @version $Id: ServletModuleUploadedMedia.java,v 1.28.2.2 2003/06/25 02:40:29 zapata Exp $
80  * @author RK, the mir-coders group
81  */
82
83 public abstract class ServletModuleUploadedMedia
84         extends mir.servlet.ServletModule {
85
86   //private static DatabaseRights dbRights;
87
88   public static ServletModule getInstance() {
89     return null;
90   }
91
92   public ServletModuleUploadedMedia() {
93     super();
94     logger = new LoggerWrapper("ServletModule.UploadedMedia");
95   }
96
97   public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
98           throws ServletModuleExc, ServletModuleUserExc {
99     try {
100       HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,
101           configuration.getString("Mir.DefaultEncoding"),
102           configuration.getInt("MaxMediaUploadSize")*1024,
103           configuration.getString("TempDir"));
104
105       Map mediaValues = new HashMap();
106
107       mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());
108
109       Iterator i = mainModule.getStorageObject().getFields().iterator();
110       while (i.hasNext()) {
111         String field = (String) i.next();
112         String value = parsedRequest.getParameter(field);
113         if (value!=null)
114           mediaValues.put(field, value);
115       }
116
117       List mediaList = new Vector();
118
119       i = parsedRequest.getFiles().iterator();
120       while (i.hasNext()) {
121         UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
122
123         String suffix = file.getFieldName().substring(5);
124         mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix));
125
126         mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
127       }
128
129       String articleid = parsedRequest.getParameter("articleid");
130       String commentid = parsedRequest.getParameter("commentid");
131
132       if (articleid!=null) {
133         EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid);
134
135         i=mediaList.iterator();
136
137         while (i.hasNext()) {
138           entContent.attach(((EntityUploadedMedia) i.next()).getId());
139         }
140
141         ((ServletModuleContent) ServletModuleContent.getInstance())._showObject(articleid, aRequest, aResponse);
142
143         return;
144       }
145
146       if (commentid!=null) {
147         EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(commentid);
148
149         i=mediaList.iterator();
150
151         while (i.hasNext()) {
152           comment.attach( ( (EntityUploadedMedia) i.next()).getId());
153         }
154
155         ((ServletModuleComment) ServletModuleComment.getInstance()).showComment(commentid, aRequest, aResponse);
156
157         return;
158       }
159
160       SimpleHash mergeData = new SimpleHash();
161       SimpleHash popups = new SimpleHash();
162       mergeData.put("contentlist", mir.generator.FreemarkerGenerator.makeAdapter(mediaList));
163
164       mergeData.put("count", Integer.toString(mediaList.size()));
165       mergeData.put("from", "1");
166       mergeData.put("to", Integer.toString(mediaList.size()));
167
168       //fetch the popups
169       popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
170       // raus damit
171       deliver(aRequest, aResponse, mergeData, popups, templateListString);
172     }
173     catch (Throwable t) {
174       Throwable cause = ExceptionFunctions.traceCauseException(t);
175
176       if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
177         throw new ServletModuleUserExc("media.error.unsupportedformat", new String[] {});
178       }
179       throw new ServletModuleFailure("ServletModuleUploadedMedia.insert: " + t.toString(), t);
180     }
181   }
182
183   public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
184
185     try {
186       HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,
187           configuration.getString("Mir.DefaultEncoding"),
188           configuration.getInt("MaxMediaUploadSize")*1024,
189           configuration.getString("TempDir"));
190       Map mediaValues = new HashMap();
191
192       Iterator i = mainModule.getStorageObject().getFields().iterator();
193       while (i.hasNext()) {
194         String field = (String) i.next();
195         String value = parsedRequest.getParameter(field);
196         if (value!=null)
197           mediaValues.put(field, value);
198       }
199
200       mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());
201       mediaValues.put("is_produced", "0");
202       if (!mediaValues.containsKey("is_published"))
203         mediaValues.put("is_published", "0");
204
205       String id = mainModule.set(mediaValues);
206       logger.debug("update: media ID = " + id);
207       _edit(id, aRequest, aResponse);
208     }
209     catch (Throwable e) {
210       throw new ServletModuleFailure("upload -- exception " + e.toString(), e);
211     }
212
213   }
214
215
216   public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
217     // Parameter auswerten
218     SimpleHash mergeData = new SimpleHash();
219     SimpleHash popups = new SimpleHash();
220
221     String query_text = aRequest.getParameter("query_text");
222     mergeData.put("query_text", query_text);
223     if (query_text != null) mergeData.put("query_text_encoded", URLEncoder.encode(query_text));
224     String query_field = aRequest.getParameter("query_field");
225     mergeData.put("query_field", query_field);
226     String query_is_published = aRequest.getParameter("query_is_published");
227     mergeData.put("query_is_published", query_is_published);
228     String query_media_folder = aRequest.getParameter("query_media_folder");
229     mergeData.put("query_media_folder", query_media_folder);
230     String offset = aRequest.getParameter("offset");
231     if (offset == null || offset.equals("")) offset = "0";
232     mergeData.put("offset", offset);
233
234     String order = aRequest.getParameter("order");
235     if (order == null || order.equals("")) order = "webdb_lastchange desc";
236
237     // if in connection mode to content
238     mergeData.put("articleid", aRequest.getParameter("articleid"));
239     mergeData.put("commentid", aRequest.getParameter("commentid"));
240
241
242     // sql basteln
243     String whereClause = "";
244     boolean isFirst = true;
245     if (query_text != null && !query_text.equalsIgnoreCase("")) {
246       whereClause += "lower(" + query_field + ") like lower('%" + query_text + "%')";
247       isFirst = false;
248     }
249     if (query_is_published != null && !query_is_published.equals("")) {
250       if (isFirst == false) whereClause += " and ";
251       whereClause += "is_published='" + query_is_published + "'";
252       isFirst = false;
253     }
254     if (query_media_folder != null && !query_media_folder.equals("")) {
255       if (isFirst == false) whereClause += " and ";
256       whereClause += "to_media_folder='" + query_media_folder + "'";
257     }
258     //theLog.printDebugInfo("sql-whereclause: " + whereClause + " order: " + order + " offset: " + offset);
259
260     // fetch and deliver
261     try {
262       if (query_text != null || query_is_published != null || query_media_folder != null) {
263         EntityList theList = mainModule.getByWhereClause(whereClause, order, (new Integer(offset)).intValue(), 10);
264         if (theList != null) {
265           mergeData.put("contentlist", theList);
266           if (theList.getOrder() != null) {
267             mergeData.put("order", theList.getOrder());
268             mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder()));
269           }
270           mergeData.put("count", (new Integer(theList.getCount())).toString());
271           mergeData.put("from", (new Integer(theList.getFrom())).toString());
272           mergeData.put("to", (new Integer(theList.getTo())).toString());
273           if (theList.hasNextBatch())
274             mergeData.put("next", (new Integer(theList.getNextBatch())).toString());
275           if (theList.hasPrevBatch())
276             mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString());
277         }
278       }
279       popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
280
281       deliver(aRequest, aResponse, mergeData, popups, templateListString);
282     }
283     catch (Throwable e) {
284       throw new ServletModuleFailure(e);
285     }
286   }
287
288
289   public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
290     try {
291       SimpleHash mergeData = new SimpleHash();
292       SimpleHash popups = new SimpleHash();
293       String maxMedia = MirPropertiesConfiguration.instance().getString("ServletModule.OpenIndy.MaxMediaUploadItems");
294       String numOfMedia = aRequest.getParameter("medianum");
295
296       mergeData.put("new", "1");
297       mergeData.put("articleid", aRequest.getParameter("articleid"));
298       mergeData.put("commentid", aRequest.getParameter("commentid"));
299
300       popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
301
302       if (numOfMedia==null || numOfMedia.equals("")) {
303         numOfMedia="1";
304       }
305       else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
306         numOfMedia = maxMedia;
307       }
308
309       int mediaNum = Integer.parseInt(numOfMedia);
310       SimpleList mediaFields = new SimpleList();
311       for(int i =0; i<mediaNum;i++){
312         Integer mNum = new Integer(i+1);
313         mediaFields.add(mNum.toString());
314       }
315       mergeData.put("medianum",numOfMedia);
316       mergeData.put("mediafields",mediaFields);
317       deliver(aRequest, aResponse, mergeData, popups, templateObjektString);
318     }
319     catch (Exception e) {
320       throw new ServletModuleFailure(e);
321     }
322   }
323
324   public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
325     String idParam = aRequest.getParameter("id");
326     _edit(idParam, aRequest, aResponse);
327   }
328
329   private void _edit(String idParam, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
330     if (idParam != null && !idParam.equals("")) {
331       try {
332         SimpleHash popups = new SimpleHash();
333         popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
334         deliver(aRequest, aResponse, mainModule.getById(idParam), popups,
335                 templateObjektString);
336       }
337       catch (Throwable e) {
338         throw new ServletModuleFailure(e);
339       }
340     }
341     else {
342       throw new ServletModuleExc("ServletmoduleUploadedMedia :: _edit without id");
343     }
344   }
345
346
347   public void getMedia(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
348     String idParam = aRequest.getParameter("id");
349     if (idParam!=null && !idParam.equals("")) {
350       try {
351         EntityUploadedMedia ent = (EntityUploadedMedia)mainModule.getById(idParam);
352         Entity mediaType = ent.getMediaType();
353         MirMedia mediaHandler;
354
355         ServletContext ctx = MirPropertiesConfiguration.getContext();
356         String fName = ent.getId()+"."+mediaType.getValue("name");
357
358         mediaHandler = MediaHelper.getHandler(mediaType);
359         InputStream in = mediaHandler.getMedia(ent, mediaType);
360
361         aResponse.setContentType(ctx.getMimeType(fName));
362         //important that before calling this aResponse.getWriter was not called first
363         ServletOutputStream out = aResponse.getOutputStream();
364
365         int read ;
366         byte[] buf = new byte[8 * 1024];
367         while((read = in.read(buf)) != -1) {
368           out.write(buf, 0, read);
369         }
370         in.close();
371         out.close();
372       }
373       catch (Throwable e) {
374         throw new ServletModuleFailure(e);
375       }
376     }
377     else logger.error("id not specified.");
378     // no exception allowed
379   }
380
381   public void getIcon(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
382   {
383     String idParam = aRequest.getParameter("id");
384     if (idParam!=null && !idParam.equals("")) {
385       try {
386         EntityUploadedMedia ent = (EntityUploadedMedia) mainModule.getById(idParam);
387         Entity mediaType = ent.getMediaType();
388         MirMedia mediaHandler;
389
390         mediaHandler = MediaHelper.getHandler(mediaType);
391         InputStream in = mediaHandler.getIcon(ent);
392
393         if (in==null)
394           throw new ServletModuleExc("no icon available");
395
396         aResponse.setContentType(mediaHandler.getIconMimeType(ent, mediaType));
397         //important that before calling this aResponse.getWriter was not called first
398         ServletOutputStream out = aResponse.getOutputStream();
399
400         int read ;
401         byte[] buf = new byte[8 * 1024];
402         while((read = in.read(buf)) != -1) {
403           out.write(buf, 0, read);
404         }
405         in.close();
406         out.close();
407       }
408
409       catch (Throwable e) {
410         logger.error("getIcon: " + e.toString());
411       }
412     }
413     else logger.error("getIcon: id not specified.");
414     // no exception allowed
415   }
416
417 }
418
419