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.ByteArrayOutputStream;
31  import java.io.IOException;
32  import java.io.OutputStream;
33  import java.nio.ByteBuffer;
34  import java.nio.CharBuffer;
35  import java.nio.charset.Charset;
36  import java.util.List;
37  
38  import org.apache.http.entity.mime.content.ContentBody;
39  import org.apache.http.util.Args;
40  import org.apache.http.util.ByteArrayBuffer;
41  
42  /**
43   * HttpMultipart represents a collection of MIME multipart encoded content bodies. This class is
44   * capable of operating either in the strict (RFC 822, RFC 2045, RFC 2046 compliant) or
45   * the browser compatible modes.
46   *
47   * @since 4.3
48   */
49  abstract class AbstractMultipartForm {
50  
51      private static ByteArrayBuffer encode(
52              final Charset charset, final String string) {
53          final ByteBuffer encoded = charset.encode(CharBuffer.wrap(string));
54          final ByteArrayBuffer bab = new ByteArrayBuffer(encoded.remaining());
55          bab.append(encoded.array(), encoded.position(), encoded.remaining());
56          return bab;
57      }
58  
59      private static void writeBytes(
60              final ByteArrayBuffer b, final OutputStream out) throws IOException {
61          out.write(b.buffer(), 0, b.length());
62      }
63  
64      private static void writeBytes(
65              final String s, final Charset charset, final OutputStream out) throws IOException {
66          final ByteArrayBuffer b = encode(charset, s);
67          writeBytes(b, out);
68      }
69  
70      private static void writeBytes(
71              final String s, final OutputStream out) throws IOException {
72          final ByteArrayBuffer b = encode(MIME.DEFAULT_CHARSET, s);
73          writeBytes(b, out);
74      }
75  
76      protected static void writeField(
77              final MinimalField field, final OutputStream out) throws IOException {
78          writeBytes(field.getName(), out);
79          writeBytes(FIELD_SEP, out);
80          writeBytes(field.getBody(), out);
81          writeBytes(CR_LF, out);
82      }
83  
84      protected static void writeField(
85              final MinimalField field, final Charset charset, final OutputStream out) throws IOException {
86          writeBytes(field.getName(), charset, out);
87          writeBytes(FIELD_SEP, out);
88          writeBytes(field.getBody(), charset, out);
89          writeBytes(CR_LF, out);
90      }
91  
92      private static final ByteArrayBuffer FIELD_SEP = encode(MIME.DEFAULT_CHARSET, ": ");
93      private static final ByteArrayBuffer CR_LF = encode(MIME.DEFAULT_CHARSET, "\r\n");
94      private static final ByteArrayBuffer TWO_DASHES = encode(MIME.DEFAULT_CHARSET, "--");
95  
96      final Charset charset;
97      final String boundary;
98  
99      /**
100      * Creates an instance with the specified settings.
101      *
102      * @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
103      * @param boundary to use  - must not be {@code null}
104      * @throws IllegalArgumentException if charset is null or boundary is null
105      */
106     public AbstractMultipartForm(final Charset charset, final String boundary) {
107         super();
108         Args.notNull(boundary, "Multipart boundary");
109         this.charset = charset != null ? charset : MIME.DEFAULT_CHARSET;
110         this.boundary = boundary;
111     }
112 
113     public AbstractMultipartForm(final String boundary) {
114         this(null, boundary);
115     }
116 
117     public abstract List<FormBodyPart> getBodyParts();
118 
119     void doWriteTo(
120         final OutputStream out,
121         final boolean writeContent) throws IOException {
122 
123         final ByteArrayBuffer boundaryEncoded = encode(this.charset, this.boundary);
124         for (final FormBodyPart part: getBodyParts()) {
125             writeBytes(TWO_DASHES, out);
126             writeBytes(boundaryEncoded, out);
127             writeBytes(CR_LF, out);
128 
129             formatMultipartHeader(part, out);
130 
131             writeBytes(CR_LF, out);
132 
133             if (writeContent) {
134                 part.getBody().writeTo(out);
135             }
136             writeBytes(CR_LF, out);
137         }
138         writeBytes(TWO_DASHES, out);
139         writeBytes(boundaryEncoded, out);
140         writeBytes(TWO_DASHES, out);
141         writeBytes(CR_LF, out);
142     }
143 
144     /**
145       * Write the multipart header fields; depends on the style.
146       */
147     protected abstract void formatMultipartHeader(
148         final FormBodyPart part,
149         final OutputStream out) throws IOException;
150 
151     /**
152      * Writes out the content in the multipart/form encoding. This method
153      * produces slightly different formatting depending on its compatibility
154      * mode.
155      */
156     public void writeTo(final OutputStream out) throws IOException {
157         doWriteTo(out, true);
158     }
159 
160     /**
161      * Determines the total length of the multipart content (content length of
162      * individual parts plus that of extra elements required to delimit the parts
163      * from one another). If any of the @{link BodyPart}s contained in this object
164      * is of a streaming entity of unknown length the total length is also unknown.
165      * <p>
166      * This method buffers only a small amount of data in order to determine the
167      * total length of the entire entity. The content of individual parts is not
168      * buffered.
169      * </p>
170      *
171      * @return total length of the multipart entity if known, {@code -1}
172      *   otherwise.
173      */
174     public long getTotalLength() {
175         long contentLen = 0;
176         for (final FormBodyPart part: getBodyParts()) {
177             final ContentBody body = part.getBody();
178             final long len = body.getContentLength();
179             if (len >= 0) {
180                 contentLen += len;
181             } else {
182                 return -1;
183             }
184         }
185         final ByteArrayOutputStream out = new ByteArrayOutputStream();
186         try {
187             doWriteTo(out, false);
188             final byte[] extra = out.toByteArray();
189             return contentLen + extra.length;
190         } catch (final IOException ex) {
191             // Should never happen
192             return -1;
193         }
194     }
195 
196 }