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