2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
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.
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.
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
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.
32 package mircoders.media;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.ServletContext;
40 import com.oreilly.servlet.multipart.FilePart;
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;
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.
57 * @author $Author: mh $
58 * @version $Revision: 1.1.2.2 $
60 * $Log: MediaRequest.java,v $
61 * Revision 1.1.2.2 2002/11/01 05:38:21 mh
62 * Converted media Interface to use streams (Java IO) instead of byte buffers of
63 * the entire uplaoded files. These saves loads of unecessary memory use. JAI
64 * still consumes quite a bit though.
66 * A new temporary file (for JAI) parameter is necessary and is in the config.properties file.
68 * A nice side effect of this work is the FileHandler interface which is
69 * basically a call back mechanism for WebdbMultipartRequest which allows the
70 * uploaded file to handled by different classes. For example, for a media
71 * upload, the content-type, etc.. needs to be determined, but if say the
72 * FileEditor had a feature to upload static files... another handler wood be
73 * needed. Right now only the MediaRequest handler exists.
75 * Revision 1.1.2.1 2002/09/01 21:31:43 mh
78 * Revision 1.1 2002/07/21 22:38:39 mh
79 * parses a multipart request's files and makes media Entity's out of them. Basically the old code from insposting() in ServletModuleOpenIndy
84 public class MediaRequest implements FileHandler
88 EntityList _returnList = new EntityList();
89 boolean _produce, _publish;
91 public MediaRequest(String user, boolean produce, boolean publish) {
97 public EntityList getEntityList() {
102 * parses the files in the uploaded media and creates media Entity's out of
103 * them. Produces them if the "produce" argument is true. The "publish"
104 * parameter determines if it should publish per default in the case where no
105 * is_published parameter (from the upload form) is supplied. (for backwards
108 public void setFile(FilePart filePart, int fileNum, HashMap mediaValues)
109 throws FileHandlerException, FileHandlerUserException {
112 MirMedia mediaHandler;
113 Database mediaStorage = null;
114 ProducerMedia mediaProducer = null;
117 String fileName = filePart.getFileName();
119 //get the content-type from what the client browser
120 //sends us. (the "Oreilly method")
121 String contentType = filePart.getContentType();
123 //theLog.printInfo("FROM BROWSER: "+contentType);
125 //if the client browser sent us unknown (text/plain is default)
126 //or if we got application/octet-stream, it's possible that
127 //the browser is in error, better check against the file extension
128 if (contentType.equals("text/plain") ||
129 contentType.equals("application/octet-stream")) {
131 * Fallback to finding the mime-type through the standard ServletApi
132 * ServletContext getMimeType() method.
134 * This is a way to get the content-type via the .extension,
135 * we could maybe use a magic method as an additional method of
136 * figuring out the content-type, by looking at the header (first
137 * few bytes) of the file. (like the file(1) command). We could
138 * also call the "file" command through Runtime. This is an
139 * option that I almost prefer as it is already implemented and
140 * exists with an up-to-date map on most modern Unix like systems.
141 * I haven't found a really nice implementation of the magic method
144 * The first method we try thought is the "Oreilly method". It
145 * relies on the content-type that the client browser sends and
146 * that sometimes is application-octet stream with
147 * broken/mis-configured browsers.
149 * The map file we use for the extensions is the standard web-app
150 * deployment descriptor file (web.xml). See Mir's web.xml or see
151 * your Servlet containers (most likely Tomcat) documentation.
152 * So if you support a new media type you have to make sure that
153 * it is in this file -mh
156 (ServletContext)MirConfig.getPropAsObject("ServletContext");
157 contentType = ctx.getMimeType(fileName);
158 if (contentType==null)
159 contentType = "text/plain"; // rfc1867 says this is the default
161 //theLog.printInfo("CONTENT TYPE IS: "+contentType);
163 if (contentType.equals("text/plain") ||
164 contentType.equals("application/octet-stream")) {
165 _throwBadContentType(fileName, contentType);
168 String mediaTitle = (String)mediaValues.get("media_title"+fileNum);
169 if ( (mediaTitle == null) || (mediaTitle.length() == 0))
170 throw new FileHandlerUserException("Missing field: media title "+mediaTitle+fileNum);
172 // TODO: need to add all the extra fields that can be present in the
173 // admin upload form. -mh
174 mediaValues.put("title", mediaTitle);
175 mediaValues.put("date", StringUtil.date2webdbDate(
176 new GregorianCalendar()));
177 mediaValues.put("to_publisher", _user);
178 //mediaValues.put("to_media_folder", "7"); // op media_folder
179 mediaValues.put("is_produced", "0");
181 // icky backwards compatibility code -mh
182 if (_publish == true) {
183 mediaValues.put("is_published", "1");
185 if (!mediaValues.containsKey("is_published"))
186 mediaValues.put("is_published", "0");
189 // @todo this should probably be moved to DatabaseMediaType -mh
190 String[] cTypeSplit = StringUtil.split(contentType, "/");
191 String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
193 DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
194 EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
196 String mediaTypeId = null;
198 //if we didn't find an entry matching the
199 //content-type int the table.
200 if (mediaTypesList.size() == 0) {
201 _throwBadContentType(fileName, contentType);
204 Entity mediaType = null;
205 Entity mediaType2 = null;
207 // find out if we an exact content-type match if so take it.
208 // otherwise try to match majortype/*
209 // @todo this should probably be moved to DatabaseMediaType -mh
210 for(int j=0;j<mediaTypesList.size();j++) {
211 if(contentType.equals(
212 mediaTypesList.elementAt(j).getValue("mime_type")))
213 mediaType = mediaTypesList.elementAt(j);
214 else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
215 cTypeSplit[0]+"/*") )
216 mediaType2= mediaTypesList.elementAt(j);
219 if ( (mediaType == null) && (mediaType2 == null) ) {
220 _throwBadContentType(fileName, contentType);
221 } else if( (mediaType == null) && (mediaType2 != null) ) {
222 mediaType = mediaType2;
225 //get the class names from the media_type table.
226 mediaTypeId = mediaType.getId();
227 // ############### @todo: merge these and the getURL call into one
228 // getURL helper call that just takes the Entity as a parameter
229 // along with media_type
231 mediaHandler = MediaHelper.getHandler(mediaType);
232 mediaStorage = MediaHelper.getStorage(mediaType,
233 "mircoders.storage.Database");
234 } catch (MirMediaException e) {
235 throw new FileHandlerException (e.getMsg());
237 mediaValues.put("to_media_type",mediaTypeId);
239 //load the classes via reflection
241 Entity mediaEnt = null;
243 mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
244 if (_produce == true) {
245 Class prodCls = Class.forName("mircoders.producer.Producer"+
246 mediaType.getValue("tablename"));
247 mediaProducer = (ProducerMedia)prodCls.newInstance();
249 } catch (Exception e) {
250 throw new FileHandlerException("Error in MediaRequest: "+e.toString());
253 mediaEnt.setStorage(mediaStorage);
254 mediaEnt.setValues(mediaValues);
255 mediaId = mediaEnt.insert();
259 // f = new File("/tmp/img.jpg");
260 // File dir = new File(f.getParent());
263 // FileOutputStream out = new FileOutputStream(f);
264 // System.out.println("WRITE");
265 // filePart.writeTo(out);
267 //} catch (Exception e) {System.out.println("EE "+e.toString());}
270 //mir.misc.FileUtil.write("/tmp/img.jpg", filePart.getInputStream());
271 //save and store the media data/metadata
273 mediaHandler.set(filePart.getInputStream(), mediaEnt, mediaType);
274 } catch (MirMediaException e) {
275 throw new FileHandlerException(e.getMsg());
278 if (_produce == true )
279 mediaProducer.handle(null, null, false, false, mediaId);
280 } catch (ModuleException e) {
281 // first try to delete it.. don't catch exception as we've already..
282 try { mediaStorage.delete(mediaId); } catch (Exception e2) {}
283 throw new FileHandlerException("error in MediaRequest: "+e.toString());
286 _returnList.add(mediaEnt);
287 } catch (StorageObjectException e) {
288 // first try to delete it.. don't catch exception as we've already..
289 try { mediaStorage.delete(mediaId); } catch (Exception e2) {}
290 throw new FileHandlerException("error in MediaRequest: "+e.toString());
291 } //end try/catch block
293 } // method setFile()
295 private void _throwBadContentType (String fileName, String contentType)
296 throws FileHandlerUserException {
298 //theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
300 throw new FileHandlerUserException("The file you uploaded is of the "
301 +"following mime-type: "+contentType
302 +", we do not support this mime-type. "
303 +"Error One or more files of unrecognized type. Sorry");