KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > bridge > jsp > taglib > util > MultiPart


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.bridge.jsp.taglib.util;
11
12 import java.util.*;
13 import javax.servlet.jsp.PageContext JavaDoc;
14 import javax.servlet.jsp.JspTagException JavaDoc;
15 import javax.servlet.http.*;
16 import org.mmbase.bridge.jsp.taglib.TaglibException;
17 import org.mmbase.util.logging.Logger;
18 import org.mmbase.util.logging.Logging;
19 import org.apache.commons.fileupload.*;
20
21 /**
22  * Taglib needs to read Multipart request sometimes. Functionallity is centralized here.
23  * @author Michiel Meeuwissen
24  * @version $Id: MultiPart.java,v 1.18 2006/03/28 20:32:40 michiel Exp $
25  **/

26
27 public class MultiPart {
28     private static final Logger log = Logging.getLoggerInstance(MultiPart.class);
29
30     static String JavaDoc MULTIPARTREQUEST_KEY = "__multipart";
31
32     public static boolean isMultipart(PageContext JavaDoc pageContext) {
33         String JavaDoc ct = ((HttpServletRequest)pageContext.getRequest()).getContentType();
34         if (ct == null) {
35             return false;
36         }
37         return (ct.startsWith("multipart/"));
38     }
39
40     public static MMultipartRequest getMultipartRequest(PageContext JavaDoc pageContext) {
41         MMultipartRequest multipartRequest = (MMultipartRequest)pageContext.getAttribute(MULTIPARTREQUEST_KEY, PageContext.REQUEST_SCOPE);
42         if (multipartRequest == null) {
43             log.debug("Creating new MultipartRequest");
44             multipartRequest = new MMultipartRequest((HttpServletRequest)pageContext.getRequest(), ContextContainer.getDefaultCharacterEncoding(pageContext));
45             log.debug("have it");
46
47             if (log.isDebugEnabled()) {
48                 if (multipartRequest != null) {
49                     Iterator paramNames = multipartRequest.getParameterNames();
50                     StringBuffer JavaDoc params = new StringBuffer JavaDoc();
51                     while (paramNames.hasNext()) {
52                         params.append(paramNames.next()).append(",");
53                     }
54                     log.debug("multipart parameters: " + params);
55                 } else {
56                     log.debug("not a multipart request");
57                 }
58             }
59             pageContext.setAttribute(MULTIPARTREQUEST_KEY, multipartRequest, PageContext.REQUEST_SCOPE);
60         } else {
61             log.debug("Found multipart request on pageContext" + multipartRequest);
62         }
63         return multipartRequest;
64     }
65
66     static public class MMultipartRequest {
67
68         private Map parametersMap = new HashMap();
69         private String JavaDoc coding = null;
70
71         MMultipartRequest(HttpServletRequest req, String JavaDoc c) {
72             try {
73                 DiskFileUpload fu = new DiskFileUpload();
74                 fu.setHeaderEncoding("ISO-8859-1"); // if incorrect, it will be fixed later.
75
List fileItems = fu.parseRequest(req);
76                 for (Iterator i = fileItems.iterator(); i.hasNext(); ) {
77                     FileItem fi = (FileItem)i.next();
78                     if (fi.isFormField()) {
79                         String JavaDoc value;
80                         try {
81                             value = fi.getString("ISO-8859-1");
82                         } catch(java.io.UnsupportedEncodingException JavaDoc uee) {
83                             log.error("could not happen, ISO-8859-1 is supported");
84                             value = fi.getString();
85                         }
86                         Object JavaDoc oldValue = parametersMap.get(fi.getFieldName());
87                         if (oldValue == null ) {
88                             parametersMap.put(fi.getFieldName(), value);
89                         } else if (!(oldValue instanceof FileItem)) {
90                             List values;
91                             if (oldValue instanceof String JavaDoc) {
92                                 values = new ArrayList();
93                                 values.add(oldValue);
94                             } else {
95                                 values = (List)oldValue;
96                             }
97                             values.add(value);
98                             parametersMap.put(fi.getFieldName(), values);
99                         }
100                     } else {
101                         parametersMap.put(fi.getFieldName(), fi);
102                     }
103                 }
104             } catch (FileUploadException e) {
105                 log.error(e.getMessage(), e);
106                 throw new RuntimeException JavaDoc(e);
107             }
108             coding = c;
109             log.debug("Created with encoding: " + coding);
110         }
111
112         /**
113          * Method to retrieve the bytes of an uploaded file.
114          * @param param The name of the parameter
115          * @return <code>null</code> if parameter not found, otherwise the bytes from the parameter
116          */

117         public byte[] getBytes(String JavaDoc param) throws JspTagException JavaDoc {
118             log.debug("Getting bytes for " + param);
119             Object JavaDoc value = parametersMap.get(param);
120             if (value instanceof FileItem) {
121                 try {
122                     return ((FileItem)value).get();
123                 } catch (Exception JavaDoc e) {
124                     throw new TaglibException(e);
125                 }
126             } else {
127                 return null;
128             }
129         }
130         public FileItem getFileItem(String JavaDoc param) throws JspTagException JavaDoc {
131             log.debug("Getting outputstream for " + param);
132             Object JavaDoc value = parametersMap.get(param);
133             if (value instanceof FileItem) {
134                 try {
135                     return (FileItem)value;
136                 } catch (Exception JavaDoc e) {
137                     throw new TaglibException(e);
138                 }
139             } else {
140                 return null;
141             }
142         }
143
144         /**
145          * Method to retrieve the bytes of an uploaded file as a string using eitehr the encoding specified in the file or
146          * the default encoding.
147          * @return <code>null</code> if parameter not found, otherwise the bytes from the parameter
148          */

149         protected String JavaDoc encodeBytesAsString(byte[] data) throws JspTagException JavaDoc {
150             String JavaDoc encoding = coding;
151             // get first 60 bytes to determine if this is a xml type
152
byte[] xmlbytes = new byte[60];
153             int sz = data.length;
154             if (sz > 60) sz = 60;
155             System.arraycopy(data, 0, xmlbytes, 0, sz);
156             String JavaDoc xmltext = new String JavaDoc(xmlbytes);
157             if (xmltext.startsWith("<?xml")) {
158                 int i = xmltext.indexOf("encoding");
159                 log.debug("i=*" + i + "*");
160                 if (i > 0) {
161                     int j = xmltext.indexOf("?>", i);
162                     log.debug("j=*" + j + "*");
163                     if (j > i) {
164                         // get trimmed attribute value
165
encoding = xmltext.substring(i + 8, j).trim();
166                         // trim '='
167
encoding = encoding.substring(1).trim();
168                         // trim quotes
169
encoding = encoding.substring(1, encoding.length() - 1).trim();
170                     }
171                 }
172             }
173             try {
174                 return new String JavaDoc(data, encoding);
175             } catch (java.io.UnsupportedEncodingException JavaDoc e) {
176                 throw new TaglibException(e);
177             }
178         }
179
180         /**
181          * @since MMBase-1.8
182          */

183         public boolean isFile(String JavaDoc param) {
184             Object JavaDoc value = parametersMap.get(param);
185             return value instanceof FileItem;
186         }
187
188         /**
189          * Method to retrieve the parameter.
190          * @param param The name of the parameter
191          * @return <code>null</code> if parameter not found, when a single occurence of the parameter
192          * the result as a <code>String</code> using the encoding specified. When if was a MultiParameter parameter, it will return
193          * a <code>List</code> of <code>String</code>'s
194          */

195         public Object JavaDoc getParameterValues(String JavaDoc param) throws JspTagException JavaDoc {
196             // this method will return null, if the parameter is not set...
197
Object JavaDoc value = parametersMap.get(param);
198             //log.debug("Got param " + param + " " + (value == null ? "NULL" : value.getClass().getName()) + " " + value);
199

200             if (value instanceof FileItem) {
201                 try {
202                     return encodeBytesAsString(((FileItem)value).get());
203                 } catch (Exception JavaDoc e) {
204                     throw new TaglibException(e);
205                 }
206             } else {
207                 return value;
208             }
209         }
210
211         public Iterator getParameterNames() {
212             return parametersMap.keySet().iterator();
213         }
214     }
215
216 }
217
Popular Tags