1
2
3
4
5
6
7 package org.mule.transport.http.multipart;
8
9 import java.io.FilterOutputStream;
10 import java.io.IOException;
11 import java.io.OutputStream;
12
13
14
15
16
17
18
19 public class MultiPartOutputStream extends FilterOutputStream
20 {
21
22 private static byte[] __CRLF;
23 private static byte[] __DASHDASH;
24 private String encoding;
25
26
27
28 private String boundary;
29 private byte[] boundaryBytes;
30
31
32 private boolean inPart=false;
33
34
35 public MultiPartOutputStream(OutputStream out, String encoding)
36 throws IOException
37 {
38 super(out);
39 this.encoding = encoding;
40
41 __CRLF="\015\012".getBytes(encoding);
42 __DASHDASH="--".getBytes(encoding);
43
44 boundary = "mule"+System.identityHashCode(this)+
45 Long.toString(System.currentTimeMillis(),36);
46 boundaryBytes=boundary.getBytes(encoding);
47
48 inPart=false;
49 }
50
51
52
53
54
55
56
57 public void close()
58 throws IOException
59 {
60 if (inPart)
61 out.write(__CRLF);
62 out.write(__DASHDASH);
63 out.write(boundaryBytes);
64 out.write(__DASHDASH);
65 out.write(__CRLF);
66 inPart=false;
67 super.close();
68 }
69
70
71 public String getBoundary()
72 {
73 return boundary;
74 }
75
76 public OutputStream getOut() {return out;}
77
78
79
80
81 public void startPart(String contentType)
82 throws IOException
83 {
84 if (inPart)
85 out.write(__CRLF);
86 inPart=true;
87 out.write(__DASHDASH);
88 out.write(boundaryBytes);
89 out.write(__CRLF);
90 out.write(("Content-Type: "+contentType).getBytes(encoding));
91 out.write(__CRLF);
92 out.write(__CRLF);
93 }
94
95
96
97
98 public void startPart(String contentType, String[] headers)
99 throws IOException
100 {
101 if (inPart)
102 out.write(__CRLF);
103 inPart=true;
104 out.write(__DASHDASH);
105 out.write(boundaryBytes);
106 out.write(__CRLF);
107 out.write(("Content-Type: "+contentType).getBytes(encoding));
108 out.write(__CRLF);
109 for (int i=0;headers!=null && i<headers.length;i++)
110 {
111 out.write(headers[i].getBytes(encoding));
112 out.write(__CRLF);
113 }
114 out.write(__CRLF);
115 }
116
117 }