KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > net > filter > MultipartWrapper


1 /*
2  * This file is part of "SnipSnap Wiki/Weblog".
3  *
4  * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
5  * All Rights Reserved.
6  *
7  * Please visit http://snipsnap.org/ for updates and contact.
8  *
9  * --LICENSE NOTICE--
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  * --LICENSE NOTICE--
24  */

25 package org.snipsnap.net.filter;
26
27 import org.radeox.util.logging.Logger;
28 import org.snipsnap.util.mail.InputStreamDataSource;
29
30 import javax.mail.BodyPart JavaDoc;
31 import javax.mail.MessagingException JavaDoc;
32 import javax.mail.internet.ContentDisposition JavaDoc;
33 import javax.mail.internet.HeaderTokenizer JavaDoc;
34 import javax.mail.internet.MimeBodyPart JavaDoc;
35 import javax.mail.internet.MimeMultipart JavaDoc;
36 import javax.servlet.http.HttpServletRequest JavaDoc;
37 import javax.servlet.http.HttpServletRequestWrapper JavaDoc;
38 import java.io.IOException JavaDoc;
39 import java.io.InputStream JavaDoc;
40 import java.io.BufferedInputStream JavaDoc;
41 import java.util.Enumeration JavaDoc;
42 import java.util.HashMap JavaDoc;
43 import java.util.Hashtable JavaDoc;
44 import java.util.Map JavaDoc;
45
46 /**
47  * A MultipartWrapper that takes a request object and parses the incoming data.
48  * Access is provided for queryString parameters and all multipart/form-data entries.
49  *
50  * @author Matthias L. Jugel
51  * @version $Id: MultipartWrapper.java 1606 2004-05-17 10:56:18Z leo $
52  */

