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