e8702f56e8ec90c948d71ddd95670f0a3fef0eba
[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(this.getClass().getName());
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         String fileType = "-1";
94         
95         //the where clause to find the media_type entry
96         //from the content-type.
97         //we use the media type entry to lookup the 
98         //media Handler/Storage classes
99         String wc = " mime_type='"+contentType+"'";
100
101         EntityList mediaTypesList = DatabaseMediaType.getInstance().selectByWhereClause(wc);
102         String mediaTypeId = null;
103         String mediaStorageName = null;
104         String mediaHandlerName = null;
105  
106         //if we found an entry matching the
107         //content-type int the table.
108         if (mediaTypesList.size() > 0) {
109           //get the class names from the media_type table.
110           mediaTypeId = mediaTypesList.elementAt(0).getId();
111           mediaStorageName = mediaTypesList.elementAt(0).getValue("tablename");
112           mediaHandlerName = mediaTypesList.elementAt(0).getValue("classname");
113           parameters.put("to_media_type",mediaTypeId);
114          
115           //load the classes via reflection
116           String MediaId;
117           try {
118                 Class mediaStorageClass = Class.forName("mircoders.storage.Database"+mediaStorageName);
119                 Method m = mediaStorageClass.getMethod("getInstance", null);
120                 Database mediaStorage = (Database)m.invoke(null, null);
121                 Entity mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
122                 mediaEnt.setStorage(mediaStorage);
123                 mediaEnt.setValues(parameters);
124                 mediaId = mediaEnt.insert();
125
126                 Class mediaHandlerClass = Class.forName("mir.media.MediaHandler"+mediaHandlerName);
127                 MirMedia mediaHandler = (MirMedia)mediaHandlerClass.newInstance();
128                 //save and store the media data/metadata
129                 mediaHandler.set(mpReq.getMedia(), mediaEnt,mediaTypesList.elementAt(0));
130
131                 //were done with mpReq at this point, dereference it. as it contains
132                 //mucho mem. -mh 01.10.2001
133                 mpReq=null;
134               
135               if(mediaId!=null){
136                 new ProducerMedia().handle(null, null, false, false, mediaId);
137               }
138           } catch (Exception e) {
139               theLog.printError("setting uploaded_media failed: "+e.toString());
140           } //end try-catch
141
142
143         if (fileType != "-1")
144           entImage.setImage(imageData, fileType);
145         else
146           theLog.printError("Wrong file uploaded!");
147       }
148       _edit(id, req, res);
149       }
150     }
151     catch (IOException e) { throw new ServletModuleException("upload -- ioexception " + e.toString());}
152     catch (ModuleException e) { throw new ServletModuleException("upload -- moduleexception " + e.toString());}
153     catch (StorageObjectException e) { throw new ServletModuleException("StorageObjectException" + e.toString());}
154
155   }
156
157   public void update(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
158   {
159
160     try {
161       WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
162       HashMap parameters = mp.getParameters();
163       MpRequest mpReq = (MpRequest)mp.requestList.get(0);
164       byte[] imageData=mpReq.getMedia();
165       String fileName=mpReq.getFilename();
166       String contentType=mpReq.getContentType();
167
168       EntityUsers   user = _getUser(req);
169       parameters.put("to_publisher", user.getId());
170       parameters.put("is_produced", "0");
171       if (!parameters.containsKey("is_published"))
172         parameters.put("is_published","0");
173
174       String id = mainModule.set(parameters);
175       EntityImages entImage = (EntityImages)mainModule.getById(id);
176
177       if (imageData!=null && fileName!=null) {
178         String fileType = "-1";
179         if (contentType.equals("image/jpeg")) fileType="0";
180         if (contentType.equals("image/gif")) fileType="1";
181         if (fileType != "-1")
182           entImage.setImage(imageData, fileType);
183         else
184           theLog.printError("Wrong file uploaded!");
185       }
186       _edit(id, req, res);
187     }
188     catch (IOException e) { throw new ServletModuleException("upload -- ioexception " + e.toString());}
189     catch (ModuleException e) { throw new ServletModuleException("upload -- moduleexception " + e.toString());}
190
191   }
192
193
194   public void showimg(HttpServletRequest req, HttpServletResponse res)
195     throws ServletModuleException
196   {
197     String idParam = req.getParameter("id");
198     if (idParam!=null && !idParam.equals("")) {
199       try {
200         EntityImages entImage =(EntityImages)mainModule.getById(idParam);
201         res.setContentType("image/jpeg"); // testweise
202         ServletOutputStream out = res.getOutputStream(); // wichtig, dass vorher kein res.getwriter() gelaufen ist
203
204         byte[] outbytes = entImage.getImage();
205         out.write(outbytes);
206         out.close();
207       }
208
209       catch (IOException e) {throw new ServletModuleException(e.toString());}
210       catch (ModuleException e) {throw new ServletModuleException(e.toString());}
211       catch (Exception e) {throw new ServletModuleException(e.toString());}
212     }
213     else theLog.printDebugInfo("id nicht angeben.");
214     // darf keine exception werfen
215   }
216
217   public void showicon(HttpServletRequest req, HttpServletResponse res)
218     throws ServletModuleException
219   {
220     String idParam = req.getParameter("id");
221     if (idParam!=null && !idParam.equals("")) {
222       try {
223         EntityImages entImage =(EntityImages)mainModule.getById(idParam);
224         res.setContentType("image/jpeg"); // testweise
225         ServletOutputStream out = res.getOutputStream(); // wichtig, dass vorher kein res.getwriter() gelaufen ist
226
227         byte[] outbytes = entImage.getIcon();
228         out.write(outbytes);
229         out.close();
230       }
231
232       catch (IOException e) {throw new ServletModuleException(e.toString());}
233       catch (ModuleException e) {throw new ServletModuleException(e.toString());}
234       catch (Exception e) {throw new ServletModuleException(e.toString());}
235     }
236     else throw new ServletModuleException("id nicht angeben.");
237   }
238
239   public void list(HttpServletRequest req, HttpServletResponse res)
240     throws ServletModuleException
241   {
242       // Parameter auswerten
243       SimpleHash mergeData = new SimpleHash();
244       String query_text = req.getParameter("query_text");
245       mergeData.put("query_text",query_text);
246       if (query_text!=null) mergeData.put("query_text_encoded",URLEncoder.encode(query_text));
247       String query_field = req.getParameter("query_field");
248       mergeData.put("query_field",query_field);
249       String query_is_published = req.getParameter("query_is_published");
250       mergeData.put("query_is_published",query_is_published);
251       String query_media_folder = req.getParameter("query_media_folder");
252       mergeData.put("query_media_folder",query_media_folder);
253       String offset = req.getParameter("offset");
254       if (offset==null || offset.equals("")) offset="0";
255       mergeData.put("offset",offset);
256
257       String order = req.getParameter("order");
258       if (order==null) order="webdb_lastchange desc";
259
260       // if in connection mode to content
261       String cid = req.getParameter("cid");
262       mergeData.put("cid",cid);
263
264
265       // sql basteln
266       String whereClause=""; boolean isFirst=true;
267       if (query_text!=null && !query_text.equalsIgnoreCase("")) {
268         whereClause += "lower("+query_field+") like lower('%"+query_text+"%')"; isFirst=false;}
269       if (query_is_published != null && !query_is_published.equals("")) {
270         if (isFirst==false) whereClause+=" and ";
271         whereClause += "is_published='"+query_is_published+"'";
272         isFirst=false;
273       }
274       if (query_media_folder != null && !query_media_folder.equals("")) {
275         if (isFirst==false) whereClause+=" and ";
276         whereClause += "to_media_folder='"+query_media_folder+"'";
277       }
278       //theLog.printDebugInfo("sql-whereclause: " + whereClause + " order: " + order + " offset: " + offset);
279
280       // fetch und ausliefern
281       try {
282         mergeData.put("mediafolderPopupData", mediafolderModule.getPopupData());
283         mergeData.put("mediafolderHashdata", mediafolderModule.getHashData());
284         if (query_text!=null || query_is_published!=null || query_media_folder!=null) {
285           EntityList theList = mainModule.getByWhereClause(whereClause, order, (new Integer(offset)).intValue(),10);
286           if (theList != null) {
287             mergeData.put("contentlist",HTMLTemplateProcessor.makeSimpleList(theList));
288             if(theList.getOrder()!=null) {
289               mergeData.put("order", theList.getOrder());
290               mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder()));
291             }
292             mergeData.put("count", (new Integer(theList.getCount())).toString());
293             mergeData.put("from", (new Integer(theList.getFrom())).toString());
294             mergeData.put("to", (new Integer(theList.getTo())).toString());
295             if (theList.hasNextBatch())
296               mergeData.put("next", (new Integer(theList.getNextBatch())).toString());
297             if (theList.hasPrevBatch())
298               mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString());
299           }
300         }
301         // raus damit
302         HTMLTemplateProcessor.process(res,getLanguage(req)+"/"+templateListString, mergeData, res.getWriter());
303       }
304       catch (ModuleException e) {throw new ServletModuleException(e.toString());}
305       catch (IOException e) {throw new ServletModuleException(e.toString());}
306       catch (Exception e) {throw new ServletModuleException(e.toString());}
307   }
308
309
310   public void add(HttpServletRequest req, HttpServletResponse res)
311   throws ServletModuleException
312   {
313     try {
314       SimpleHash mergeData = new SimpleHash();
315       mergeData.put("new", "1");
316       mergeData.put("mediafolderPopupData", mediafolderModule.getPopupData());
317       deliver(req, res, mergeData, templateObjektString);
318     }
319     catch (Exception e) { throw new ServletModuleException(e.toString());}
320   }
321
322   public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
323   {
324     String        idParam = req.getParameter("id");
325     _edit(idParam, req, res);
326   }
327
328   private void _edit(String idParam, HttpServletRequest req, HttpServletResponse res) throws ServletModuleException {
329     if (idParam!=null && !idParam.equals("")) {
330       try {
331         SimpleHash mergeData =  HTMLTemplateProcessor.makeSimpleHash(mainModule.getById(idParam));
332         mergeData.put("mediafolderPopupData", mediafolderModule.getPopupData());
333         mergeData.put("rightsHashdata", dbRights.getHashData());
334         mergeData.put("imgformatHashdata", dbImageFormat.getHashData());
335         mergeData.put("imgcolorHashdata", dbImageColor.getHashData());
336         mergeData.put("imgtypeHashdata", dbImageType.getHashData());
337         mergeData.put("imglayoutHashdata", dbImageLayout.getHashData());
338         deliver(req, res, mergeData, templateObjektString);
339       }
340       catch (ModuleException e) { throw new ServletModuleException(e.toString());}
341     }
342     else throw new ServletModuleException("ServletmoduleImage :: _edit without id");
343   }
344
345
346   /** @todo should be in ServletModule.java */
347   private EntityUsers _getUser(HttpServletRequest req)
348   {
349     HttpSession session=req.getSession(false);
350     return (EntityUsers)session.getAttribute("login.uid");
351   }
352
353
354   // deprecated
355   public void upload(HttpServletRequest req, HttpServletResponse res) throws ServletModuleException
356   {
357     //theLog.printDebugInfo("-- trying to upload");
358     String idParam = req.getParameter("id");
359     if (idParam!=null && !idParam.equals("")) {
360       try {
361
362         WebdbMultipartRequest mp = new WebdbMultipartRequest(req);
363         HashMap withValues = mp.getParameters();
364         MpRequest mpReq = (MpRequest)mp.requestList.get(0);
365         byte[] imageData=mpReq.getMedia();
366         String fileName=mpReq.getFilename();
367         String contentType=mpReq.getContentType();
368
369         String fileType = "-1";
370         if (contentType.equals("image/jpeg")) fileType="0";
371         if (contentType.equals("image/gif")) fileType="1";
372         if (fileType != "-1") {
373           EntityImages entImage = (EntityImages)mainModule.getById(idParam);
374           entImage.setImage(imageData, fileType);
375         }
376         else
377           theLog.printError("Wrong file uploaded!");
378       }
379       catch (IOException e) { throw new ServletModuleException("upload -- ioexception " + e.toString());}
380       catch (ModuleException e) { throw new ServletModuleException("upload -- moduleexception " + e.toString());}
381     }
382     else // keine id
383       throw new ServletModuleException("Keine id angegeben");
384     edit(req,res);
385   }
386
387
388 }