Some small things like, reorganizing imports, accessing static variables
[mir.git] / source / mircoders / media / MediaRequest.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.media;
33
34 import java.util.GregorianCalendar;
35 import java.util.HashMap;
36 import java.util.Iterator;
37
38 import javax.servlet.ServletContext;
39
40 import com.oreilly.servlet.multipart.FilePart;
41
42 import mir.log.LoggerWrapper;
43 import mir.config.MirPropertiesConfiguration;
44 import mir.entity.Entity;
45 import mir.entity.EntityList;
46 import mir.media.MediaHelper;
47 import mir.media.MirMedia;
48 import mir.media.MirMediaException;
49 import mir.misc.FileHandler;
50 import mir.misc.FileHandlerException;
51 import mir.misc.FileHandlerUserException;
52 import mir.misc.StringUtil;
53 import mir.storage.Database;
54 import mir.storage.StorageObjectExc;
55 import mir.storage.StorageObjectFailure;
56
57 import mircoders.storage.DatabaseMediaType;
58
59
60 /*
61  *  MediaRequest.java -
62  *    Takes an HTTPServletRequest from a mutltipart form and finds the files
63  *    uploaded via the com.oreilly.servlet.multipart package. Finally the
64  *    appropriate media objects are set.
65  *
66  * @author mh
67  * @version $Id: MediaRequest.java,v 1.14 2003/02/28 18:27:08 idfx Exp $
68  *
69  */
70
71 public class MediaRequest implements FileHandler
72 {
73   private String _user;
74   private EntityList _returnList = new EntityList();
75   private boolean _publish;
76   private LoggerWrapper logger;
77
78   public MediaRequest(String user, boolean publish) {
79     _user = user;
80     _publish = publish;
81     logger = new LoggerWrapper("Media.Request");
82   }
83
84   public EntityList getEntityList() {
85     return _returnList;
86   }
87
88   /*
89    * parses the files in the uploaded media and creates media Entity's out of
90    * them.  Produces them if the "produce" argument is true. The "publish"
91    * parameter determines if it should publish per default in the case where no
92    * is_published parameter (from the upload form) is supplied. (for backwards
93    * compatibility.)
94    */
95   public void setFile(FilePart filePart, int fileNum, HashMap mediaValues)
96     throws FileHandlerException, FileHandlerUserException {
97
98     String mediaId=null;
99     MirMedia mediaHandler;
100     Database mediaStorage = null;
101
102     try {
103       String fileName = filePart.getFileName();
104
105       //get the content-type from what the client browser
106       //sends us. (the "Oreilly method")
107       String contentType = filePart.getContentType();
108
109       //theLog.printInfo("FROM BROWSER: "+contentType);
110
111       //if the client browser sent us unknown (text/plain is default)
112       //or if we got application/octet-stream, it's possible that
113       //the browser is in error, better check against the file extension
114       if (contentType.equals("text/plain") ||
115           contentType.equals("application/octet-stream")) {
116         /**
117          * Fallback to finding the mime-type through the standard ServletApi
118          * ServletContext getMimeType() method.
119          *
120          * This is a way to get the content-type via the .extension,
121          * we could maybe use a magic method as an additional method of
122          * figuring out the content-type, by looking at the header (first
123          * few bytes) of the file. (like the file(1) command). We could
124          * also call the "file" command through Runtime. This is an
125          * option that I almost prefer as it is already implemented and
126          * exists with an up-to-date map on most modern Unix like systems.
127          * I haven't found a really nice implementation of the magic method
128          * in pure java yet.
129          *
130          * The first method we try thought is the "Oreilly method". It
131          * relies on the content-type that the client browser sends and
132          * that sometimes is application-octet stream with
133          * broken/mis-configured browsers.
134          *
135          * The map file we use for the extensions is the standard web-app
136          * deployment descriptor file (web.xml). See Mir's web.xml or see
137          * your Servlet containers (most likely Tomcat) documentation.
138          * So if you support a new media type you have to make sure that
139          * it is in this file -mh
140          */
141         ServletContext ctx = MirPropertiesConfiguration.getContext();
142         contentType = ctx.getMimeType(fileName);
143         if (contentType==null)
144           contentType = "text/plain"; // rfc1867 says this is the default
145       }
146       //theLog.printInfo("CONTENT TYPE IS: "+contentType);
147
148       if (contentType.equals("text/plain") ||
149           contentType.equals("application/octet-stream")) {
150         _throwBadContentType(fileName, contentType);
151       }
152
153       // call the routines that escape html
154       for (Iterator i=mediaValues.keySet().iterator(); i.hasNext(); ){
155         String k=(String)i.next();
156         String v=(String)mediaValues.get(k);
157
158         if (k.equals("description")) {
159           String tmp = StringUtil.deleteForbiddenTags(v);
160           mediaValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
161         } else {
162           //we don't want people fucking with the author/title, etc..
163           mediaValues.put(k,StringUtil.removeHTMLTags(v));
164         }
165
166       }
167
168       String mediaTitle = (String)mediaValues.get("media_title"+fileNum);
169       if ( (mediaTitle == null) || (mediaTitle.length() == 0)) {
170         //  uncomment the next line and comment out the exception throw
171         //  if you'd rather just assign missing media titles automatically
172         //  mediaTitle="media item "+fileNum;
173         throw new FileHandlerUserException("Missing field: media title "+mediaTitle+fileNum);
174       }
175
176       // TODO: need to add all the extra fields that can be present in the
177       // admin upload form. -mh
178       mediaValues.put("title", mediaTitle);
179       mediaValues.put("date", StringUtil.date2webdbDate(
180                                                     new GregorianCalendar()));
181       mediaValues.put("to_publisher", _user);
182       //mediaValues.put("to_media_folder", "7"); // op media_folder
183       mediaValues.put("is_produced", "0");
184
185       // icky backwards compatibility code -mh
186       if (_publish == true) {
187         mediaValues.put("is_published", "1");
188       } else {
189         if (!mediaValues.containsKey("is_published"))
190           mediaValues.put("is_published", "0");
191       }
192
193       // @todo this should probably be moved to DatabaseMediaType -mh
194       String[] cTypeSplit = StringUtil.split(contentType, "/");
195       String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
196
197       DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
198       EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
199
200       String mediaTypeId = null;
201
202       //if we didn't find an entry matching the
203       //content-type int the table.
204       if (mediaTypesList.size() == 0) {
205        _throwBadContentType(fileName, contentType);
206       }
207
208       Entity mediaType = null;
209       Entity mediaType2 = null;
210
211       // find out if we an exact content-type match if so take it.
212       // otherwise try to match majortype/*
213       // @todo this should probably be moved to DatabaseMediaType -mh
214       for(int j=0;j<mediaTypesList.size();j++) {
215         if(contentType.equals(
216               mediaTypesList.elementAt(j).getValue("mime_type")))
217           mediaType = mediaTypesList.elementAt(j);
218         else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
219                   cTypeSplit[0]+"/*") )
220           mediaType2= mediaTypesList.elementAt(j);
221       }
222
223       if ( (mediaType == null) && (mediaType2 == null) ) {
224         _throwBadContentType(fileName, contentType);
225       } else if( (mediaType == null) && (mediaType2 != null) ) {
226         mediaType = mediaType2;
227       }
228
229       //get the class names from the media_type table.
230       mediaTypeId = mediaType.getId();
231       // ############### @todo: merge these and the getURL call into one
232       // getURL helper call that just takes the Entity as a parameter
233       // along with media_type
234       try {
235         mediaHandler = MediaHelper.getHandler(mediaType);
236         mediaStorage = MediaHelper.getStorage(mediaType,
237                                             "mircoders.storage.Database");
238       }
239       catch (MirMediaException e) {
240         throw new FileHandlerException (e.getMessage());
241       }
242       mediaValues.put("to_media_type",mediaTypeId);
243
244       //load the classes via reflection
245       String MediaId;
246       Entity mediaEnt = null;
247       try {
248         mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
249       }
250       catch (Exception e) {
251         throw new FileHandlerException("Error in MediaRequest: "+e.toString());
252       }
253
254       mediaEnt.setStorage(mediaStorage);
255       mediaEnt.setValues(mediaValues);
256       mediaId = mediaEnt.insert();
257
258       //save and store the media data/metadata
259       try {
260         mediaHandler.set(filePart.getInputStream(), mediaEnt, mediaType);
261       }
262       catch (MirMediaException e) {
263         throw new FileHandlerException(e.getMessage());
264       }
265
266       _returnList.add(mediaEnt);
267     }
268     catch (StorageObjectFailure e) {
269       // first try to delete it.. don't catch exception as we've already..
270       try {
271         mediaStorage.delete(mediaId);
272       }
273       catch (Exception e2) {
274       }
275       throw new FileHandlerException("error in MediaRequest: "+e.toString());
276     }
277     catch (StorageObjectExc e) {
278       throw new FileHandlerException("error in MediaRequest: "+e.toString());
279     } //end try/catch block
280
281   } // method setFile()
282
283   private void _throwBadContentType (String fileName, String contentType)
284     throws FileHandlerUserException {
285
286     //theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
287       //                    +contentType);
288     throw new FileHandlerUserException("The file you uploaded is of the "
289         +"following mime-type: "+contentType
290         +", we do not support this mime-type. "
291         +"Error One or more files of unrecognized type. Sorry");
292   }
293
294 }
295