added another "virtual member"
[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("description_sentence"))
156         returnField = getDescriptionSentence();
157       else if (field.equals("content_data_parsed"))
158         returnField = getContentDataParsed();
159       else
160         return super.getValue(field);
161     }
162     return returnField;
163         }
164
165   public TemplateModel get(java.lang.String key) throws TemplateModelException
166   {
167     if (key!=null) {
168       if (_entCache.containsKey(key)) {
169         return (TemplateModel)_entCache.get(key);
170       }
171       if (key.equals("to_comments")) {
172         try {
173           _entCache.put(key, getComments());
174           return (TemplateModel)_entCache.get(key);
175         } catch (Exception ex) {
176           theLog.printWarning("-- getComments: could not fetch data " + ex.toString());
177           throw new TemplateModelException(ex.toString());
178         }
179       }
180       if (key.equals("to_media_images")) {
181         try {
182           _entCache.put(key, getImagesForContent());
183           return (TemplateModel)_entCache.get(key);
184         }
185         catch (Exception ex) {
186           theLog.printWarning("-- getImagesForContent: could not fetch data " + ex.toString());
187           throw new TemplateModelException(ex.toString());
188         }
189       }
190       if (key.equals("to_media_audio")) {
191         try {
192           _entCache.put(key, getAudioForContent());
193           return (TemplateModel)_entCache.get(key);
194         }
195         catch (Exception ex) {
196           theLog.printWarning("-- getAudioForContent: could not fetch data " + ex.toString());
197           throw new TemplateModelException(ex.toString());
198         }
199       }
200       if (key.equals("to_media_video")) {
201         try {
202           _entCache.put(key, getVideoForContent());
203           return (TemplateModel)_entCache.get(key);
204         }
205         catch (Exception ex) {
206           theLog.printWarning("-- getVideoForContent: could not fetch data " + ex.toString());
207           throw new TemplateModelException(ex.toString());
208         }
209       }
210       if (key.equals("to_media_other")) {
211         try {
212           _entCache.put(key, getOtherMediaForContent());
213           return (TemplateModel)_entCache.get(key);
214         }
215         catch (Exception ex) {
216           theLog.printWarning("-- getOtherMediaForContent: could not fetch data " + ex.toString());
217           throw new TemplateModelException(ex.toString());
218         }
219       }
220       else if (key.equals("to_media_icon")) {
221         try {
222           _entCache.put(key, getUploadedMediaForNewswire());
223           return (TemplateModel)_entCache.get(key);
224         }
225         catch (Exception ex) {
226           theLog.printWarning("-- getUploadedMediaForNewswire: could not fetch data " + ex.toString());
227           throw new TemplateModelException(ex.toString());
228         }
229       }
230       else if (key.equals("to_topics")) {
231         try {
232           _entCache.put(key, 
233                         DatabaseContentToTopics.getInstance().getTopics(this));
234           return (TemplateModel)_entCache.get(key);
235         }
236         catch (Exception ex) {
237           theLog.printWarning("-- getTopics: could not fetch data " + ex.toString());
238           throw new TemplateModelException(ex.toString());
239         }
240       }
241       else {
242         return new SimpleScalar(getValue(key));
243       }
244
245     }
246     return null;
247   }
248
249
250
251
252         /**
253          * overridden method setValues to patch creator_main_url
254          */
255         public void setValues(HashMap theStringValues) {
256                 if (theStringValues != null) {
257                         if (theStringValues.containsKey("creator_main_url")){
258                                 if (((String)theStringValues.get("creator_main_url")).equalsIgnoreCase("http://")){
259                                         theStringValues.remove("creator_main_url");
260         } else if (!((String)theStringValues.get("creator_main_url")).startsWith("http://")){
261           theStringValues.put("creator_main_url","http://"+((String)theStringValues.get("creator_main_url")));
262         }
263       }
264                 }
265                 super.setValues(theStringValues);
266         }
267
268
269   private String getContentDataParsed() {
270     String returnField = getValue("content_data");
271     if (returnField!=null & returnField.length()>0 ) {
272       returnField=StringUtil.deleteForbiddenTags(returnField);
273       //create http-links and email-links
274       if (getValue("is_html").equals("0")) {
275         returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
276                                             mirconf_mailLinkName,mirconf_extLinkName,
277                                             mirconf_intLinkName);
278       }
279       returnField = StringUtil.decodeHTMLinTags(returnField);
280     }
281     return returnField;
282   }
283
284   private String getDescriptionSentence() {
285     String returnField = getValue("description");
286     if (returnField != null && returnField.length()>0) {
287        returnField = StringUtil.removeHTMLTags(returnField);
288        int endOfFirstSentence=StringUtil.findEndOfSentence(returnField,0);
289        if (endOfFirstSentence > 0){
290          returnField = returnField.substring(0,endOfFirstSentence);
291        }
292     }
293     return returnField;
294   }
295
296   private String getDescriptionParsed() {
297     String returnField = getValue("description");
298     if (returnField != null && returnField.length()>0) {
299       returnField = StringUtil.deleteForbiddenTags(returnField);
300       if (getValue("is_html").equals("0")) {
301         returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
302                                             mirconf_mailLinkName,mirconf_extLinkName,
303                                             mirconf_intLinkName);
304       }
305       returnField = StringUtil.decodeHTMLinTags(returnField);
306     }
307     return returnField;
308   }
309
310         /**
311          * fetches all the comments belonging to an article
312          *
313          * @return freemarker.template.SimpleList
314          */
315         private EntityList getComments() throws StorageObjectException {
316                 return ((DatabaseContent)theStorageObject).getComments(this);
317         }
318
319   // @todo this needs to optimized. expensive SQL
320   private SimpleHash getUploadedMediaForNewswire()
321     throws StorageObjectException, TemplateModelException
322   {
323     // fetching/setting the images
324     // return to_media_icons
325     String        tinyIcon = null, iconAlt = null;
326     MirMedia      mediaHandler = null;
327     EntityUploadedMedia uploadedMedia;
328     Entity        mediaType;
329     SimpleHash    returnHash = new SimpleHash();
330
331     EntityList upMediaEntityList =
332                     DatabaseContentToMedia.getInstance().getUploadedMedia(this);
333     if (upMediaEntityList!=null && upMediaEntityList.getCount()>=1) {
334
335       for (int n=0; n < upMediaEntityList.size();n++) {
336         uploadedMedia = (EntityUploadedMedia)upMediaEntityList.elementAt(n);
337         mediaType = uploadedMedia.getMediaType();
338         try {
339           mediaHandler = MediaHelper.getHandler( mediaType );
340         } catch (MirMediaException ex) {
341           throw new TemplateModelException(ex.toString());
342         }
343         //the "best" media type to show
344         if (mediaHandler.isVideo()) {
345           tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
346           iconAlt = "Video";
347           break;
348         } else if (mediaHandler.isAudio()) {
349           tinyIcon = MirConfig.getProp("Producer.Icon.TinyAudio");
350           iconAlt = "Audio";
351         } else if (tinyIcon == null && !mediaHandler.isImage()) {
352           tinyIcon = mediaHandler.getTinyIcon();
353           iconAlt = mediaHandler.getIconAlt();
354         }
355
356       }
357       //it only has image(s)
358       if (tinyIcon == null) {
359         tinyIcon = MirConfig.getProp("Producer.Icon.TinyImage");
360         iconAlt = "Image";
361       }
362     // uploadedMedia Entity list is empty.
363     // we only have text
364     } else {
365       tinyIcon = MirConfig.getProp("Producer.Icon.TinyText");
366       iconAlt = "Text";
367     }
368     returnHash.put("tiny_icon", mirconf_imageRoot+"/"+tinyIcon);
369     returnHash.put("icon_alt", iconAlt);
370     return returnHash;
371   }
372
373   private boolean hasMedia() throws StorageObjectException
374   {
375     if (_hasMedia == null) {
376       _hasMedia =
377         new Boolean(DatabaseContentToMedia.getInstance().hasMedia(this));
378     }
379     return _hasMedia.booleanValue();
380   }
381
382   //######## @todo all of the following getBlahForContent should have
383   // and optimized version where LIMIT=1 sql for list view.
384   private EntityList getImagesForContent()
385     throws StorageObjectException, TemplateModelException
386   {
387     if (hasMedia())
388       return DatabaseContentToMedia.getInstance().getImages(this);
389     else
390       return null;
391   }
392
393   private EntityList getAudioForContent()
394     throws StorageObjectException, TemplateModelException
395   {
396     if (hasMedia())
397       return DatabaseContentToMedia.getInstance().getAudio(this) ;
398     else
399       return null;
400   }
401
402   private EntityList getVideoForContent()
403     throws StorageObjectException, TemplateModelException
404   {
405     if (hasMedia())
406       return DatabaseContentToMedia.getInstance().getVideo(this) ;
407     else
408       return null;
409   }
410
411   private EntityList getOtherMediaForContent()
412     throws StorageObjectException, TemplateModelException
413   {
414     if (hasMedia())
415       return DatabaseContentToMedia.getInstance().getOther(this);
416     else
417       return null;
418   }
419
420 }