summaryrefslogtreecommitdiffstats
path: root/core/java/com/android/internal/http/multipart/Part.java
blob: 1d66dc674331ee89c2f84a93fe0be7c92b859edf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
 * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/Part.java,v 1.16 2005/01/14 21:16:40 olegk Exp $
 * $Revision: 480424 $
 * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
 *
 * ====================================================================
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package com.android.internal.http.multipart;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.http.util.EncodingUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Abstract class for one Part of a multipart post object.
 *
 * @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
 * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
 * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
 * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
 * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
 *
 * @since 2.0
 *
 * @deprecated Please use {@link java.net.URLConnection} and friends instead.
 *     The Apache HTTP client is no longer maintained and may be removed in a future
 *     release. Please visit <a href="http://android-developers.blogspot.com/2011/09/androids-http-clients.html">this webpage</a>
 *     for further details.
 */
@Deprecated
public abstract class Part {

    /** Log object for this class. */
    private static final Log LOG = LogFactory.getLog(Part.class);

    /** 
     * The boundary 
     * @deprecated use {@link org.apache.http.client.methods.multipart#MULTIPART_BOUNDARY}
     */
    protected static final String BOUNDARY = "----------------314159265358979323846";
    
    /** 
     * The boundary as a byte array.
     * @deprecated
     */
    protected static final byte[] BOUNDARY_BYTES = EncodingUtils.getAsciiBytes(BOUNDARY);

    /**
     * The default boundary to be used if {@link #setPartBoundary(byte[])} has not
     * been called.
     */
    private static final byte[] DEFAULT_BOUNDARY_BYTES = BOUNDARY_BYTES;    
    
    /** Carriage return/linefeed */
    protected static final String CRLF = "\r\n";
    
    /** Carriage return/linefeed as a byte array */
    protected static final byte[] CRLF_BYTES = EncodingUtils.getAsciiBytes(CRLF);
    
    /** Content dispostion characters */
    protected static final String QUOTE = "\"";
    
    /** Content dispostion as a byte array */
    protected static final byte[] QUOTE_BYTES = 
      EncodingUtils.getAsciiBytes(QUOTE);

    /** Extra characters */
    protected static final String EXTRA = "--";
    
    /** Extra characters as a byte array */
    protected static final byte[] EXTRA_BYTES = 
      EncodingUtils.getAsciiBytes(EXTRA);
    
    /** Content dispostion characters */
    protected static final String CONTENT_DISPOSITION = "Content-Disposition: form-data; name=";
    
    /** Content dispostion as a byte array */
    protected static final byte[] CONTENT_DISPOSITION_BYTES = 
      EncodingUtils.getAsciiBytes(CONTENT_DISPOSITION);

    /** Content type header */
    protected static final String CONTENT_TYPE = "Content-Type: ";

    /** Content type header as a byte array */
    protected static final byte[] CONTENT_TYPE_BYTES = 
      EncodingUtils.getAsciiBytes(CONTENT_TYPE);

    /** Content charset */
    protected static final String CHARSET = "; charset=";

    /** Content charset as a byte array */
    protected static final byte[] CHARSET_BYTES = 
      EncodingUtils.getAsciiBytes(CHARSET);

    /** Content type header */
    protected static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: ";

    /** Content type header as a byte array */
    protected static final byte[] CONTENT_TRANSFER_ENCODING_BYTES = 
      EncodingUtils.getAsciiBytes(CONTENT_TRANSFER_ENCODING);

    /**
     * Return the boundary string.
     * @return the boundary string
     * @deprecated uses a constant string. Rather use {@link #getPartBoundary}
     */
    public static String getBoundary() {
        return BOUNDARY;
    }

    /**
     * The ASCII bytes to use as the multipart boundary.
     */
    private byte[] boundaryBytes;
    
    /**
     * Return the name of this part.
     * @return The name.
     */
    public abstract String getName();
    
    /**
     * Returns the content type of this part.
     * @return the content type, or <code>null</code> to exclude the content type header
     */
    public abstract String getContentType();

    /**
     * Return the character encoding of this part.
     * @return the character encoding, or <code>null</code> to exclude the character 
     * encoding header
     */
    public abstract String getCharSet();

