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.storage.Database;
54 import mir.storage.StorageObjectExc;
55 import mir.storage.StorageObjectFailure;
57 import mircoders.storage.DatabaseMediaType;
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.
67 * @version $Id: MediaRequest.java,v 1.14 2003/02/28 18:27:08 idfx Exp $
71 public class MediaRequest implements FileHandler
74 private EntityList _returnList = new EntityList();
75 private boolean _publish;
76 private LoggerWrapper logger;
78 public MediaRequest(String user, boolean publish) {
81 logger = new LoggerWrapper("Media.Request");
84 public EntityList getEntityList() {
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
95 public void setFile(FilePart filePart, int fileNum, HashMap mediaValues)
96 throws FileHandlerException, FileHandlerUserException {
99 MirMedia mediaHandler;
100 Database mediaStorage = null;
103 String fileName = filePart.getFileName();
105 //get the content-type from what the client browser
106 //sends us. (the "Oreilly method")
107 String contentType = filePart.getContentType();
109 //theLog.printInfo("FROM BROWSER: "+contentType);
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")) {
117 * Fallback to finding the mime-type through the standard ServletApi
118 * ServletContext getMimeType() method.
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
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.
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
141 ServletContext ctx = MirPropertiesConfiguration.getContext();
142 contentType = ctx.getMimeType(fileName);
143 if (contentType==null)
144 contentType = "text/plain"; // rfc1867 says this is the default
146 //theLog.printInfo("CONTENT TYPE IS: "+contentType);
148 if (contentType.equals("text/plain") ||
149 contentType.equals("application/octet-stream")) {
150 _throwBadContentType(fileName, contentType);
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);
158 if (k.equals("description")) {
159 String tmp = StringUtil.deleteForbiddenTags(v);
160 mediaValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
162 //we don't want people fucking with the author/title, etc..
163 mediaValues.put(k,StringUtil.removeHTMLTags(v));
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);
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");
185 // icky backwards compatibility code -mh
186 if (_publish == true) {
187 mediaValues.put("is_published", "1");
189 if (!mediaValues.containsKey("is_published"))
190 mediaValues.put("is_published", "0");
193 // @todo this should probably be moved to DatabaseMediaType -mh
194 String[] cTypeSplit = StringUtil.split(contentType, "/");
195 String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
197 DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
198 EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
200 String mediaTypeId = null;
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);
208 Entity mediaType = null;
209 Entity mediaType2 = null;
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);
223 if ( (mediaType == null) && (mediaType2 == null) ) {
224 _throwBadContentType(fileName, contentType);
225 } else if( (mediaType == null) && (mediaType2 != null) ) {
226 mediaType = mediaType2;
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
235 mediaHandler = MediaHelper.getHandler(mediaType);
236 mediaStorage = MediaHelper.getStorage(mediaType,
237 "mircoders.storage.Database");
239 catch (MirMediaException e) {
240 throw new FileHandlerException (e.getMessage());
242 mediaValues.put("to_media_type",mediaTypeId);
244 //load the classes via reflection
246 Entity mediaEnt = null;
248 mediaEnt = (Entity)mediaStorage.getEntityClass().newInstance();
250 catch (Exception e) {
251 throw new FileHandlerException("Error in MediaRequest: "+e.toString());
254 mediaEnt.setStorage(mediaStorage);
255 mediaEnt.setValues(mediaValues);
256 mediaId = mediaEnt.insert();
258 //save and store the media data/metadata
260 mediaHandler.set(filePart.getInputStream(), mediaEnt, mediaType);
262 catch (MirMediaException e) {
263 throw new FileHandlerException(e.getMessage());
266 _returnList.add(mediaEnt);
268 catch (StorageObjectFailure e) {
269 // first try to delete it.. don't catch exception as we've already..
271 mediaStorage.delete(mediaId);
273 catch (Exception e2) {
275 throw new FileHandlerException("error in MediaRequest: "+e.toString());
277 catch (StorageObjectExc e) {
278 throw new FileHandlerException("error in MediaRequest: "+e.toString());
279 } //end try/catch block
281 } // method setFile()
283 private void _throwBadContentType (String fileName, String contentType)
284 throws FileHandlerUserException {
286 //theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
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");