View Javadoc

1   /*
2    * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/MultipartRequestEntity.java,v 1.1 2004/10/06 03:39:59 mbecke Exp $
3    * $Revision: 155418 $
4    * $Date: 2005-02-26 08:01:52 -0500 (Sat, 26 Feb 2005) $
5    *
6    * ====================================================================
7    *
8    *  Copyright 2002-2004 The Apache Software Foundation
9    *
10   *  Licensed under the Apache License, Version 2.0 (the "License");
11   *  you may not use this file except in compliance with the License.
12   *  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  package org.apache.commons.httpclient.methods.multipart;
30  
31  import java.io.IOException;
32  import java.io.OutputStream;
33  import java.util.Random;
34  
35  import org.apache.commons.httpclient.methods.RequestEntity;
36  import org.apache.commons.httpclient.params.HttpMethodParams;
37  import org.apache.commons.httpclient.util.EncodingUtil;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  
41  /***
42   * Implements a request entity suitable for an HTTP multipart POST method.
43   * <p>
44   * The HTTP multipart POST method is defined in section 3.3 of
45   * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC1867</a>:
46   * <blockquote>
47   * The media-type multipart/form-data follows the rules of all multipart
48   * MIME data streams as outlined in RFC 1521. The multipart/form-data contains 
49   * a series of parts. Each part is expected to contain a content-disposition 
50   * header where the value is "form-data" and a name attribute specifies 
51   * the field name within the form, e.g., 'content-disposition: form-data; 
52   * name="xxxxx"', where xxxxx is the field name corresponding to that field.
53   * Field names originally in non-ASCII character sets may be encoded using 
54   * the method outlined in RFC 1522.
55   * </blockquote>
56   * </p>
57   * <p>This entity is designed to be used in conjunction with the 
58   * {@link org.apache.commons.httpclient.methods.PostMethod post method} to provide
59   * multipart posts.  Example usage:</p>
60   * <code>
61   *  File f = new File("/path/fileToUpload.txt");
62   *  PostMethod filePost = new PostMethod("http://host/some_path");
63   *  Part[] parts = {
64   *      new StringPart("param_name", "value"),
65   *      new FilePart(f.getName(), f)
66   *  };
67   *  filePost.setRequestEntity(
68   *      new MultipartRequestEntity(parts, filePost.getParams())
69   *      );
70   *  HttpClient client = new HttpClient();
71   *  int status = client.executeMethod(filePost);
72   * </code>
73   * 
74   * @since 3.0
75   */
76  public class MultipartRequestEntity implements RequestEntity {
77  
78      private static final Log log = LogFactory.getLog(MultipartRequestEntity.class);
79      
80      /*** The Content-Type for multipart/form-data. */
81      private static final String MULTIPART_FORM_CONTENT_TYPE = "multipart/form-data";
82      
83      /***
84       * The pool of ASCII chars to be used for generating a multipart boundary.
85       */
86      private static byte[] MULTIPART_CHARS = EncodingUtil.getAsciiBytes(
87          "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
88      
89      /***
90       * Generates a random multipart boundary string.
91       * @return
92       */
93      private static byte[] generateMultipartBoundary() {
94          Random rand = new Random();
95          byte[] bytes = new byte[rand.nextInt(11) + 30]; // a random size from 30 to 40
96          for (int i = 0; i < bytes.length; i++) {
97              bytes[i] = MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)];
98          }
99          return bytes;
100     }
101     
102     private Part[] parts;
103     
104     private byte[] multipartBoundary;
105     
106     private HttpMethodParams params;
107     
108     /***
109      * Creates a new multipart entity containing the given parts.
110      * @param parts The parts to include.
111      * @param params The params of the HttpMethod using this entity.
112      */
113     public MultipartRequestEntity(Part[] parts, HttpMethodParams params) {
114         if (parts == null) {
115             throw new IllegalArgumentException("parts cannot be null");
116         }
117         if (params == null) {
118             throw new IllegalArgumentException("params cannot be null");
119         }
120         this.parts = parts;
121         this.params = params;
122     }
123 
124     private byte[] getMultipartBoundary() {
125         if (multipartBoundary == null) {
126             String temp = (String) params.getParameter(HttpMethodParams.MULTIPART_BOUNDARY);
127             if (temp != null) {
128                 multipartBoundary = EncodingUtil.getAsciiBytes(temp);
129             } else {
130                 multipartBoundary = generateMultipartBoundary();
131             }
132         }
133         return multipartBoundary;
134     }
135 
136     /***
137      * Returns <code>true</code> if all parts are repeatable, <code>false</code> otherwise.
138      * @see org.apache.commons.httpclient.methods.RequestEntity#isRepeatable()
139      */
140     public boolean isRepeatable() {
141         for (int i = 0; i < parts.length; i++) {
142             if (!parts[i].isRepeatable()) {
143                 return false;
144             }
145         }
146         return true;
147     }
148 
149     /* (non-Javadoc)
150      * @see org.apache.commons.httpclient.methods.RequestEntity#writeRequest(java.io.OutputStream)
151      */
152     public void writeRequest(OutputStream out) throws IOException {
153         Part.sendParts(out, parts, getMultipartBoundary());
154     }
155 
156     /* (non-Javadoc)
157      * @see org.apache.commons.httpclient.methods.RequestEntity#getContentLength()
158      */
159     public long getContentLength() {
160         try {
161             return Part.getLengthOfParts(parts, getMultipartBoundary());            
162         } catch (Exception e) {
163             log.error("An exception occurred while getting the length of the parts", e);
164             return 0;
165         }
166     }
167 
168     /* (non-Javadoc)
169      * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType()
170      */
171     public String getContentType() {
172         StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
173         buffer.append("; boundary=");
174         buffer.append(EncodingUtil.getAsciiString(getMultipartBoundary()));
175         return buffer.toString();
176     }
177 
178 }