bbf142cdaf72529d80cc684c7f45ea56faea8516
[mir.git] / source / mircoders / entity / EntityContent.java
1 /*
2  * Copyright (C) 2001, 2002  The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package mircoders.entity;
33
34 import java.lang.*;
35 import java.io.*;
36 import java.util.*;
37 import java.sql.*;
38 import java.lang.reflect.*;
39
40 import freemarker.template.*;
41
42 import mir.entity.*;
43 import mir.misc.*;
44 import mir.media.*;
45 import mir.storage.*;
46
47 import mircoders.storage.*;
48
49 /**
50  * this class implements mapping of one line of the database table content
51  * to a java object
52  *
53  * @version $Revision: 1.9.2.2 $ $Date: 2002/11/01 05:38:20 $
54  * @author $Author: mh $
55  *
56  * $Log: EntityContent.java,v $
57  * Revision 1.9.2.2  2002/11/01 05:38:20  mh
58  * Converted media Interface to use streams (Java IO) instead of byte buffers of
59  * the entire uplaoded files. These saves loads of unecessary memory use. JAI
60  * still consumes quite a bit though.
61  *
62  * A new temporary file (for JAI) parameter is necessary and is in the config.properties file.
63  *
64  * A nice side effect of this work is the FileHandler interface which is
65  * basically a call back mechanism for WebdbMultipartRequest which allows the
66  * uploaded file to handled by different classes. For example, for a media
67  * upload, the content-type, etc.. needs to be determined, but if say the
68  * FileEditor had a feature to upload static files... another handler wood be
69  * needed. Right now only the MediaRequest handler exists.
70  *
71  * Revision 1.9.2.1  2002/09/01 21:31:43  mh
72  * Mir goes GPL
73  *
74  * Revision 1.9  2002/07/19 20:55:49  mh
75  * commented out decodeHTML, as we don't encodeHTML anymore
76  *
77  * Revision 1.8  2002/06/28 20:37:33  mh
78  * make date_formatted be webdb_create_short instead to be more consistent. also make date2webdb.. use webdb_create
79  *
80  * 
81  */
82
83
84 public class EntityContent extends Entity
85 {
86
87   String mirconf_extLinkName  = MirConfig.getProp("Producer.ExtLinkName");
88   String mirconf_intLinkName  = MirConfig.getProp("Producer.IntLinkName");
89   String mirconf_mailLinkName = MirConfig.getProp("Producer.MailLinkName");
90   String mirconf_imageRoot    = MirConfig.getProp("Producer.ImageRoot");
91
92   //this should always be transient i.e it can never be stored in the db
93   //or ObjectStore. (so the ObjectStore should only be caching what comes
94   //directly out of the DB. @todo confirm this with rk. -mh
95   HashMap _entCache = new HashMap();
96   Boolean _hasMedia = null;
97
98         // constructors
99
100         public EntityContent()
101         {
102                 super();
103     //content_data is now filed-type "text"
104                 //streamedInput = new ArrayList();
105                 //streamedInput.add("content_data");
106         }
107
108         public EntityContent(StorageObject theStorage) {
109                 this();
110                 setStorage(theStorage);
111         }
112
113         //
114         // methods
115
116  /**
117         * set is_produced flag for the article
118         */
119
120         public void setProduced(boolean yesno) throws StorageObjectException
121         {
122                 String value = (yesno) ? "1":"0";
123                 if (value.equals( getValue("is_produced") )) return;
124
125     Connection con=null;Statement stmt=null;
126     String sql = "update content set is_produced='" + value + "' where id='" + getId()+"'";
127                 try {
128                         con = theStorageObject.getPooledCon();
129                         /** @todo should be preparedStatement: faster!! */
130                         stmt = con.createStatement();
131                         theStorageObject.executeUpdate(stmt,sql);
132                 } catch (StorageObjectException e) {
133             throwStorageObjectException(e, "\n -- set produced failed");
134                 } catch (SQLException e) {
135             throwStorageObjectException(e, "\n -- set produced failed");
136                 } finally {
137                         theStorageObject.freeConnection(con,stmt);
138                 }
139         }
140
141
142  /**
143         * make openposting to newswire
144         */
145
146         public void newswire() throws StorageObjectException
147         {
148                 String sql = "update content set to_article_type='1', is_produced='0' where id='" + getId()+"'";
149                 try {
150                                 theStorageObject.executeUpdate(sql);
151                 } catch (StorageObjectException e) {
152             throwStorageObjectException(e, "\n -- newswire failed");
153                 } catch (SQLException e) {
154             throwStorageObjectException(e, "\n -- newswire failed");
155                 }
156         }
157
158
159  /**
160         * dettach from media
161         */
162         public void dettach(String cid,String mid) throws StorageObjectException
163         {
164                 if (mid!=null){
165                         try{
166                                 DatabaseContentToMedia.getInstance().delete(cid,mid);
167                         } catch (Exception e){
168                 throwStorageObjectException(e, "\n -- failed to get instance");
169                         }
170                         //set Content to unproduced
171                         setProduced(false);
172                 }
173         }
174
175  /**
176         * attach to media
177         */
178
179         public void attach(String mid) throws StorageObjectException
180         {
181                 if (mid!=null) {
182                         //write media-id mid and content-id in table content_x_media
183                         try{
184                                 DatabaseContentToMedia.getInstance().addMedia(getId(),mid);
185                         } catch(StorageObjectException e){
186                                 throwStorageObjectException(e, "attach: could not get the instance");
187                         }
188                         //set Content to unproduced
189                         setProduced(false);
190                 }       else {
191                         theLog.printError("EntityContent: attach without mid");
192                 }
193         }
194
195         /**
196          * overridden method getValue to include formatted date into every
197          * entityContent
198          */
199
200         public String getValue(String field)
201   {
202     String returnField = null;
203     if (field!=null)
204     {
205       if (field.equals("date_formatted") || field.equals("webdb_create_short") )
206       {
207                   if (hasValueForField("date"))
208         returnField = StringUtil.webdbDate2readableDate(getValue("webdb_create"));
209                 }
210       else if (field.equals("description_parsed"))
211         returnField = getDescriptionParsed();
212       else if (field.equals("description_sentence"))
213         returnField = getDescriptionSentence();
214       else if (field.equals("content_data_parsed"))
215         returnField = getContentDataParsed();
216       else
217         return super.getValue(field);
218     }
219     return returnField;
220         }
221
222   public TemplateModel get(java.lang.String key) throws TemplateModelException
223   {
224     if (key!=null) {
225       if (_entCache.containsKey(key)) {
226         return (TemplateModel)_entCache.get(key);
227       }
228       if (key.equals("to_comments")) {
229         try {
230           _entCache.put(key, getComments());
231           return (TemplateModel)_entCache.get(key);
232         } catch (Exception ex) {
233           theLog.printWarning("-- getComments: could not fetch data " + ex.toString());
234           throw new TemplateModelException(ex.toString());
235         }
236       }
237       if (key.equals("to_media_images")) {
238         try {
239           _entCache.put(key, getImagesForContent());
240           return (TemplateModel)_entCache.get(key);
241         }
242         catch (Exception ex) {
243           theLog.printWarning("-- getImagesForContent: could not fetch data " + ex.toString());
244           throw new TemplateModelException(ex.toString());
245         }
246       }
247       if (key.equals("to_media_audio")) {
248         try {
249           _entCache.put(key, getAudioForContent());
250           return (TemplateModel)_entCache.get(key);
251         }
252         catch (Exception ex) {
253           theLog.printWarning("-- getAudioForContent: could not fetch data " + ex.toString());
254           throw new TemplateModelException(ex.toString());
255         }
256       }
257       if (key.equals("to_media_video")) {
258         try {
259           _entCache.put(key, getVideoForContent());
260           return (TemplateModel)_entCache.get(key);
261         }
262         catch (Exception ex) {
263           theLog.printWarning("-- getVideoForContent: could not fetch data " + ex.toString());
264           throw new TemplateModelException(ex.toString());
265         }
266       }
267       if (key.equals("to_media_other")) {
268         try {
269           _entCache.put(key, getOtherMediaForContent());
270           return (TemplateModel)_entCache.get(key);
271         }
272         catch (Exception ex) {
273           theLog.printWarning("-- getOtherMediaForContent: could not fetch data " + ex.toString());
274           throw new TemplateModelException(ex.toString());
275         }
276       }
277       else if (key.equals("to_media_icon")) {
278         try {
279           _entCache.put(key, getUploadedMediaForNewswire());
280           return (TemplateModel)_entCache.get(key);
281         }
282         catch (Exception ex) {
283           theLog.printWarning("-- getUploadedMediaForNewswire: could not fetch data " + ex.toString());
284           throw new TemplateModelException(ex.toString());
285         }
286       }
287       else if (key.equals("to_topics")) {
288         try {
289           _entCache.put(key, 
290                         DatabaseContentToTopics.getInstance().getTopics(this));
291           return (TemplateModel)_entCache.get(key);
292         }
293         catch (Exception ex) {
294           theLog.printWarning("-- getTopics: could not fetch data " + ex.toString());
295           throw new TemplateModelException(ex.toString());
296         }
297       }
298       else {
299         return new SimpleScalar(getValue(key));
300       }
301
302     }
303     return null;
304   }
305
306
307
308
309         /**
310          * overridden method setValues to patch creator_main_url
311          */
312         public void setValues(HashMap theStringValues) {
313                 if (theStringValues != null) {
314                         if (theStringValues.containsKey("creator_main_url")){
315                                 if (((String)theStringValues.get("creator_main_url")).equalsIgnoreCase("http://")){
316                                         theStringValues.remove("creator_main_url");
317         } else if (!((String)theStringValues.get("creator_main_url")).startsWith("http://")){
318           theStringValues.put("creator_main_url","http://"+((String)theStringValues.get("creator_main_url")));
319         }
320       }
321                 }
322                 super.setValues(theStringValues);
323         }
324
325
326   private String getContentDataParsed() {
327     String returnField = getValue("content_data");
328     if ((returnField!=null) && (returnField.length()>0) ) {
329       returnField=StringUtil.deleteForbiddenTags(returnField);
330       //create http-links and email-links
331       if (getValue("is_html").equals("0")) {
332         returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
333                                             mirconf_mailLinkName,mirconf_extLinkName,
334                                             mirconf_intLinkName);
335       }
336       // commented this out as I don't think it necessary as we don't
337       // "encodeHTML" in the first place anymore.. -mh 2002.07.19
338       //returnField = StringUtil.decodeHTMLinTags(returnField);
339     }
340     return returnField;
341   }
342
343   private String getDescriptionSentence() {
344     String returnField = getValue("description");
345     if (returnField != null && returnField.length()>0) {
346        returnField = StringUtil.removeHTMLTags(returnField);
347        int endOfFirstSentence=StringUtil.findEndOfSentence(returnField,0);
348        if (endOfFirstSentence > 0){
349          returnField = returnField.substring(0,endOfFirstSentence);
350        }
351     }
352     return returnField;
353   }
354
355   private String getDescriptionParsed() {
356     String returnField = getValue("description");
357     if (returnField != null && returnField.length()>0) {
358       returnField = StringUtil.deleteForbiddenTags(returnField);
359       if (getValue("is_html").equals("0")) {
360         returnField = StringUtil.createHTML(returnField,mirconf_imageRoot,
361                                             mirconf_mailLinkName,mirconf_extLinkName,
362                                             mirconf_intLinkName);
363       }
364       returnField = StringUtil.decodeHTMLinTags(returnField);
365     }
366     return returnField;
367   }
368
369         /**
370          * fetches all the comments belonging to an article
371          *
372          * @return freemarker.template.SimpleList
373          */
374         private EntityList getComments() throws StorageObjectException {
375                 return ((DatabaseContent)theStorageObject).getComments(this);
376         }
377
378   // @todo this needs to optimized. expensive SQL
379   private SimpleHash getUploadedMediaForNewswire()
380     throws StorageObjectException, TemplateModelException
381   {
382     // fetching/setting the images
383     // return to_media_icons
384     String        tinyIcon = null, iconAlt = null;
385     MirMedia      mediaHandler = null;
386     EntityUploadedMedia uploadedMedia;
387     Entity        mediaType;
388     SimpleHash    returnHash = new SimpleHash();
389
390     EntityList upMediaEntityList =
391                     DatabaseContentToMedia.getInstance().getUploadedMedia(this);
392     if (upMediaEntityList!=null && upMediaEntityList.getCount()>=1) {
393
394       for (int n=0; n < upMediaEntityList.size();n++) {
395         uploadedMedia = (EntityUploadedMedia)upMediaEntityList.elementAt(n);
396         mediaType = uploadedMedia.getMediaType();
397         try {
398           mediaHandler = MediaHelper.getHandler( mediaType );
399         } catch (MirMediaException ex) {
400           throw new TemplateModelException(ex.toString());
401         }
402         //the "best" media type to show
403         if (mediaHandler.isVideo()) {
404           tinyIcon = MirConfig.getProp("Producer.Icon.TinyVideo");
405           iconAlt = "Video";
406           break;
407         } else if (mediaHandler.isAudio()) {
408           tinyIcon = MirConfig.getProp("Producer.Icon.TinyAudio");
409           iconAlt = "Audio";
410         } else if (tinyIcon == null && !mediaHandler.isImage()) {
411           tinyIcon = mediaHandler.getTinyIconName();
412           iconAlt = mediaHandler.getIconAltName();
413         }
414
415       }
416       //it only has image(s)
417       if (tinyIcon == null) {
418         tinyIcon = MirConfig.getProp("Producer.Icon.TinyImage");
419         iconAlt = "Image";
420       }
421     // uploadedMedia Entity list is empty.
422     // we only have text
423     } else {
424       tinyIcon = MirConfig.getProp("Producer.Icon.TinyText");
425       iconAlt = "Text";
426     }
427     returnHash.put("tiny_icon", mirconf_imageRoot+"/"+tinyIcon);
428     returnHash.put("icon_alt", iconAlt);
429     return returnHash;
430   }
431
432   private boolean hasMedia() throws StorageObjectException
433   {
434     if (_hasMedia == null) {
435       _hasMedia =
436         new Boolean(DatabaseContentToMedia.getInstance().hasMedia(this));
437     }
438     return _hasMedia.booleanValue();
439   }
440
441   //######## @todo all of the following getBlahForContent should have
442   // and optimized version where LIMIT=1 sql for list view.
443   private EntityList getImagesForContent()
444     throws StorageObjectException, TemplateModelException
445   {
446     if (hasMedia())
447       return DatabaseContentToMedia.getInstance().getImages(this);
448     else
449       return null;
450   }
451
452   private EntityList getAudioForContent()
453     throws StorageObjectException, TemplateModelException
454   {
455     if (hasMedia())
456       return DatabaseContentToMedia.getInstance().getAudio(this) ;
457     else
458       return null;
459   }
460
461   private EntityList getVideoForContent()
462     throws StorageObjectException, TemplateModelException
463   {
464     if (hasMedia())
465       return DatabaseContentToMedia.getInstance().getVideo(this) ;
466     else
467       return null;
468   }
469
470   private EntityList getOtherMediaForContent()
471     throws StorageObjectException, TemplateModelException
472   {
473     if (hasMedia())
474       return DatabaseContentToMedia.getInstance().getOther(this);
475     else
476       return null;
477   }
478
479 }