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