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