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: 332125 $
4    * $Date: 2005-11-09 14:41:40 -0500 (Wed, 09 Nov 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 uses a constant string. Rather use {@link #getPartBoundary}
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         if (lengthOfData() < 0) {
327             return -1;
328         }
329         ByteArrayOutputStream overhead = new ByteArrayOutputStream();
330         sendStart(overhead);
331         sendDispositionHeader(overhead);
332         sendContentTypeHeader(overhead);
333         sendTransferEncodingHeader(overhead);
334         sendEndOfHeader(overhead);
335         sendEnd(overhead);
336         return overhead.size() + lengthOfData();
337     }
338 
339     /***
340      * Return a string representation of this object.
341      * @return A string representation of this object.
342      * @see java.lang.Object#toString()
343      */    
344     public String toString() {
345         return this.getName();
346     }
347 
348     /***
349      * Write all parts and the last boundary to the specified output stream.
350      * 
351      * @param out The stream to write to.
352      * @param parts The parts to write.
353      * 
354      * @throws IOException If an I/O error occurs while writing the parts.
355      */
356     public static void sendParts(OutputStream out, final Part[] parts)
357         throws IOException {
358         sendParts(out, parts, DEFAULT_BOUNDARY_BYTES);
359     }
360 
361     /***
362      * Write all parts and the last boundary to the specified output stream.
363      * 
364      * @param out The stream to write to.
365      * @param parts The parts to write.
366      * @param partBoundary The ASCII bytes to use as the part boundary.
367      * 
368      * @throws IOException If an I/O error occurs while writing the parts.
369      * 
370      * @since 3.0
371      */
372     public static void sendParts(OutputStream out, Part[] parts, byte[] partBoundary)
373         throws IOException {
374         
375         if (parts == null) {
376             throw new IllegalArgumentException("Parts may not be null"); 
377         }
378         if (partBoundary == null || partBoundary.length == 0) {
379             throw new IllegalArgumentException("partBoundary may not be empty");
380         }
381         for (int i = 0; i < parts.length; i++) {
382             // set the part boundary before the part is sent
383             parts[i].setPartBoundary(partBoundary);
384             parts[i].send(out);
385         }
386         out.write(EXTRA_BYTES);
387         out.write(partBoundary);
388         out.write(EXTRA_BYTES);
389         out.write(CRLF_BYTES);
390     }
391     
392     /***
393      * Return the total sum of all parts and that of the last boundary
394      * 
395      * @param parts The parts.
396      * @return The total length
397      * 
398      * @throws IOException If an I/O error occurs while writing the parts.
399      */
400     public static long getLengthOfParts(Part[] parts)
401     throws IOException {
402         return getLengthOfParts(parts, DEFAULT_BOUNDARY_BYTES);
403     }
404     
405     /***
406      * Gets the length of the multipart message including the given parts.
407      * 
408      * @param parts The parts.
409      * @param partBoundary The ASCII bytes to use as the part boundary.
410      * @return The total length
411      * 
412      * @throws IOException If an I/O error occurs while writing the parts.
413      * 
414      * @since 3.0
415      */
416     public static long getLengthOfParts(Part[] parts, byte[] partBoundary) throws IOException {
417         LOG.trace("getLengthOfParts(Parts[])");
418         if (parts == null) {
419             throw new IllegalArgumentException("Parts may not be null"); 
420         }
421         long total = 0;
422         for (int i = 0; i < parts.length; i++) {
423             // set the part boundary before we calculate the part's length
424             parts[i].setPartBoundary(partBoundary);
425             long l = parts[i].length();
426             if (l < 0) {
427                 return -1;
428             }
429             total += l;
430         }
431         total += EXTRA_BYTES.length;
432         total += partBoundary.length;
433         total += EXTRA_BYTES.length;
434         total += CRLF_BYTES.length;
435         return total;
436     }        
437 }