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.entity.ContentType;
40  import org.apache.http.entity.mime.content.ByteArrayBody;
41  import org.apache.http.entity.mime.content.ContentBody;
42  import org.apache.http.entity.mime.content.FileBody;
43  import org.apache.http.entity.mime.content.InputStreamBody;
44  import org.apache.http.entity.mime.content.StringBody;
45  import org.apache.http.util.Args;
46  
47  /**
48   * Builder for multipart {@link HttpEntity}s.
49   *
50   * @since 4.3
51   */
52  public class MultipartEntityBuilder {
53  
54      /**
55       * The pool of ASCII chars to be used for generating a multipart boundary.
56       */
57      private final static char[] MULTIPART_CHARS =
58              "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
59                      .toCharArray();
60  
61      private final static String DEFAULT_SUBTYPE = "form-data";
62  
63      private String subType = DEFAULT_SUBTYPE;
64      private HttpMultipartMode mode = HttpMultipartMode.STRICT;
65      private String boundary = null;
66      private Charset charset = null;
67      private List<FormBodyPart> bodyParts = null;
68  
69      public static MultipartEntityBuilder create() {
70          return new MultipartEntityBuilder();
71      }
72  
73      MultipartEntityBuilder() {
74          super();
75      }
76  
77      public MultipartEntityBuilder setMode(final HttpMultipartMode mode) {
78          this.mode = mode;
79          return this;
80      }
81  
82      public MultipartEntityBuilder setLaxMode() {
83          this.mode = HttpMultipartMode.BROWSER_COMPATIBLE;
84          return this;
85      }
86  
87      public MultipartEntityBuilder setStrictMode() {
88          this.mode = HttpMultipartMode.STRICT;
89          return this;
90      }
91  
92      public MultipartEntityBuilder setBoundary(final String boundary) {
93          this.boundary = boundary;
94          return this;
95      }
96  
97      /**
98       * @since 4.4
99       */
100     public MultipartEntityBuilder setMimeSubtype(final String subType) {
101         Args.notBlank(subType, "MIME subtype");
102         this.subType = subType;
103         return this;
104     }
105 
106     public MultipartEntityBuilder setCharset(final Charset charset) {
107         this.charset = charset;
108         return this;
109     }
110 
111     /**
112      * @since 4.4
113      */
114     public MultipartEntityBuilder addPart(final FormBodyPart bodyPart) {
115         if (bodyPart == null) {
116             return this;
117         }
118         if (this.bodyParts == null) {
119             this.bodyParts = new ArrayList<FormBodyPart>();
120         }
121         this.bodyParts.add(bodyPart);
122         return this;
123     }
124 
125     public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) {
126         Args.notNull(name, "Name");
127         Args.notNull(contentBody, "Content body");
128         return addPart(new FormBodyPart(name, contentBody));
129     }
130 
131     public MultipartEntityBuilder addTextBody(
132             final String name, final String text, final ContentType contentType) {
133         return addPart(name, new StringBody(text, contentType));
134     }
135 
136     public MultipartEntityBuilder addTextBody(
137             final String name, final String text) {
138         return addTextBody(name, text, ContentType.DEFAULT_TEXT);
139     }
140 
141     public MultipartEntityBuilder addBinaryBody(
142             final String name, final byte[] b, final ContentType contentType, final String filename) {
143         return addPart(name, new ByteArrayBody(b, contentType, filename));
144     }
145 
146     public MultipartEntityBuilder addBinaryBody(
147             final String name, final byte[] b) {
148         return addBinaryBody(name, b, ContentType.DEFAULT_BINARY, null);
149     }
150 
151     public MultipartEntityBuilder addBinaryBody(
152             final String name, final File file, final ContentType contentType, final String filename) {
153         return addPart(name, new FileBody(file, contentType, filename));
154     }
155 
156     public MultipartEntityBuilder addBinaryBody(
157             final String name, final File file) {
158         return addBinaryBody(name, file, ContentType.DEFAULT_BINARY, file != null ? file.getName() : null);
159     }
160 
161     public MultipartEntityBuilder addBinaryBody(
162             final String name, final InputStream stream, final ContentType contentType,
163             final String filename) {
164         return addPart(name, new InputStreamBody(stream, contentType, filename));
165     }
166 
167     public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream) {
168         return addBinaryBody(name, stream, ContentType.DEFAULT_BINARY, null);
169     }
170 
171     private String generateContentType(
172             final String boundary,
173             final String subType,
174             final Charset charset) {
175         final StringBuilder buffer = new StringBuilder();
176         buffer.append("multipart/").append(subType).append("; boundary=");
177         buffer.append(boundary);
178         if (charset != null) {
179             buffer.append("; charset=");
180             buffer.append(charset.name());
181         }
182         return buffer.toString();
183     }
184 
185     private String generateBoundary() {
186         final StringBuilder buffer = new StringBuilder();
187         final Random rand = new Random();
188         final int count = rand.nextInt(11) + 30; // a random size from 30 to 40
189         for (int i = 0; i < count; i++) {
190             buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
191         }
192         return buffer.toString();
193     }
194 
195     MultipartFormEntity buildEntity() {
196         final String st = subType != null ? subType : DEFAULT_SUBTYPE;
197         final Charset cs = charset;
198         final String b = boundary != null ? boundary : generateBoundary();
199         final List<FormBodyPart> bps = bodyParts != null ? new ArrayList<FormBodyPart>(bodyParts) :
200                 Collections.<FormBodyPart>emptyList();
201         final HttpMultipartMode m = mode != null ? mode : HttpMultipartMode.STRICT;
202         final AbstractMultipartForm form;
203         switch (m) {
204             case BROWSER_COMPATIBLE:
205                 form = new HttpBrowserCompatibleMultipart(st, cs, b, bps);
206                 break;
207             case RFC6532:
208                 form = new HttpRFC6532Multipart(st, cs, b, bps);
209                 break;
210             default:
211                 form = new HttpStrictMultipart(st, cs, b, bps);
212         }
213         return new MultipartFormEntity(form, generateContentType(b, st, cs), form.getTotalLength());
214     }
215 
216     public HttpEntity build() {
217         return buildEntity();
218     }
219 
220 }