Home | History | Annotate | Download | only in multipart
      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: 502647 $
      4  * $Date: 2007-02-02 17:22:54 +0100 (Fri, 02 Feb 2007) $
      5  *
      6  * ====================================================================
      7  *
      8  *  Licensed to the Apache Software Foundation (ASF) under one or more
      9  *  contributor license agreements.  See the NOTICE file distributed with
     10  *  this work for additional information regarding copyright ownership.
     11  *  The ASF licenses this file to You under the Apache License, Version 2.0
     12  *  (the "License"); you may not use this file except in compliance with
     13  *  the License.  You may obtain a copy of the License at
     14  *
     15  *      http://www.apache.org/licenses/LICENSE-2.0
     16  *
     17  *  Unless required by applicable law or agreed to in writing, software
     18  *  distributed under the License is distributed on an "AS IS" BASIS,
     19  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     20  *  See the License for the specific language governing permissions and
     21  *  limitations under the License.
     22  * ====================================================================
     23  *
     24  * This software consists of voluntary contributions made by many
     25  * individuals on behalf of the Apache Software Foundation.  For more
     26  * information on the Apache Software Foundation, please see
     27  * <http://www.apache.org/>.
     28  *
     29  */
     30 
     31 package com.android.internal.http.multipart;
     32 
     33 import java.io.ByteArrayInputStream;
     34 import java.io.ByteArrayOutputStream;
     35 import java.io.IOException;
     36 import java.io.InputStream;
     37 import java.io.OutputStream;
     38 import java.util.Random;
     39 
     40 import org.apache.http.Header;
     41 import org.apache.http.entity.AbstractHttpEntity;
     42 import org.apache.http.message.BasicHeader;
     43 import org.apache.http.params.HttpParams;
     44 import org.apache.http.protocol.HTTP;
     45 import org.apache.http.util.EncodingUtils;
     46 import org.apache.commons.logging.Log;
     47 import org.apache.commons.logging.LogFactory;
     48 
     49 /**
     50  * Implements a request entity suitable for an HTTP multipart POST method.
     51  * <p>
     52  * The HTTP multipart POST method is defined in section 3.3 of
     53  * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC1867</a>:
     54  * <blockquote>
     55  * The media-type multipart/form-data follows the rules of all multipart
     56  * MIME data streams as outlined in RFC 1521. The multipart/form-data contains
     57  * a series of parts. Each part is expected to contain a content-disposition
     58  * header where the value is "form-data" and a name attribute specifies
     59  * the field name within the form, e.g., 'content-disposition: form-data;
     60  * name="xxxxx"', where xxxxx is the field name corresponding to that field.
     61  * Field names originally in non-ASCII character sets may be encoded using
     62  * the method outlined in RFC 1522.
     63  * </blockquote>
     64  * </p>
     65  * <p>This entity is designed to be used in conjunction with the
     66  * {@link org.apache.http.HttpRequest} to provide
     67  * multipart posts.  Example usage:</p>
     68  * <pre>
     69  *  File f = new File("/path/fileToUpload.txt");
     70  *  HttpRequest request = new HttpRequest("http://host/some_path");
     71  *  Part[] parts = {
     72  *      new StringPart("param_name", "value"),
     73  *      new FilePart(f.getName(), f)
     74  *  };
     75  *  filePost.setEntity(
     76  *      new MultipartRequestEntity(parts, filePost.getParams())
     77  *      );
     78  *  HttpClient client = new HttpClient();
     79  *  int status = client.executeMethod(filePost);
     80  * </pre>
     81  *
     82  * @since 3.0
     83  */
     84 public class MultipartEntity extends AbstractHttpEntity {
     85 
     86     private static final Log log = LogFactory.getLog(MultipartEntity.class);
     87 
     88     /** The Content-Type for multipart/form-data. */
     89     private static final String MULTIPART_FORM_CONTENT_TYPE = "multipart/form-data";
     90 
     91     /**
     92      * Sets the value to use as the multipart boundary.
     93      * <p>
     94      * This parameter expects a value if type {@link String}.
     95      * </p>
     96      */
     97     public static final String MULTIPART_BOUNDARY = "http.method.multipart.boundary";
     98 
     99     /**
    100      * The pool of ASCII chars to be used for generating a multipart boundary.
    101      */
    102     private static byte[] MULTIPART_CHARS = EncodingUtils.getAsciiBytes(
    103         "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
    104 
    105     /**
    106      * Generates a random multipart boundary string.
    107     */
    108     private static byte[] generateMultipartBoundary() {
    109         Random rand = new Random();
    110         byte[] bytes = new byte[rand.nextInt(11) + 30]; // a random size from 30 to 40
    111         for (int i = 0; i < bytes.length; i++) {
    112             bytes[i] = MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)];
    113         }
    114         return bytes;
    115     }
    116 
    117     /** The MIME parts as set by the constructor */
    118     protected Part[] parts;
    119 
    120     private byte[] multipartBoundary;
    121 
    122     private HttpParams params;
    123 
    124     private boolean contentConsumed = false;
    125 
    126     /**
    127      * Creates a new multipart entity containing the given parts.
    128      * @param parts The parts to include.
    129      * @param params The params of the HttpMethod using this entity.
    130      */
    131     public MultipartEntity(Part[] parts, HttpParams params) {
    132       if (parts == null) {
    133           throw new IllegalArgumentException("parts cannot be null");
    134       }
    135       if (params == null) {
    136           throw new IllegalArgumentException("params cannot be null");
    137       }
    138       this.parts = parts;
    139       this.params = params;
    140     }
    141 
    142     public MultipartEntity(Part[] parts) {
    143       setContentType(MULTIPART_FORM_CONTENT_TYPE);
    144       if (parts == null) {
    145           throw new IllegalArgumentException("parts cannot be null");
    146       }
    147       this.parts = parts;
    148       this.params = null;
    149     }
    150 
    151     /**
    152      * Returns the MIME boundary string that is used to demarcate boundaries of
    153      * this part. The first call to this method will implicitly create a new
    154      * boundary string. To create a boundary string first the
    155      * HttpMethodParams.MULTIPART_BOUNDARY parameter is considered. Otherwise
    156      * a random one is generated.
    157      *
    158      * @return The boundary string of this entity in ASCII encoding.
    159      */
    160     protected byte[] getMultipartBoundary() {
    161         if (multipartBoundary == null) {
    162             String temp = null;
    163             if (params != null) {
    164               temp = (String) params.getParameter(MULTIPART_BOUNDARY);
    165             }
    166             if (temp != null) {
    167                 multipartBoundary = EncodingUtils.getAsciiBytes(temp);
    168             } else {
    169                 multipartBoundary = generateMultipartBoundary();
    170             }
    171         }
    172         return multipartBoundary;
    173     }
    174 
    175     /**
    176      * Returns <code>true</code> if all parts are repeatable, <code>false</code> otherwise.
    177      */
    178     public boolean isRepeatable() {
    179         for (int i = 0; i < parts.length; i++) {
    180             if (!parts[i].isRepeatable()) {
    181                 return false;
    182             }
    183         }
    184         return true;
    185     }
    186 
    187     /* (non-Javadoc)
    188      */
    189     public void writeTo(OutputStream out) throws IOException {
    190         Part.sendParts(out, parts, getMultipartBoundary());
    191     }
    192     /* (non-Javadoc)
    193      * @see org.apache.commons.http.AbstractHttpEntity.#getContentType()
    194      */
    195     @Override
    196     public Header getContentType() {
    197       StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
    198       buffer.append("; boundary=");
    199       buffer.append(EncodingUtils.getAsciiString(getMultipartBoundary()));
    200       return new BasicHeader(HTTP.CONTENT_TYPE, buffer.toString());
    201 
    202     }
    203 
    204     /* (non-Javadoc)
    205      */
    206     public long getContentLength() {
    207         try {
    208             return Part.getLengthOfParts(parts, getMultipartBoundary());
    209         } catch (Exception e) {
    210             log.error("An exception occurred while getting the length of the parts", e);
    211             return 0;
    212         }
    213     }
    214 
    215     public InputStream getContent() throws IOException, IllegalStateException {
    216           if(!isRepeatable() && this.contentConsumed ) {
    217               throw new IllegalStateException("Content has been consumed");
    218           }
    219           this.contentConsumed = true;
    220 
    221           ByteArrayOutputStream baos = new ByteArrayOutputStream();
    222           Part.sendParts(baos, this.parts, this.multipartBoundary);
    223           ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    224           return bais;
    225     }
    226 
    227     public boolean isStreaming() {
    228         return false;
    229     }
    230 }
    231