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