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.Iterator;
38 import javax.servlet.ServletContext;
40 import mir.config.MirPropertiesConfiguration;
41 import mir.entity.Entity;
42 import mir.entity.EntityList;
43 import mir.log.LoggerWrapper;
44 import mir.media.MediaHelper;
45 import mir.media.MirMedia;
46 import mir.media.MirMediaException;
47 import mir.misc.FileHandler;
48 import mir.misc.FileHandlerException;
49 import mir.misc.FileHandlerUserException;
50 import mir.misc.StringUtil;
51 import mir.storage.Database;
52 import mir.storage.StorageObjectExc;
53 import mir.storage.StorageObjectFailure;
54 import mircoders.storage.DatabaseMediaType;
56 import com.oreilly.servlet.multipart.FilePart;
61 * Takes an HTTPServletRequest from a mutltipart form and finds the files
62 * uploaded via the com.oreilly.servlet.multipart package. Finally the
63 * appropriate media objects are set.
66 * @version $Id: MediaRequest.java,v 1.16 2003/03/05 19:23:16 idfx Exp $
70 public class MediaRequest implements FileHandler
73 private EntityList _returnList = new EntityList();
74 private boolean _publish;
75 private LoggerWrapper logger;
77 public MediaRequest(String user, boolean publish) {
80 logger = new LoggerWrapper("Media.Request");
83 public EntityList getEntityList() {
88 * parses the files in the uploaded media and creates media Entity's out of
89 * them. Produces them if the "produce" argument is true. The "publish"
90 * parameter determines if it should publish per default in the case where no
91 * is_published parameter (from the upload form) is supplied. (for backwards
94 public void setFile(FilePart filePart, int fileNum, Map mediaValues)
95 throws FileHandlerException, FileHandlerUserException {
98 MirMedia mediaHandler;
99 Database mediaStorage = null;
102 String fileName = filePart.getFileName();
104 //get the content-type from what the client browser
105 //sends us. (the "Oreilly method")
106 String contentType = filePart.getContentType();
108 //theLog.printInfo("FROM BROWSER: "+contentType);
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")) {
116 * Fallback to finding the mime-type through the standard ServletApi
117 * ServletContext getMimeType() method.
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
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.
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
140 ServletContext ctx = MirPropertiesConfiguration.getContext();
141 contentType = ctx.getMimeType(fileName);
142 if (contentType==null)
143 contentType = "text/plain"; // rfc1867 says this is the default
145 //theLog.printInfo("CONTENT TYPE IS: "+contentType);
147 if (contentType.equals("text/plain") ||
148 contentType.equals("application/octet-stream")) {
149 _throwBadContentType(fileName, contentType);
152 // call the routines that escape html
153 for (Iterator i=mediaValues.keySet().iterator(); i.hasNext(); ){
154 String k=(String)i.next();
155 String v=(String)mediaValues.get(k);
157 if (k.equals("description")) {
158 String tmp = StringUtil.deleteForbiddenTags(v);
159 mediaValues.put(k,StringUtil.deleteHTMLTableTags(tmp));
161 //we don't want people fucking with the author/title, etc..
162 mediaValues.put(k,StringUtil.removeHTMLTags(v));
167 String mediaTitle = (String)mediaValues.get("media_title"+fileNum);
168 if ( (mediaTitle == null) || (mediaTitle.length() == 0)) {
169 // uncomment the next line and comment out the exception throw
170 // if you'd rather just assign missing media titles automatically
171 // mediaTitle="media item "+fileNum;
172 throw new FileHandlerUserException("Missing field: media title "+mediaTitle+fileNum);
175 // TODO: need to add all the extra fields that can be present in the
176 // admin upload form. -mh
177 mediaValues.put("title", mediaTitle);
178 mediaValues.put("date", StringUtil.date2webdbDate(
179 new GregorianCalendar()));
180 mediaValues.put("to_publisher", _user);
181 //mediaValues.put("to_media_folder", "7"); // op media_folder
182 mediaValues.put("is_produced", "0");
184 // icky backwards compatibility code -mh
185 if (_publish == true) {
186 mediaValues.put("is_published", "1");
188 if (!mediaValues.containsKey("is_published"))
189 mediaValues.put("is_published", "0");
192 // @todo this should probably be moved to DatabaseMediaType -mh
193 String[] cTypeSplit = StringUtil.split(contentType, "/");
194 String wc = " mime_type LIKE '"+cTypeSplit[0]+"%'";
196 DatabaseMediaType mediaTypeStor = DatabaseMediaType.getInstance();
197 EntityList mediaTypesList = mediaTypeStor.selectByWhereClause(wc);
199 String mediaTypeId = null;
201 //if we didn't find an entry matching the
202 //content-type int the table.
203 if (mediaTypesList.size() == 0) {
204 _throwBadContentType(fileName, contentType);
207 Entity mediaType = null;
208 Entity mediaType2 = null;
210 // find out if we an exact content-type match if so take it.
211 // otherwise try to match majortype/*
212 // @todo this should probably be moved to DatabaseMediaType -mh
213 for(int j=0;j<mediaTypesList.size();j++) {
214 if(contentType.equals(
215 mediaTypesList.elementAt(j).getValue("mime_type")))
216 mediaType = mediaTypesList.elementAt(j);
217 else if ((mediaTypesList.elementAt(j).getValue("mime_type")).equals(
218 cTypeSplit[0]+"/*") )
219 mediaType2= mediaTypesList.elementAt(j);
222 if ( (mediaType == null) && (mediaType2 == null) ) {
223 _throwBadContentType(fileName, contentType);
224 } else if( (mediaType == null) && (mediaType2 != null) ) {
225 mediaType = mediaType2;
228 //get the class names from the media_type table.
229 mediaTypeId = mediaType.getId();
230 // ############### @todo: merge these and the getURL call into one
231 // getURL helper call that just takes the Entity as a parameter
232 // along with media_type
234 mediaHandler = MediaHelper.getHandler(mediaType);
235 mediaStorage = MediaHelper.getStorage(mediaType,
236 "mircoders.storage.Database");
238 catch (MirMediaException e) {
239 throw new FileHandlerException (e.getMessage());
241 mediaValues.put("to_media_type",mediaTypeId);
243 //load the classes via reflection
245 Entity mediaEnt = null;
247 mediaEnt = (Entity)mediaStorage.getEntityClass().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();
257 //save and store the media data/metadata
259 mediaHandler.set(filePart.getInputStream(), mediaEnt, mediaType);
261 catch (MirMediaException e) {
262 throw new FileHandlerException(e.getMessage());
265 _returnList.add(mediaEnt);
267 catch (StorageObjectFailure e) {
268 // first try to delete it.. don't catch exception as we've already..
270 mediaStorage.delete(mediaId);
272 catch (Exception e2) {
274 throw new FileHandlerException("error in MediaRequest: "+e.toString());
276 catch (StorageObjectExc e) {
277 throw new FileHandlerException("error in MediaRequest: "+e.toString());
278 } //end try/catch block
280 } // method setFile()
282 private void _throwBadContentType (String fileName, String contentType)
283 throws FileHandlerUserException {
285 //theLog.printDebugInfo("Wrong file type uploaded!: " + fileName+" "
287 throw new FileHandlerUserException("The file you uploaded is of the "
288 +"following mime-type: "+contentType
289 +", we do not support this mime-type. "
290 +"Error One or more files of unrecognized type. Sorry");