first cut of merge of STABLE-pre1_0 into HEAD. I won't even guarantee that it
[mir.git] / source / mircoders / servlet / ServletModuleImages.java
1 package mircoders.servlet;
2
3 import java.io.*;
4 import java.lang.*;
5 import java.sql.*;
6 import java.util.*;
7 import java.net.*;
8 import java.lang.reflect.*;
9 import javax.servlet.*;
10 import javax.servlet.http.*;
11
12 import freemarker.template.*;
13 import com.oreilly.servlet.multipart.*;
14 import com.oreilly.servlet.*;
15
16 import mir.servlet.*;
17 import mir.module.*;
18 import mir.misc.*;
19 import mir.entity.*;
20 import mir.storage.*;
21 import mir.media.*;
22
23 import mircoders.entity.*;
24 import mircoders.storage.*;
25 import mircoders.module.*;
26 import mircoders.producer.*;
27
28 /*
29  *  ServletModuleBilder -
30  *  liefert HTML fuer Bilder
31  *
32  *
33  * @author RK
34  */
35
36 public class ServletModuleImages extends mir.servlet.ServletModule
37 {
38
39   private static ModuleMediafolder mediafolderModule;
40   private static DatabaseRights dbRights;
41   private static DatabaseImageFormat dbImageFormat;
42   private static DatabaseImageType dbImageType;
43   private static DatabaseImageColor dbImageColor;
44   private static DatabaseImageLayout dbImageLayout;
45
46   // Singelton / Kontruktor
47   private static ServletModuleImages instance = new ServletModuleImages();
48   public static ServletModule getInstance() { return instance; }
49
50
51   private ServletModuleImages() {
52     theLog = Logfile.getInstance(MirConfig.getProp("Home") + MirConfig.getProp("ServletModule.Bilder.Logfile"));
53     templateListString = MirConfig.getProp("ServletModule.Bilder.ListTemplate");
54     templateObjektString = MirConfig.getProp("ServletModule.Bilder.ObjektTemplate");
55     templateConfirmString = MirConfig.getProp("ServletModule.Bilder.ConfirmTemplate");
56     try {
57       mainModule = new ModuleImages(DatabaseImages.getInstance());
58       mediafolderModule = new ModuleMediafolder(DatabaseMediafolder.getInstance());
59       dbRights = DatabaseRights.getInstance();
60       dbImageFormat = DatabaseImageFormat.getInstance();
61       dbImageColor = DatabaseImageColor.getInstance();
62       dbImageType = DatabaseImageType.getInstance();
63       dbImageLayout = DatabaseImageLayout.getInstance();
64     }
65     catch (StorageObjectException e) {
66       theLog.printDebugInfo("servletmodulebilder konnte nicht initialisiert werden");
67     }
68   }
69
70
71   public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
72   {
73     try {
74       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
75       HashMap parameters = mp.getParameters();
76       String mediaId=null;
77       MpRequest mpReq = (MpRequest)mp.requestList.get(0);
78       byte[] imageData=mpReq.getMedia();
79       String fileName=mpReq.getFilename();
80       String contentType= mpReq.getContentType();
81
82       EntityUsers   user = _getUser(req);
83       parameters.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
84       parameters.put("to_publisher", user.getId());
85       parameters.put("is_produced", "0");
86       if (!parameters.containsKey("is_published"))
87         parameters.put("is_published","0");
88
89       String id = mainModule.add(parameters);
90       EntityImages entImage = (EntityImages)mainModule.getById(id);
91
92       if (imageData!=null && fileName!=null) {
93             //the where clause to find the media_type entry
94         //from the content-type.
95         //we use the media type entry to lookup the
96         //media Handler/Storage classes
97         String wc = " mime_type='"+contentType+"'";
98
99         EntityList mediaTypesList = DatabaseMediaType.getInstance().selectByWhereClause(wc);
100             String mediaTypeId = null;
101         String mediaStorageName = null;
102         String mediaHandlerName = null;
103
104         //if we found an entry matching the
105         //content-type int the table.
106         if (mediaTypesList.size() > 0) {
107           //get the class names from the media_type table.
108           mediaTypeId = mediaTypesList.elementAt(0).getId();
109           mediaStorageName = mediaTypesList.elementAt(0).getValue("tablename");
110           mediaHandlerName = mediaTypesList.elementAt(0).getValue("classname");
111           parameters.put("to_media_type",mediaTypeId);
112
113           //load the classes via reflection
114           String MediaId;
115           try {
116                 Class mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
117                 Method m = mediaStorageClass.getMethod("getInstance", null);
118                 Database mediaStorage = (Database)m.invoke(null, null);
119                 Entity mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
120                 mediaEnt.setStorage(mediaStorage);
121                 mediaEnt.setValues(parameters);
122                 mediaId = mediaEnt.insert();
123
124                 Class mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
125                 MirMedia mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
126                 //save and store the media data/metadata
127                 mediaHandler.set(mpReq.getMedia(), mediaEnt,mediaTypesList.elementAt(0));
128
129                 //were done with mpReq at this point, dereference it. as it contains
130                 //mucho mem. -mh 01.10.2001
131                 mpReq=null;
132
133               if(mediaId!=null){
134                 new ProducerMedia().handle(null, null, false, false, mediaId);
135               }
136               } catch (Exception e) {
137                 theLog.printError("setting uploaded_media failed: "+e.toString());
138           } //end try-catch
139
140
141         entImage.setImage(imageData);
142       }
143       _edit(id, req, res);
144       }
145     }
146     catch (IOException e) { throw new ServletModuleException("upload -- ioexception " + e.toString());}
147     catch (ModuleException e) { throw new ServletModuleException("upload -- moduleexception " + e.toString());}
148     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
149
150   }
151
152   public void update(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
153   {
154
155     try {
156       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
157       HashMap parameters = mp.getParameters();
158       //MpRequest mpReq = (MpRequest)mp.requestList.get(0);
159       //byte[] imageData=mpReq.getMedia();
160       //String fileName=mpReq.getFilename();
161       //String contentType=mpReq.getContentType();
162
163       EntityUsers   user = _getUser(req);
164       parameters.put("to_publisher", user.getId());
165       parameters.put("is_produced", "0");
166       if (!parameters.containsKey("is_published"))
167         parameters.put("is_published","0");
168
169       String id = mainModule.set(parameters);
170       theLog.printError("Image ID"+id);
171       _edit(id, req, res);
172     }
173     catch (IOException e) { throw new ServletModuleException("upload -- ioexception " + e.toString());}
174     catch (ModuleException e) { throw new ServletModuleException("upload -- moduleexception " + e.toString());}
175
176   }
177
178
179   public void showimg(HttpServletRequest req, HttpServletResponse res)
180     throws ServletModuleException
181   {
182     String idParam = req.getParameter("id");
183     if (idParam!=null && !idParam.equals("")) {
184       try {
185         EntityImages entImage =(EntityImages)mainModule.getById(idParam);
186         res.setContentType("image/jpeg"); // testweise
187         ServletOutputStream out = res.getOutputStream(); // wichtig, dass vorher kein res.getwriter() gelaufen ist
188
189         byte[] outbytes = entImage.getImage();
190         out.write(outbytes);
191         out.close();
192       }
193
194       catch (IOException e) {throw new ServletModuleException(e.toString());}
195       catch (ModuleException e) {throw new ServletModuleException(e.toString());}
196       catch (Exception e) {throw new ServletModuleException(e.toString());}
197     }
198     else theLog.printDebugInfo("id nicht angeben.");
199     // darf keine exception werfen
200   }
201
202   public void showicon(HttpServletRequest req, HttpServletResponse res)
203     throws ServletModuleException
204   {
205     String idParam = req.getParameter("id");
206     if (idParam!=null && !idParam.equals("")) {
207       try {
208         EntityImages entImage =(EntityImages)mainModule.getById(idParam);
209         res.setContentType("image/jpeg"); // testweise
210         ServletOutputStream out = res.getOutputStream(); // wichtig, dass vorher kein res.getwriter() gelaufen ist
211
212         byte[] outbytes = entImage.getIcon();
213         out.write(outbytes);
214         out.close();
215       }
216
217       catch (IOException e) {throw new ServletModuleException(e.toString());}
218       catch (ModuleException e) {throw new ServletModuleException(e.toString());}
219       catch (Exception e) {throw new ServletModuleException(e.toString());}
220     }
221     else throw new ServletModuleException("id nicht angeben.");
222   }
223
224   public void list(HttpServletRequest req, HttpServletResponse res)
225     throws ServletModuleException
226   {
227       // Parameter auswerten
228       SimpleHash mergeData = new SimpleHash();
229       String query_text = req.getParameter("query_text");
230       mergeData.put("query_text",query_text);
231       if (query_text!=null) mergeData.put("query_text_encoded",URLEncoder.encode(query_text));
232       String query_field = req.getParameter("query_field");
233       mergeData.put("query_field",query_field);
234       String query_is_published = req.getParameter("query_is_published");
235       mergeData.put("query_is_published",query_is_published);
236       String query_media_folder = req.getParameter("query_media_folder");
237       mergeData.put("query_media_folder",query_media_folder);
238       String offset = req.getParameter("offset");
239       if (offset==null || offset.equals("")) offset="0";
240       mergeData.put("offset",offset);
241
242       String order = req.getParameter("order");
243       if (order==null) order="webdb_lastchange desc";
244
245       // if in connection mode to content
246       String cid = req.getParameter("cid");
247       mergeData.put("cid",cid);
248
249
250       // sql basteln
251       String whereClause=""; boolean isFirst=true;
252       if (query_text!=null && !query_text.equalsIgnoreCase("")) {
253         whereClause += "lower("+query_field+") like lower('%"+query_text+"%')"; isFirst=false;}
254       if (query_is_published != null && !query_is_published.equals("")) {
255         if (isFirst==false) whereClause+=" and ";
256         whereClause += "is_published='"+query_is_published+"'";
257         isFirst=false;
258       }
259       if (query_media_folder != null && !query_media_folder.equals("")) {
260         if (isFirst==false) whereClause+=" and ";
261         whereClause += "to_media_folder='"+query_media_folder+"'";
262       }
263       //theLog.printDebugInfo("sql-whereclause: " + whereClause + " order: " + order + " offset: " + offset);
264
265       // fetch und ausliefern
266       try {
267         mergeData.put("mediafolderPopupData", mediafolderModule.getPopupData());
268         mergeData.put("mediafolderHashdata", mediafolderModule.getHashData());
269         if (query_text!=null || query_is_published!=null || query_media_folder!=null) {
270           EntityList theList = mainModule.getByWhereClause(whereClause, order, (new Integer(offset)).intValue(),10);
271           if (theList != null) {
272             mergeData.put("contentlist",HTMLTemplateProcessor.makeSimpleList(theList));
273             if(theList.getOrder()!=null) {
274               mergeData.put("order", theList.getOrder());
275               mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder()));
276             }
277             mergeData.put("count", (new Integer(theList.getCount())).toString());
278             mergeData.put("from", (new Integer(theList.getFrom())).toString());
279             mergeData.put("to", (new Integer(theList.getTo())).toString());
280             if (theList.hasNextBatch())
281               mergeData.put("next", (new Integer(theList.getNextBatch())).toString());
282             if (theList.hasPrevBatch())
283               mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString());
284           }
285         }
286         // raus damit
287         HTMLTemplateProcessor.process(res,getLanguage(req)+"/"+templateListString, mergeData, res.getWriter());
288       }
289       catch (ModuleException e) {throw new ServletModuleException(e.toString());}
290       catch (IOException e) {throw new ServletModuleException(e.toString());}
291       catch (Exception e) {throw new ServletModuleException(e.toString());}
292   }
293
294
295   public void add(HttpServletRequest req, HttpServletResponse res)
296   throws ServletModuleException
297   {
298     try {
299       SimpleHash mergeData = new SimpleHash();
300       mergeData.put("new", "1");
301       mergeData.put("mediafolderPopupData", mediafolderModule.getPopupData());
302       deliver(req, res, mergeData, templateObjektString);
303     }
304     catch (Exception e) { throw new ServletModuleException(e.toString());}
305   }
306
307   public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
308   {
309     String        idParam = req.getParameter("id");
310     _edit(idParam, req, res);
311   }
312
313   private void _edit(String idParam, HttpServletRequest req, HttpServletResponse res) throws ServletModuleException {
314     if (idParam!=null && !idParam.equals("")) {
315       try {
316         SimpleHash mergeData =  HTMLTemplateProcessor.makeSimpleHash(mainModule.getById(idParam));
317         mergeData.put("mediafolderPopupData", mediafolderModule.getPopupData());
318         mergeData.put("rightsHashdata", dbRights.getHashData());
319         mergeData.put("imgformatHashdata", dbImageFormat.getHashData());
320         mergeData.put("imgcolorHashdata", dbImageColor.getHashData());
321         mergeData.put("imgtypeHashdata", dbImageType.getHashData());
322         mergeData.put("imglayoutHashdata", dbImageLayout.getHashData());
323         deliver(req, res, mergeData, templateObjektString);
324       }
325       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
326     }
327     else throw new ServletModuleException("ServletmoduleImage :: _edit without id");
328   }
329
330
331   /** @todo should be in ServletModule.java */
332   private EntityUsers _getUser(HttpServletRequest req)
333   {
334     HttpSession session=req.getSession(false);
335     return (EntityUsers)session.getAttribute("login.uid");
336   }
337
338
339   // deprecated
340   public void upload(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
341   {
342     //theLog.printDebugInfo("-- trying to upload");
343     String idParam = req.getParameter("id");
344     if (idParam!=null && !idParam.equals("")) {
345       try {
346
347         WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
348         HashMap withValues = mp.getParameters();
349         MpRequest mpReq = (MpRequest)mp.requestList.get(0);
350         byte[] imageData=mpReq.getMedia();
351         String fileName=mpReq.getFilename();
352         String contentType=mpReq.getContentType();
353
354         EntityImages entImage = (EntityImages)mainModule.getById(idParam);
355         entImage.setImage(imageData);
356       }
357       catch (IOException e) { throw new ServletModuleException("upload -- ioexception " + e.toString());}
358       catch (ModuleException e) { throw new ServletModuleException("upload -- moduleexception " + e.toString());}
359       catch (StorageObjectException e) { throw new ServletModuleException("upload -- storageobjectexception " + e.toString());}
360     }
361     else // keine id
362       throw new ServletModuleException("Keine id angegeben");
363     edit(req,res);
364   }
365
366
367 }