    /**
     * Return the transfer encoding of this part.
     * @return the transfer encoding, or <code>null</code> to exclude the transfer encoding header
     */
    public abstract String getTransferEncoding();

    /**
     * Gets the part boundary to be used.
     * @return the part boundary as an array of bytes.
     * 
     * @since 3.0
     */
    protected byte[] getPartBoundary() {
        if (boundaryBytes == null) {
            // custom boundary bytes have not been set, use the default.
            return DEFAULT_BOUNDARY_BYTES;
        } else {
            return boundaryBytes;            
        }
    }
    
    /**
     * Sets the part boundary.  Only meant to be used by 
     * {@link Part#sendParts(OutputStream, Part[], byte[])}
     * and {@link Part#getLengthOfParts(Part[], byte[])}
     * @param boundaryBytes An array of ASCII bytes.
     * @since 3.0
     */
    void setPartBoundary(byte[] boundaryBytes) {
        this.boundaryBytes = boundaryBytes;
    }
    
    /**
     * Tests if this part can be sent more than once.
     * @return <code>true</code> if {@link #sendData(OutputStream)} can be successfully called 
     * more than once.
     * @since 3.0
     */
    public boolean isRepeatable() {
        return true;
    }
    
    /**
     * Write the start to the specified output stream
     * @param out The output stream
     * @throws IOException If an IO problem occurs.
     */
    protected void sendStart(OutputStream out) throws IOException {
        LOG.trace("enter sendStart(OutputStream out)");
        out.write(EXTRA_BYTES);
        out.write(getPartBoundary());
        out.write(CRLF_BYTES);
    }
    
    /**
     * Write the content disposition header to the specified output stream
     * 
     * @param out The output stream
     * @throws IOException If an IO problem occurs.
     */
    protected void sendDispositionHeader(OutputStream out) throws IOException {
        LOG.trace("enter sendDispositionHeader(OutputStream out)");
        out.write(CONTENT_DISPOSITION_BYTES);
        out.write(QUOTE_BYTES);
        out.write(EncodingUtils.getAsciiBytes(getName()));
        out.write(QUOTE_BYTES);
    }
    
    /**
     * Write the content type header to the specified output stream
     * @param out The output stream
     * @throws IOException If an IO problem occurs.
     */
     protected void sendContentTypeHeader(OutputStream out) throws IOException {
        LOG.trace("enter sendContentTypeHeader(OutputStream out)");
        String contentType = getContentType();
        if (contentType != null) {
            out.write(CRLF_BYTES);
            out.write(CONTENT_TYPE_BYTES);
            out.write(EncodingUtils.getAsciiBytes(contentType));
            String charSet = getCharSet();
            if (charSet != null) {
                out.write(CHARSET_BYTES);
                out.write(EncodingUtils.getAsciiBytes(charSet));
            }
        }
    }

    /**
     * Write the content transfer encoding header to the specified 
     * output stream
     * 
     * @param out The output stream
     * @throws IOException If an IO problem occurs.
     */
     protected void sendTransferEncodingHeader(OutputStream out) throws IOException {
        LOG.trace("enter sendTransferEncodingHeader(OutputStream out)");
        String transferEncoding = getTransferEncoding();
        if (transferEncoding != null) {
            out.write(CRLF_BYTES);
            out.write(CONTENT_TRANSFER_ENCODING_BYTES);
            out.write(EncodingUtils.getAsciiBytes(transferEncoding));
        }
    }

    /**
     * Write the end of the header to the output stream
     * @param out The output stream
     * @throws IOException If an IO problem occurs.
     */
    protected void sendEndOfHeader(OutputStream out) throws IOException {
        LOG.trace("enter sendEndOfHeader(OutputStream out)");
        out.write(CRLF_BYTES);
        out.write(CRLF_BYTES);
    }
    
    /**
     * Write the data to the specified output stream
     * @param out The output stream
     * @throws IOException If an IO problem occurs.
     */
    protected abstract void sendData(OutputStream out) throws IOException;
    
    /**
     * Return the length of the main content
     * 
     * @return long The length.
     * @throws IOException If an IO problem occurs
     */
    protected abstract long lengthOfData() throws IOException;
    
    /**
     * Write the end data to the output stream.
     * @param out The output stream
     * @throws IOException If an IO problem occurs.
     */
    protected void sendEnd(OutputStream out) throws IOException {
        LOG.trace("enter sendEnd(OutputStream out)");
        out.write(CRLF_BYTES);
    }
    
