View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.entity.mime;
29  
30  import java.io.File;
31  import java.io.InputStream;
32  import java.nio.charset.Charset;
33  import java.util.ArrayList;
34  import java.util.Collections;
35  import java.util.List;
36  import java.util.Random;
37  
38  import org.apache.http.HttpEntity;
39  import org.apache.http.NameValuePair;
40  import org.apache.http.entity.ContentType;
41  import org.apache.http.entity.mime.content.ByteArrayBody;
42  import org.apache.http.entity.mime.content.ContentBody;
43  import org.apache.http.entity.mime.content.FileBody;
44  import org.apache.http.entity.mime.content.InputStreamBody;
45  import org.apache.http.entity.mime.content.StringBody;
46  import org.apache.http.message.BasicNameValuePair;
47  import org.apache.http.util.Args;
48  
49  /**
50   * Builder for multipart {@link HttpEntity}s.
51   *
52   * @since 4.3
53   */
54  public class MultipartEntityBuilder {
55  
56      /**
57       * The pool of ASCII chars to be used for generating a multipart boundary.
58       */
59      private final static char[] MULTIPART_CHARS =
60              "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
61                      .toCharArray();
62  
63      private final static String DEFAULT_SUBTYPE = "form-data";
64  
65      private ContentType contentType;
66      private HttpMultipartMode mode = HttpMultipartMode.STRICT;
67      private String boundary = null;
68      private Charset charset = null;
69      private List<FormBodyPart> bodyParts = null;
70  
71      public static MultipartEntityBuilder create() {
72          return new MultipartEntityBuilder();
73      }
74  
75      MultipartEntityBuilder() {
76      }
77  
78      public MultipartEntityBuilder setMode(final HttpMultipartMode mode) {
79          this.mode = mode;
80          return this;
81      }
82  
83      public MultipartEntityBuilder setLaxMode() {
84          this.mode = HttpMultipartMode.BROWSER_COMPATIBLE;
85          return this;
86      }
87  
88      public MultipartEntityBuilder setStrictMode() {
89          this.mode = HttpMultipartMode.STRICT;
90          return this;
91      }
92  
93      public MultipartEntityBuilder setBoundary(final String boundary) {
94          this.boundary = boundary;
95          return this;
96      }
97  
98      /**
99       * @since 4.4
100      */
101     public MultipartEntityBuilder setMimeSubtype(final String subType) {
102         Args.notBlank(subType, "MIME subtype");
103         this.contentType = ContentType.create("multipart/" + subType);
104         return this;
105     }
106 
107     /**
108      * @since 4.4
109      */
110     public MultipartEntityBuilder seContentType(final ContentType contentType) {
111         Args.notNull(contentType, "Content type");
112         this.contentType = contentType;
113         return this;
114     }
115 
116     public MultipartEntityBuilder setCharset(final Charset charset) {
117         this.charset = charset;
118         return this;
119     }
120 
121     /**
122      * @since 4.4
123      */
124     public MultipartEntityBuilder addPart(final FormBodyPart bodyPart) {
125         if (bodyPart == null) {
126             return this;
127         }
128         if (this.bodyParts == null) {
129             this.bodyParts = new ArrayList<FormBodyPart>();
130         }
131         this.bodyParts.add(bodyPart);
132         return this;
133     }
134 
135     public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) {
136         Args.notNull(name, "Name");
137         Args.notNull(contentBody, "Content body");
138         return addPart(FormBodyPartBuilder.create(name, contentBody).build());
139     }
140 
141     public MultipartEntityBuilder addTextBody(
142             final String name, final String text, final ContentType contentType) {
143         return addPart(name, new StringBody(text, contentType));
144     }
145 
146     public MultipartEntityBuilder addTextBody(
147             final String name, final String text) {
148         return addTextBody(name, text, ContentType.DEFAULT_TEXT);
149     }
150 
151     public MultipartEntityBuilder addBinaryBody(
152             final String name, final byte[] b, final ContentType contentType, final String filename) {
153         return addPart(name, new ByteArrayBody(b, contentType, filename));
154     }
155 
156     public MultipartEntityBuilder addBinaryBody(
157             final String name, final byte[] b) {
158         return addBinaryBody(name, b, ContentType.DEFAULT_BINARY, null);
159     }
160 
161     public MultipartEntityBuilder addBinaryBody(
162             final String name, final File file, final ContentType contentType, final String filename) {
163         return addPart(name, new FileBody(file, contentType, filename));
164     }
165 
166     public MultipartEntityBuilder addBinaryBody(
167             final String name, final File file) {
168         return addBinaryBody(name, file, ContentType.DEFAULT_BINARY, file != null ? file.getName() : null);
169     }
170 
171     public MultipartEntityBuilder addBinaryBody(
172             final String name, final InputStream stream, final ContentType contentType,
173             final String filename) {
174         return addPart(name, new InputStreamBody(stream, contentType, filename));
175     }
176 
177     public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream) {
178         return addBinaryBody(name, stream, ContentType.DEFAULT_BINARY, null);
179     }
180 
181     private String generateBoundary() {
182         final StringBuilder buffer = new StringBuilder();
183         final Random rand = new Random();
184         final int count = rand.nextInt(11) + 30; // a random size from 30 to 40
185         for (int i = 0; i < count; i++) {
186             buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
187         }
188         return buffer.toString();
189     }
190 
191     MultipartFormEntity buildEntity() {
192         String boundaryCopy = boundary;
193         if (boundaryCopy == null && contentType != null) {
194             boundaryCopy = contentType.getParameter("boundary");
195         }
196         if (boundaryCopy == null) {
197             boundaryCopy = generateBoundary();
198         }
199         Charset charsetCopy = charset;
200         if (charsetCopy == null && contentType != null) {
201             charsetCopy = contentType.getCharset();
202         }
203         final List<NameValuePair> paramsList = new ArrayList<NameValuePair>(2);
204         paramsList.add(new BasicNameValuePair("boundary", boundaryCopy));
205         if (charsetCopy != null) {
206             paramsList.add(new BasicNameValuePair("charset", charsetCopy.name()));
207         }
208         final NameValuePair[] params = paramsList.toArray(new NameValuePair[paramsList.size()]);
209         final ContentType contentTypeCopy = contentType != null ?
210                 contentType.withParameters(params) :
211                 ContentType.create("multipart/" + DEFAULT_SUBTYPE, params);
212         final List<FormBodyPart> bodyPartsCopy = bodyParts != null ? new ArrayList<FormBodyPart>(bodyParts) :
213                 Collections.<FormBodyPart>emptyList();
214         final HttpMultipartMode modeCopy = mode != null ? mode : HttpMultipartMode.STRICT;
215         final AbstractMultipartForm form;
216         switch (modeCopy) {
217             case BROWSER_COMPATIBLE:
218                 form = new HttpBrowserCompatibleMultipart(charsetCopy, boundaryCopy, bodyPartsCopy);
219                 break;
220             case RFC6532:
221                 form = new HttpRFC6532Multipart(charsetCopy, boundaryCopy, bodyPartsCopy);
222                 break;
223             default:
224                 form = new HttpStrictMultipart(charsetCopy, boundaryCopy, bodyPartsCopy);
225         }
226         return new MultipartFormEntity(form, contentTypeCopy, form.getTotalLength());
227     }
228 
229     public HttpEntity build() {
230         return buildEntity();
231     }
232 
233 }