media stuff
[mir.git] / source / mircoders / entity / EntityContent.java
1 package mircoders.entity;
2
3 import java.lang.*;
4 import java.io.*;
5 import java.util.*;
6 import java.sql.*;
7 import java.lang.reflect.*;
8
9 import freemarker.template.*;
10
11 import mir.entity.*;
12 import mir.misc.*;
13 import mir.media.*;
14 import mir.storage.*;
15
16 import mircoders.storage.*;
17
18 /**
19  * this class implements mapping of one line of the database table content
20  * to a java object
21  *
22  * @author RK
23  * @version 2001
24  */
25
26
27 public class EntityContent extends Entity
28 {
29
30   String mirconf_extLinkName  = MirConfig.getProp("Producer.ExtLinkName");
31   String mirconf_intLinkName  = MirConfig.getProp("Producer.IntLinkName");
32   String mirconf_mailLinkName = MirConfig.getProp("Producer.MailLinkName");
33   String mirconf_imageRoot    = MirConfig.getProp("Producer.ImageRoot");
34
35   //this should always be transient i.e it can never be stored in the db
36   //or ObjectStore. (so the ObjectStore should only be caching what comes
37   //directly out of the DB. @todo confirm this with rk. -mh
38   HashMap _entCache = new HashMap();
39   Boolean _hasMedia = null;
40
41         // constructors
42
43         public EntityContent()
44         {
45                 super();
46     //content_data is now filed-type "text"
47                 //streamedInput = new ArrayList();
48                 //streamedInput.add("content_data");
49         }
50
51         public EntityContent(StorageObject theStorage) {
52                 this();
53                 setStorage(theStorage);
54         }
55
56         //
57         // methods
58
59  /**
60         * set is_produced flag for the article
61         */
62
63         public void setProduced(boolean yesno) throws StorageObjectException
64         {
65                 String value = (yesno) ? "1":"0";
66                 if (value.equals( getValue("is_produced") )) return;
67
68     Connection con=null;Statement stmt=null;
69     String sql = "update content set is_produced='" + value + "' where id='" + getId()+"'";
70                 try {
71                         con = theStorageObject.getPooledCon();
72                         /** @todo should be preparedStatement: faster!! */
73                         stmt = con.createStatement();
74                         theStorageObject.executeUpdate(stmt,sql);
75                 } catch (StorageObjectException e) {
76             throwStorageObjectException(e, "\n -- set produced failed");
77                 } catch (SQLException e) {
78             throwStorageObjectException(e, "\n -- set produced failed");
79                 } finally {
80                         theStorageObject.freeConnection(con,stmt);
81                 }
82         }
83
84
85  /**
86         * make openposting to newswire
87         */
88
89         public void newswire() throws StorageObjectException
90         {
91                 String sql = "update content set to_article_type='1', is_produced='0' where id='" + getId()+"'";
92                 try {
93                                 theStorageObject.executeUpdate(sql);
94                 } catch (StorageObjectException e) {
95             throwStorageObjectException(e, "\n -- newswire failed");
96                 } catch (SQLException e) {
97             throwStorageObjectException(e, "\n -- newswire failed");
98                 }
99         }
100
101
102  /**
103         * dettach from media
104         */
105         public void dettach(String cid,String mid) throws StorageObjectException
106         {
107                 if (mid!=null){
108                         try{
109                                 DatabaseContentToMedia.getInstance().delete(cid,mid);
110                         } catch (Exception e){
111                 throwStorageObjectException(e, "\n -- failed to get instance");
112                         }
113                         //set Content to unproduced
114                         setProduced(false);
115                 }
116         }
117
118  /**
119         * attach to media
120         */
121
122         public void attach(String mid) throws StorageObjectException
123         {
124                 if (mid!=null) {
125                         //write media-id mid and content-id in table content_x_media
126                         try{
127                                 DatabaseContentToMedia.getInstance().addMedia(getId(),mid);
128                         } catch(StorageObjectException e){
129                                 throwStorageObjectException(e, "attach: could not get the instance");
130                         }
131                         //set Content to unproduced
132                         setProduced(false);
133                 }       else {
134                         theLog.printError("EntityContent: attach without mid");
135                 }
136         }
137
138         /**
139          * overridden method getValue to include formatted date into every
140          * entityContent
141          */
142
143         public String getValue(String field)
144   {
145     String returnField = null;
146     if (field!=null)
147     {
148       if (field.equals("date_formatted"))
149       {
150                   if (hasValueForField("date"))
151         returnField = StringUtil.webdbDate2readableDate(getValue("date"));
152                 }
153       else if (field.equals("description_parsed"))
154         returnField = getDescriptionParsed();
155       else if (field.equals("content_data_parsed"))
156         returnField = getContentDataParsed();
157       else
158         return super.getValue(field);
159     }
160     return returnField;
161         }
162
163   public TemplateModel get(java.lang.String key) throws TemplateModelException
164   {
165     if (key!=null) {
166       if (_entCache.containsKey(key)) {
167         return (TemplateModel)_entCache.get(key);
168       }
169       if (key.equals("to_comments")) {
170         try {
171           _entCache.put(key, getComments());
172           return (TemplateModel)_entCache.get(key);
173         } catch (Exception ex) {
174           theLog.printWarning("-- getComments: could not fetch data " + ex.toString());
175           throw new TemplateModelException(ex.toString());
176         }
177       }
178       if (key.equals("to_media_images")) {
179         try {
180           _entCache.put(key, getImagesForContent());
181           return (TemplateModel)_entCache.get(key);
182         }
183         catch (Exception ex) {
184           theLog.printWarning("-- getImagesForContent: could not fetch data " + ex.toString());
185           throw new TemplateModelException(ex.toString());
186         }
187       }
188       if (key.equals("to_media_audio")) {
189         try {
190           _entCache.put(key, getAudioForContent());
191           return (TemplateModel)_entCache.get(key);
192         }
193         catch (Exception ex) {
194           theLog.printWarning("-- getAudioForContent: could not fetch data " + ex.toString());
195           throw new TemplateModelException(ex.toString());
196         }
197       }
198       if (key.equals("to_media_video")) {
199         try {
200           _entCache.put(key, getVideoForContent());
201           return (TemplateModel)_entCache.get(key);
202         }
203         catch (Exception ex) {
204           theLog.printWarning("-- getVideoForContent: could not fetch data " + ex.toString());
205           throw new TemplateModelException(ex.toString());
206         }
207       }
208       if (key.equals("to_media_other")) {
209         try {
210           _entCache.put(key, getOtherMediaForContent());
211           return (TemplateModel)_entCache.get(key);
212         }
213         catch (Exception ex) {
214           theLog.printWarning("-- getOtherMediaForContent: could not fetch data " + ex.toString());
215           throw new TemplateModelException(ex.toString());
216         }
217       }
218       else if (key.equals("to_media_icon")) {
219         try {
220           _entCache.put(key, getUploadedMediaForNewswire());
221           return (TemplateModel)_entCache.get(key);
222         }
223         catch (Exception ex) {
224           theLog.printWarning("-- getUploadedMediaForNewswire: could not fetch data " + ex.toString());
225           throw new TemplateModelException(ex.toString());
226         }
227       }
228       else if (key.equals("to_topics")) {
229         try {
230           _entCache.put(key, 
231                         DatabaseContentToTopics.getInstance().getTopics(this));
232           return (TemplateModel)_entCache.get(key);
233         }
234         catch (Exception ex) {
235           theLog.printWarning("-- getTopics: could not fetch data " + ex.toString());
236           throw new TemplateModelException(ex.toString());
237         }
238       }
239       else {
240         return new SimpleScalar(getValue(key));
241       }
242
243     }
244     return null;
245   }
246
247
248
249
250         /**
251          * overridden method setValues to patch creator_main_url
252          */
253         public void setValues(HashMap theStringValues) {
254                 if (theStringValues != null) {
255                         if (theStringValues.containsKey("creator_main_url")){
256                                 if (((String)theStringValues.get("creator_main_url")).equalsIgnoreCase("http://")){
257                                         theStringValues.remove("creator_main_url");
258         } else if (!((String)theStringValues.get("creator_main_url")).startsWith("http://")){
259           theStringValues.put("creator_main_url","http://"+((String)theStringValues.get("creator_main_url")));
260         }
261       }
262                 }
263                 super.setValues(theStringValues);
264         }
265
266
267   private String getContentDataParsed() {
268     String returnField = getValue("content_data");
269     if (returnField!=null & returnField.length()>0 ) {
270       returnField=StringUtil.deleteForbiddenTags(returnField);
271       //create http-links and email-links
272       if (getValue("is_html").equals("0")) {
273         returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
274                                             mirconf_mailLinkName,mirconf_extLinkName,
275                                             mirconf_intLinkName);
276       }
277       returnField = StringUtil.decodeHTMLinTags(returnField);
278     }
279     return returnField;
280   }
281
282
283   private String getDescriptionParsed() {
284     String returnField = getValue("description");
285     if (returnField != null && returnField.length()>0) {
286       returnField = StringUtil.deleteForbiddenTags(returnField);
287       if (getValue("is_html").equals("0")) {
288         returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
289                                             mirconf_mailLinkName,mirconf_extLinkName,
290                                             mirconf_intLinkName);
291       }
292       returnField = StringUtil.decodeHTMLinTags(returnField);
293     }
294     return returnField;
295   }
296
297         /**
298          * fetches all the comments belonging to an article
299          *
300          * @return freemarker.template.SimpleList
301          */
302         private EntityList getComments() throws StorageObjectException {
303                 return ((DatabaseContent)theStorageObject).getComments(this);
304         }
305
306   // @todo this needs to optimized. expensive SQL
307   private SimpleHash getUploadedMediaForNewswire()
308     throws StorageObjectException, TemplateModelException
309   {
310     // fetching/setting the images
311     // return to_media_icons
312     String        tinyIcon = null, iconAlt = null;
313     MirMedia      mediaHandler = null;
314     EntityUploadedMedia uploadedMedia;
315     Entity        mediaType;
316     SimpleHash    returnHash = new SimpleHash();
317
318     EntityList upMediaEntityList =
319                     DatabaseContentToMedia.getInstance().getUploadedMedia(this);
320     if (upMediaEntityList!=null && upMediaEntityList.getCount()>=1) {
321
322       for (int n=0; n < upMediaEntityList.size();n++) {
323         uploadedMedia = (EntityUploadedMedia)upMediaEntityList.elementAt(n);
324         mediaType = uploadedMedia.getMediaType();
325         try {
326           mediaHandler = MediaHelper.getHandler( mediaType );
327         } catch (MirMediaException ex) {
328           throw new TemplateModelException(ex.toString());
329         }
330         //the "best" media type to show
331         if (mediaHandler.isVideo()) {
332           tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
333           iconAlt = "Video";
334           break;
335         } else if (mediaHandler.isAudio()) {
336           tinyIcon = MirConfig.getProp("Producer.Icon.TinyAudio");
337           iconAlt = "Audio";
338         } else if (tinyIcon == null && !mediaHandler.isImage()) {
339           tinyIcon = mediaHandler.getTinyIcon();
340           iconAlt = mediaHandler.getIconAlt();
341         }
342
343       }
344       //it only has image(s)
345       if (tinyIcon == null) {
346         tinyIcon = MirConfig.getProp("Producer.Icon.TinyImage");
347         iconAlt = "Image";
348       }
349     // uploadedMedia Entity list is empty.
350     // we only have text
351     } else {
352       tinyIcon = MirConfig.getProp("Producer.Icon.TinyText");
353       iconAlt = "Text";
354     }
355     returnHash.put("tiny_icon", mirconf_imageRoot+"/"+tinyIcon);
356     returnHash.put("icon_alt", iconAlt);
357     return returnHash;
358   }
359
360   private boolean hasMedia() throws StorageObjectException
361   {
362     if (_hasMedia == null) {
363       _hasMedia =
364         new Boolean(DatabaseContentToMedia.getInstance().hasMedia(this));
365     }
366     return _hasMedia.booleanValue();
367   }
368
369   //######## @todo all of the following getBlahForContent should have
370   // and optimized version where LIMIT=1 sql for list view.
371   private EntityList getImagesForContent()
372     throws StorageObjectException, TemplateModelException
373   {
374     if (hasMedia())
375       return DatabaseContentToMedia.getInstance().getImages(this);
376     else
377       return null;
378   }
379
380   private EntityList getAudioForContent()
381     throws StorageObjectException, TemplateModelException
382   {
383     if (hasMedia())
384       return DatabaseContentToMedia.getInstance().getAudio(this) ;
385     else
386       return null;
387   }
388
389   private EntityList getVideoForContent()
390     throws StorageObjectException, TemplateModelException
391   {
392     if (hasMedia())
393       return DatabaseContentToMedia.getInstance().getVideo(this) ;
394     else
395       return null;
396   }
397
398   private EntityList getOtherMediaForContent()
399     throws StorageObjectException, TemplateModelException
400   {
401     if (hasMedia())
402       return DatabaseContentToMedia.getInstance().getOther(this);
403     else
404       return null;
405   }
406
407 }