53 public class MultipartWrapper extends HttpServletRequestWrapper JavaDoc {
54
55   private String JavaDoc encoding = "UTF-8";
56   private MimeMultipart JavaDoc multipart = null;
57   private Hashtable JavaDoc params = null;
58   private Map JavaDoc files = new HashMap JavaDoc();
59
60   public MultipartWrapper(HttpServletRequest JavaDoc request, String JavaDoc enc) throws IOException JavaDoc, IllegalArgumentException JavaDoc {
61     super(request);
62
63     if(null != enc) {
64       encoding = enc;
65       "".getBytes(enc);
66     }
67
68     Logger.debug("MultipartWrapper: parsing input data ...");
69     InputStreamDataSource ds = new InputStreamDataSource(new BufferedInputStream JavaDoc(request.getInputStream()), request.getContentType());
70     try {
71       multipart = new MimeMultipart JavaDoc(ds);
72       params = new Hashtable JavaDoc(request.getParameterMap());
73
74       int count = multipart.getCount();
75       for (int i = 0; i < count; i++) {
76         MimeBodyPart JavaDoc body = (MimeBodyPart JavaDoc) multipart.getBodyPart(i);
77         ContentDisposition JavaDoc disp = new ContentDisposition JavaDoc(body.getHeader("content-disposition", null));
78         String JavaDoc name = disp.getParameter("name");
79         if (body.getContentType().startsWith("text/plain")) {
80           String JavaDoc value = new String JavaDoc(((String JavaDoc) body.getContent()).getBytes("iso-8859-1"), encoding);
81           String JavaDoc[] values = (String JavaDoc[]) params.get(name);
82           if (null == values) {
83             params.put(name, new String JavaDoc[]{value});
84           } else {
85             String JavaDoc[] tmp = new String JavaDoc[values.length + 1];
86             System.arraycopy(values, 0, tmp, 0, values.length);
87             tmp[tmp.length - 1] = value;
88             params.put(name, tmp);
89           }
90         }
91         files.put(name, body);
92       }
93     } catch (MessagingException JavaDoc e) {
94       Logger.warn("Error parsing request (not multipart/form-data)", e);
95       throw new IllegalArgumentException JavaDoc("Error parsing request (not multipart/form-data?)");
96     }
97     Logger.debug("MultipartWrapper: finished parsing input data ...");
98   }
99
100   public Enumeration JavaDoc getParameterNames() {
101     return params.keys();
102   }
103
104   public String JavaDoc getParameter(String JavaDoc name) {
105     String JavaDoc[] values = (String JavaDoc[]) params.get(name);
106     if (values != null && values.length > 0) {
107       return values[0];
108     }
109     return null;
110   }
111
112   public String JavaDoc[] getParameterValues(String JavaDoc name) {
113     return (String JavaDoc[]) params.get(name);
114   }
115
116   /**
117    * Returns a map of all parameters except special body parts
118    */

119   public Map JavaDoc getParameterMap() {
120     return params;
121   }
122
123   /**
124    * If a special input field is not text it can be retrieved as BodyPart
125    * for further processing.
126    * @param name the name of the input field
127    * @return a body part object from JavaMail
128    */

129   public BodyPart JavaDoc getBodyPart(String JavaDoc name) {
130     return (BodyPart JavaDoc) files.get(name);
131   }
132
133   /**
134    * Get file name for uploaded file.
135    * @param name the name of the uploaded file field
136    */

137   public String JavaDoc getFileName(String JavaDoc name) throws IOException JavaDoc {
138
139     String JavaDoc fileName = null;
140     MimeBodyPart JavaDoc part = (MimeBodyPart JavaDoc) getBodyPart(name);
141     try {
142       // HACK: the tokenizer removes backslashes '\' from original input, so we need to
143
// parse ourself, not very nice, but necessary
144
String JavaDoc contentDisposition = new String JavaDoc(part.getHeader("content-disposition", null).getBytes("iso-8859-1"), encoding);
145       Logger.log(Logger.DEBUG, "content-disposition: " + contentDisposition);
146       HeaderTokenizer JavaDoc tokenizer = new HeaderTokenizer JavaDoc(contentDisposition, HeaderTokenizer.MIME, true);
147       HeaderTokenizer.Token JavaDoc token = null;
148       while ((token = tokenizer.next()).getType() != HeaderTokenizer.Token.EOF) {
149         if (token.getType() == HeaderTokenizer.Token.ATOM && "filename".equals(token.getValue())) {
150           String JavaDoc remainder = tokenizer.getRemainder();
151           int quoteStart = remainder.indexOf('"');
152           int quoteEnd = remainder.indexOf('"', quoteStart + 1);
153           fileName = remainder.substring(quoteStart + 1, quoteEnd);
154         }
155       }
156     } catch (Exception JavaDoc e) {
157       Logger.log(Logger.FATAL, "error parsing uploaded file name: "+e.getMessage());
158     }
159
160     if (null == fileName && part != null) {
161       try {
162         fileName = new String JavaDoc(part.getFileName().getBytes("iso-8859-1"), encoding);
163       } catch (Exception JavaDoc e) {
164         e.printStackTrace();
165         throw new IOException JavaDoc(e.getMessage());
166       }
167     }
168     Logger.log(Logger.DEBUG, "file name: '" + fileName + "'");
169     return fileName;
170   }
171
172   /**
173    * Get the content type of a file parameter from the request.
174    * @param name the name of the input field
175    * @return the content type
176    */

177   public String JavaDoc getFileContentType(String JavaDoc name) {
178     BodyPart JavaDoc part = getBodyPart(name);
179     if (part != null) {
180       try {
181         return part.getContentType();
182       } catch (MessagingException JavaDoc e) {
183         // ignore and simply return null
184
}
185     }
186     return null;
187   }
188
189   public InputStream JavaDoc getFileInputStream(String JavaDoc name) throws IOException JavaDoc {
190     BodyPart JavaDoc part = getBodyPart(name);
191     try {
192       return part.getInputStream();
193     } catch (MessagingException JavaDoc e) {
194       throw new IOException JavaDoc(e.getMessage());
195     }
196   }
197
198   public int getFileContentLength(String JavaDoc name) throws IOException JavaDoc {
199     BodyPart JavaDoc part = getBodyPart(name);
200     if (part != null) {
201       try {
202         return part.getSize();
203       } catch (MessagingException JavaDoc e) {
204         // ignore and simply return null
205
}
206     }
207     return -1;
208
209   }
210
211 }
212
213
Popular Tags