View Javadoc

1   /*
2    * $Header: /home/cvs/jakarta-commons/httpclient/src/java/org/apache/commons/httpclient/methods/multipart/Part.java,v 1.15 2004/10/06 03:39:59 mbecke Exp $
3    * $Revision: 1.15 $
4    * $Date: 2004/10/06 03:39:59 $
5    *
6    * ====================================================================
7    *
8    *  Copyright 2002-2004 The Apache Software Foundation
9    *
10   *  Licensed under the Apache License, Version 2.0 (the "License");
11   *  you may not use this file except in compliance with the License.
12   *  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.methods.multipart;
31  
32  import java.io.ByteArrayOutputStream;
33  import java.io.IOException;
34  import java.io.OutputStream;
35  
36  import org.apache.commons.httpclient.util.EncodingUtil;
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  
40  /***
41   * Abstract class for one Part of a multipart post object.
42   *
43   * @author <a href="mailto:mattalbright@yahoo.com">Matthew Albright</a>
44   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
45   * @author <a href="mailto:adrian@ephox.com">Adrian Sutton</a>
46   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
47   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
48   *
49   * @since 2.0
50   */
51  public abstract class Part {
52  
53      /*** Log object for this class. */
54      private static final Log LOG = LogFactory.getLog(Part.class);
55  
56      /*** 
57       * The boundary 
58       * @deprecated use {@link org.apache.commons.httpclient.params.HttpMethodParams#MULTIPART_BOUNDARY}
59       */
60      protected static final String BOUNDARY = "----------------314159265358979323846";
61      
62      /*** 
63       * The boundary as a byte array.
64       * @deprecated
65       */
66      protected static final byte[] BOUNDARY_BYTES = EncodingUtil.getAsciiBytes(BOUNDARY);
67  
68      /***
69       * The default boundary to be used if {@link #setBoundaryBytes(byte[])) has not
70       * been called.
71       */
72      private static final byte[] DEFAULT_BOUNDARY_BYTES = BOUNDARY_BYTES;    
73      
74      /*** Carriage return/linefeed */
75      protected static final String CRLF = "\r\n";
76      
77      /*** Carriage return/linefeed as a byte array */
78      protected static final byte[] CRLF_BYTES = EncodingUtil.getAsciiBytes(CRLF);
79      
80      /*** Content dispostion characters */
81      protected static final String QUOTE = "\"";
82      
83      /*** Content dispostion as a byte array */
84      protected static final byte[] QUOTE_BYTES = 
85        EncodingUtil.getAsciiBytes(QUOTE);
86  
87      /*** Extra characters */
88      protected static final String EXTRA = "--";
89      
90      /*** Extra characters as a byte array */
91      protected static final byte[] EXTRA_BYTES = 
92        EncodingUtil.getAsciiBytes(EXTRA);
93      
94      /*** Content dispostion characters */
95      protected static final String CONTENT_DISPOSITION = "Content-Disposition: form-data; name=";
96      
97      /*** Content dispostion as a byte array */
98      protected static final byte[] CONTENT_DISPOSITION_BYTES = 
99        EncodingUtil.getAsciiBytes(CONTENT_DISPOSITION);
100 
101     /*** Content type header */
102     protected static final String CONTENT_TYPE = "Content-Type: ";
103 
104     /*** Content type header as a byte array */
105     protected static final byte[] CONTENT_TYPE_BYTES = 
106       EncodingUtil.getAsciiBytes(CONTENT_TYPE);
107 
108     /*** Content charset */
109     protected static final String CHARSET = "; charset=";
110 
111     /*** Content charset as a byte array */
112     protected static final byte[] CHARSET_BYTES = 
113       EncodingUtil.getAsciiBytes(CHARSET);
114 
115     /*** Content type header */
116     protected static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: ";
117 
118     /*** Content type header as a byte array */
119     protected static final byte[] CONTENT_TRANSFER_ENCODING_BYTES = 
120       EncodingUtil.getAsciiBytes(CONTENT_TRANSFER_ENCODING);
121 
122     /***
123      * Return the boundary string.
124      * @return the boundary string
125      * @deprecated 
126      */
127     public static String getBoundary() {
128         return BOUNDARY;
129     }
130 
131     /***
132      * The ASCII bytes to use as the multipart boundary.
133      */
134     private byte[] boundaryBytes;
135     
136     /***
137      * Return the name of this part.
138      * @return The name.
139      */
140     public abstract String getName();
141     
142     /***
143      * Returns the content type of this part.
144      * @return the content type, or <code>null</code> to exclude the content type header
145      */
146     public abstract String getContentType();
147 
148     /***
149      * Return the character encoding of this part.
150      * @return the character encoding, or <code>null</code> to exclude the character 
151      * encoding header
152      */
153     public abstract String getCharSet();
154 
155     /***
156      * Return the transfer encoding of this part.
157      * @return the transfer encoding, or <code>null</code> to exclude the transfer encoding header
158      */
159     public abstract String getTransferEncoding();
160 
161     /***
162      * Gets the part boundary to be used.
163      * @return
164      * @since 3.0
165      */
166     protected byte[] getPartBoundary() {
167         if (boundaryBytes == null) {
168             // custom boundary bytes have not been set, use the default.
169             return DEFAULT_BOUNDARY_BYTES;
170         } else {
171             return boundaryBytes;            
172         }
173     }
174     
175     /***
176      * Sets the part boundary.  Only meant to be used by 
177      * {@link Part#sendParts(OutputStream, Part[], byte[])}
178      * and {@link Part#getLengthOfParts(Part[], byte[])}
179      * @param boundaryBytes An array of ASCII bytes.
180      * @since 3.0
181      */
182     void setPartBoundary(byte[] boundaryBytes) {
183         this.boundaryBytes = boundaryBytes;
184     }
185     
186     /***
187      * Tests if this part can be sent more than once.
188      * @return <code>true</code> if {@link #sendData(OutputStream)} can be successfully called 
189      * more than once.
190      * @since 3.0
191      */
192     public boolean isRepeatable() {
193         return true;
194     }
195     
196     /***
197      * Write the start to the specified output stream
198      * @param out The output stream
199      * @throws IOException If an IO problem occurs.
200      */
201     protected void sendStart(OutputStream out) throws IOException {
202         LOG.trace("enter sendStart(OutputStream out)");
203         out.write(EXTRA_BYTES);
204         out.write(getPartBoundary());
205         out.write(CRLF_BYTES);
206     }
207     
208     /***
209      * Write the content disposition header to the specified output stream
210      * 
211      * @param out The output stream
212      * @throws IOException If an IO problem occurs.
213      */
214     protected void sendDispositionHeader(OutputStream out) throws IOException {
215         LOG.trace("enter sendDispositionHeader(OutputStream out)");
216         out.write(CONTENT_DISPOSITION_BYTES);
217         out.write(QUOTE_BYTES);
218         out.write(EncodingUtil.getAsciiBytes(getName()));
219         out.write(QUOTE_BYTES);
220     }
221     
222     /***
223      * Write the content type header to the specified output stream
224      * @param out The output stream
225      * @throws IOException If an IO problem occurs.
226      */
227      protected void sendContentTypeHeader(OutputStream out) throws IOException {
228         LOG.trace("enter sendContentTypeHeader(OutputStream out)");
229         String contentType = getContentType();
230         if (contentType != null) {
231             out.write(CRLF_BYTES);
232             out.write(CONTENT_TYPE_BYTES);
233             out.write(EncodingUtil.getAsciiBytes(contentType));
234             String charSet = getCharSet();
235             if (charSet != null) {
236                 out.write(CHARSET_BYTES);
237                 out.write(EncodingUtil.getAsciiBytes(charSet));
238             }
239         }
240     }
241 
242     /***
243      * Write the content transfer encoding header to the specified 
244      * output stream
245      * 
246      * @param out The output stream
247      * @throws IOException If an IO problem occurs.
248      */
249      protected void sendTransferEncodingHeader(OutputStream out) throws IOException {
250         LOG.trace("enter sendTransferEncodingHeader(OutputStream out)");
251         String transferEncoding = getTransferEncoding();
252         if (transferEncoding != null) {
253             out.write(CRLF_BYTES);
254             out.write(CONTENT_TRANSFER_ENCODING_BYTES);
255             out.write(EncodingUtil.getAsciiBytes(transferEncoding));
256         }
257     }
258 
259     /***
260      * Write the end of the header to the output stream
261      * @param out The output stream
262      * @throws IOException If an IO problem occurs.
263      */
264     protected void sendEndOfHeader(OutputStream out) throws IOException {
265         LOG.trace("enter sendEndOfHeader(OutputStream out)");
266         out.write(CRLF_BYTES);
267         out.write(CRLF_BYTES);
268     }
269     
270     /***
271      * Write the data to the specified output stream
272      * @param out The output stream
273      * @throws IOException If an IO problem occurs.
274      */
275     protected abstract void sendData(OutputStream out) throws IOException;
276     
277     /***
278      * Return the length of the main content
279      * 
280      * @return long The length.
281      * @throws IOException If an IO problem occurs
282      */
283     protected abstract long lengthOfData() throws IOException;
284     
285     /***
286      * Write the end data to the output stream.
287      * @param out The output stream
288      * @throws IOException If an IO problem occurs.
289      */
290     protected void sendEnd(OutputStream out) throws IOException {
291         LOG.trace("enter sendEnd(OutputStream out)");
292         out.write(CRLF_BYTES);
293     }
294     
295     /***
296      * Write all the data to the output stream.
297      * If you override this method make sure to override 
298      * #length() as well
299      * 
300      * @param out The output stream
301      * @throws IOException If an IO problem occurs.
302      */
303     public void send(OutputStream out) throws IOException {
304         LOG.trace("enter send(OutputStream out)");
305         sendStart(out);
306         sendDispositionHeader(out);
307         sendContentTypeHeader(out);
308         sendTransferEncodingHeader(out);
309         sendEndOfHeader(out);
310         sendData(out);
311         sendEnd(out);
312     }
313 
314 
315     /***
316      * Return the full length of all the data.
317      * If you override this method make sure to override 
318      * #send(OutputStream) as well
319      * 
320      * @return long The length.
321      * @throws IOException If an IO problem occurs
322      */
323     public long length() throws IOException {
324         LOG.trace("enter length()");
325         ByteArrayOutputStream overhead = new ByteArrayOutputStream();
326         sendStart(overhead);
327         sendDispositionHeader(overhead);
328         sendContentTypeHeader(overhead);
329         sendTransferEncodingHeader(overhead);
330         sendEndOfHeader(overhead);
331         sendEnd(overhead);
332         return overhead.size() + lengthOfData();
333     }
334 
335     /***
336      * Return a string representation of this object.
337      * @return A string representation of this object.
338      * @see java.lang.Object#toString()
339      */    
340     public String toString() {
341         return this.getName();
342     }
343 
344     /***
345      * Write all parts and the last boundary to the specified output stream.
346      * 
347      * @param out The stream to write to.
348      * @param parts The parts to write.
349      * 
350      * @throws IOException If an I/O error occurs while writing the parts.
351      */
352     public static void sendParts(OutputStream out, final Part[] parts)
353         throws IOException {
354         sendParts(out, parts, DEFAULT_BOUNDARY_BYTES);
355     }
356 
357     /***
358      * Write all parts and the last boundary to the specified output stream.
359      * 
360      * @param out The stream to write to.
361      * @param parts The parts to write.
362      * @param partBoundary The ASCII bytes to use as the part boundary.
363      * 
364      * @throws IOException If an I/O error occurs while writing the parts.
365      * 
366      * @since 3.0
367      */
368     public static void sendParts(OutputStream out, Part[] parts, byte[] partBoundary)
369         throws IOException {
370         
371         if (parts == null) {
372             throw new IllegalArgumentException("Parts may not be null"); 
373         }
374         if (partBoundary == null || partBoundary.length == 0) {
375             throw new IllegalArgumentException("partBoundary may not be empty");
376         }
377         for (int i = 0; i < parts.length; i++) {
378             // set the part boundary before the part is sent
379             parts[i].setPartBoundary(partBoundary);
380             parts[i].send(out);
381         }
382         out.write(EXTRA_BYTES);
383         out.write(partBoundary);
384         out.write(EXTRA_BYTES);
385         out.write(CRLF_BYTES);
386     }
387     
388     /***
389      * Return the total sum of all parts and that of the last boundary
390      * 
391      * @param parts The parts.
392      * @return The total length
393      * 
394      * @throws IOException If an I/O error occurs while writing the parts.
395      */
396     public static long getLengthOfParts(Part[] parts)
397     throws IOException {
398         return getLengthOfParts(parts, DEFAULT_BOUNDARY_BYTES);
399     }
400     
401     /***
402      * Gets the length of the multipart message including the given parts.
403      * 
404      * @param parts The parts.
405      * @param partBoundary The ASCII bytes to use as the part boundary.
406      * @return The total length
407      * 
408      * @throws IOException If an I/O error occurs while writing the parts.
409      * 
410      * @since 3.0
411      */
412     public static long getLengthOfParts(Part[] parts, byte[] partBoundary) throws IOException {
413         LOG.trace("getLengthOfParts(Parts[])");
414         if (parts == null) {
415             throw new IllegalArgumentException("Parts may not be null"); 
416         }
417         long total = 0;
418         for (int i = 0; i < parts.length; i++) {
419             // set the part boundary before we calculate the part's length
420             parts[i].setPartBoundary(partBoundary);
421             total += parts[i].length();
422         }
423         total += EXTRA_BYTES.length;
424         total += partBoundary.length;
425         total += EXTRA_BYTES.length;
426         total += CRLF_BYTES.length;
427         return total;
428     }        
429 }