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