View Javadoc

1   /*
2    * $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 $
3    * $Revision: 155418 $
4    * $Date: 2005-02-26 08:01:52 -0500 (Sat, 26 Feb 2005) $
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 the part boundary as an array of bytes.
164      * 
165      * @since 3.0
166      */
167     protected byte[] getPartBoundary() {
168         if (boundaryBytes == null) {
169             // custom boundary bytes have not been set, use the default.
170             return DEFAULT_BOUNDARY_BYTES;
171         } else {
172             return boundaryBytes;            
173         }
174     }
175     
176     /***
177      * Sets the part boundary.  Only meant to be used by 
178      * {@link Part#sendParts(OutputStream, Part[], byte[])}
179      * and {@link Part#getLengthOfParts(Part[], byte[])}
180      * @param boundaryBytes An array of ASCII bytes.
181      * @since 3.0
182      */
183     void setPartBoundary(byte[] boundaryBytes) {
184         this.boundaryBytes = boundaryBytes;
185     }
186     
187     /***
188      * Tests if this part can be sent more than once.
189      * @return <code>true</code> if {@link #sendData(OutputStream)} can be successfully called 
190      * more than once.
191      * @since 3.0
192      */
193     public boolean isRepeatable() {
194         return true;
195     }
196     
197     /***
198      * Write the start to the specified output stream
199      * @param out The output stream
200      * @throws IOException If an IO problem occurs.
201      */
202     protected void sendStart(OutputStream out) throws IOException {
203         LOG.trace("enter sendStart(OutputStream out)");
204         out.write(EXTRA_BYTES);
205         out.write(getPartBoundary());
206         out.write(CRLF_BYTES);
207     }
208     
209     /***
210      * Write the content disposition header to the specified output stream
211      * 
212      * @param out The output stream
213      * @throws IOException If an IO problem occurs.
214      */
215     protected void sendDispositionHeader(OutputStream out) throws IOException {
216         LOG.trace("enter sendDispositionHeader(OutputStream out)");
217         out.write(CONTENT_DISPOSITION_BYTES);
218         out.write(QUOTE_BYTES);
219         out.write(EncodingUtil.getAsciiBytes(getName()));
220         out.write(QUOTE_BYTES);
221     }
222     
223     /***
224      * Write the content type header to the specified output stream
225      * @param out The output stream
226      * @throws IOException If an IO problem occurs.
227      */
228      protected void sendContentTypeHeader(OutputStream out) throws IOException {
229         LOG.trace("enter sendContentTypeHeader(OutputStream out)");
230         String contentType = getContentType();
231         if (contentType != null) {
232             out.write(CRLF_BYTES);
233             out.write(CONTENT_TYPE_BYTES);
234             out.write(EncodingUtil.getAsciiBytes(contentType));
235             String charSet = getCharSet();
236             if (charSet != null) {
237                 out.write(CHARSET_BYTES);
238                 out.write(EncodingUtil.getAsciiBytes(charSet));
239             }
240         }
241     }
242 
243     /***
244      * Write the content transfer encoding header to the specified 
245      * output stream
246      * 
247      * @param out The output stream
248      * @throws IOException If an IO problem occurs.
249      */
250      protected void sendTransferEncodingHeader(OutputStream out) throws IOException {
251         LOG.trace("enter sendTransferEncodingHeader(OutputStream out)");
252         String transferEncoding = getTransferEncoding();
253         if (transferEncoding != null) {
254             out.write(CRLF_BYTES);
255             out.write(CONTENT_TRANSFER_ENCODING_BYTES);
256             out.write(EncodingUtil.getAsciiBytes(transferEncoding));
257         }
258     }
259 
260     /***
261      * Write the end of the header to the output stream
262      * @param out The output stream
263      * @throws IOException If an IO problem occurs.
264      */
265     protected void sendEndOfHeader(OutputStream out) throws IOException {
266         LOG.trace("enter sendEndOfHeader(OutputStream out)");
267         out.write(CRLF_BYTES);
268         out.write(CRLF_BYTES);
269     }
270     
271     /***
272      * Write the data to the specified output stream
273      * @param out The output stream
274      * @throws IOException If an IO problem occurs.
275      */
276     protected abstract void sendData(OutputStream out) throws IOException;
277     
278     /***
279      * Return the length of the main content
280      * 
281      * @return long The length.
282      * @throws IOException If an IO problem occurs
283      */
284     protected abstract long lengthOfData() throws IOException;
285     
286     /***
287      * Write the end data to the output stream.
288      * @param out The output stream
289      * @throws IOException If an IO problem occurs.
290      */
291     protected void sendEnd(OutputStream out) throws IOException {
292         LOG.trace("enter sendEnd(OutputStream out)");
293         out.write(CRLF_BYTES);
294     }
295     
296     /***
297      * Write all the data to the output stream.
298      * If you override this method make sure to override 
299      * #length() as well
300      * 
301      * @param out The output stream
302      * @throws IOException If an IO problem occurs.
303      */
304     public void send(OutputStream out) throws IOException {
305         LOG.trace("enter send(OutputStream out)");
306         sendStart(out);
307         sendDispositionHeader(out);
308         sendContentTypeHeader(out);
309         sendTransferEncodingHeader(out);
310         sendEndOfHeader(out);
311         sendData(out);
312         sendEnd(out);
313     }
314 
315 
316     /***
317      * Return the full length of all the data.
318      * If you override this method make sure to override 
319      * #send(OutputStream) as well
320      * 
321      * @return long The length.
322      * @throws IOException If an IO problem occurs
323      */
324     public long length() throws IOException {
325         LOG.trace("enter length()");
326         ByteArrayOutputStream overhead = new ByteArrayOutputStream();
327         sendStart(overhead);
328         sendDispositionHeader(overhead);
329         sendContentTypeHeader(overhead);
330         sendTransferEncodingHeader(overhead);
331         sendEndOfHeader(overhead);
332         sendEnd(overhead);
333         return overhead.size() + lengthOfData();
334     }
335 
336     /***
337      * Return a string representation of this object.
338      * @return A string representation of this object.
339      * @see java.lang.Object#toString()
340      */    
341     public String toString() {
342         return this.getName();
343     }
344 
345     /***
346      * Write all parts and the last boundary to the specified output stream.
347      * 
348      * @param out The stream to write to.
349      * @param parts The parts to write.
350      * 
351      * @throws IOException If an I/O error occurs while writing the parts.
352      */
353     public static void sendParts(OutputStream out, final Part[] parts)
354         throws IOException {
355         sendParts(out, parts, DEFAULT_BOUNDARY_BYTES);
356     }
357 
358     /***
359      * Write all parts and the last boundary to the specified output stream.
360      * 
361      * @param out The stream to write to.
362      * @param parts The parts to write.
363      * @param partBoundary The ASCII bytes to use as the part boundary.
364      * 
365      * @throws IOException If an I/O error occurs while writing the parts.
366      * 
367      * @since 3.0
368      */
369     public static void sendParts(OutputStream out, Part[] parts, byte[] partBoundary)
370         throws IOException {
371         
372         if (parts == null) {
373             throw new IllegalArgumentException("Parts may not be null"); 
374         }
375         if (partBoundary == null || partBoundary.length == 0) {
376             throw new IllegalArgumentException("partBoundary may not be empty");
377         }
378         for (int i = 0; i < parts.length; i++) {
379             // set the part boundary before the part is sent
380             parts[i].setPartBoundary(partBoundary);
381             parts[i].send(out);
382         }
383         out.write(EXTRA_BYTES);
384         out.write(partBoundary);
385         out.write(EXTRA_BYTES);
386         out.write(CRLF_BYTES);
387     }
388     
389     /***
390      * Return the total sum of all parts and that of the last boundary
391      * 
392      * @param parts The parts.
393      * @return The total length
394      * 
395      * @throws IOException If an I/O error occurs while writing the parts.
396      */
397     public static long getLengthOfParts(Part[] parts)
398     throws IOException {
399         return getLengthOfParts(parts, DEFAULT_BOUNDARY_BYTES);
400     }
401     
402     /***
403      * Gets the length of the multipart message including the given parts.
404      * 
405      * @param parts The parts.
406      * @param partBoundary The ASCII bytes to use as the part boundary.
407      * @return The total length
408      * 
409      * @throws IOException If an I/O error occurs while writing the parts.
410      * 
411      * @since 3.0
412      */
413     public static long getLengthOfParts(Part[] parts, byte[] partBoundary) throws IOException {
414         LOG.trace("getLengthOfParts(Parts[])");
415         if (parts == null) {
416             throw new IllegalArgumentException("Parts may not be null"); 
417         }
418         long total = 0;
419         for (int i = 0; i < parts.length; i++) {
420             // set the part boundary before we calculate the part's length
421             parts[i].setPartBoundary(partBoundary);
422             total += parts[i].length();
423         }
424         total += EXTRA_BYTES.length;
425         total += partBoundary.length;
426         total += EXTRA_BYTES.length;
427         total += CRLF_BYTES.length;
428         return total;
429     }        
430 }