    /**
     * Write all the data to the output stream.
     * If you override this method make sure to override 
     * #length() as well
     * 
     * @param out The output stream
     * @throws IOException If an IO problem occurs.
     */
    public void send(OutputStream out) throws IOException {
        LOG.trace("enter send(OutputStream out)");
        sendStart(out);
        sendDispositionHeader(out);
        sendContentTypeHeader(out);
        sendTransferEncodingHeader(out);
        sendEndOfHeader(out);
        sendData(out);
        sendEnd(out);
    }


    /**
     * Return the full length of all the data.
     * If you override this method make sure to override 
     * #send(OutputStream) as well
     * 
     * @return long The length.
     * @throws IOException If an IO problem occurs
     */
    public long length() throws IOException {
        LOG.trace("enter length()");
        if (lengthOfData() < 0) {
            return -1;
        }
        ByteArrayOutputStream overhead = new ByteArrayOutputStream();
        sendStart(overhead);
        sendDispositionHeader(overhead);
        sendContentTypeHeader(overhead);
        sendTransferEncodingHeader(overhead);
        sendEndOfHeader(overhead);
        sendEnd(overhead);
        return overhead.size() + lengthOfData();
    }

    /**
     * Return a string representation of this object.
     * @return A string representation of this object.
     * @see java.lang.Object#toString()
     */    
    @Override
    public String toString() {
        return this.getName();
    }

    /**
     * Write all parts and the last boundary to the specified output stream.
     * 
     * @param out The stream to write to.
     * @param parts The parts to write.
     * 
     * @throws IOException If an I/O error occurs while writing the parts.
     */
    public static void sendParts(OutputStream out, final Part[] parts)
        throws IOException {
        sendParts(out, parts, DEFAULT_BOUNDARY_BYTES);
    }

    /**
     * Write all parts and the last boundary to the specified output stream.
     * 
     * @param out The stream to write to.
     * @param parts The parts to write.
     * @param partBoundary The ASCII bytes to use as the part boundary.
     * 
     * @throws IOException If an I/O error occurs while writing the parts.
     * 
     * @since 3.0
     */
    public static void sendParts(OutputStream out, Part[] parts, byte[] partBoundary)
        throws IOException {
        
        if (parts == null) {
            throw new IllegalArgumentException("Parts may not be null"); 
        }
        if (partBoundary == null || partBoundary.length == 0) {
            throw new IllegalArgumentException("partBoundary may not be empty");
        }
        for (int i = 0; i < parts.length; i++) {
            // set the part boundary before the part is sent
            parts[i].setPartBoundary(partBoundary);
            parts[i].send(out);
        }
        out.write(EXTRA_BYTES);
        out.write(partBoundary);
        out.write(EXTRA_BYTES);
        out.write(CRLF_BYTES);
    }
    
    /**
     * Return the total sum of all parts and that of the last boundary
     * 
     * @param parts The parts.
     * @return The total length
     * 
     * @throws IOException If an I/O error occurs while writing the parts.
     */
    public static long getLengthOfParts(Part[] parts)
    throws IOException {
        return getLengthOfParts(parts, DEFAULT_BOUNDARY_BYTES);
    }
    
    /**
     * Gets the length of the multipart message including the given parts.
     * 
     * @param parts The parts.
     * @param partBoundary The ASCII bytes to use as the part boundary.
     * @return The total length
     * 
     * @throws IOException If an I/O error occurs while writing the parts.
     * 
     * @since 3.0
     */
    public static long getLengthOfParts(Part[] parts, byte[] partBoundary) throws IOException {
        LOG.trace("getLengthOfParts(Parts[])");
        if (parts == null) {
            throw new IllegalArgumentException("Parts may not be null"); 
        }
        long total = 0;
        for (int i = 0; i < parts.length; i++) {
            // set the part boundary before we calculate the part's length
            parts[i].setPartBoundary(partBoundary);
            long l = parts[i].length();
            if (l < 0) {
                return -1;
            }
            total += l;
        }
        total += EXTRA_BYTES.length;
        total += partBoundary.length;
        total += EXTRA_BYTES.length;
        total += CRLF_BYTES.length;
        return total;
    }        
}