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