1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.portals.applications.util;
18
19 import java.io.ByteArrayOutputStream;
20 import java.io.InputStream;
21 import java.io.IOException;
22 import java.io.OutputStream;
23 import java.io.OutputStreamWriter;
24 import java.io.Reader;
25 import java.io.Writer;
26 import java.io.InputStreamReader;
27
28 /***
29 * Utility functions related to Streams.
30 *
31 * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
32 * @version $Id: Streams.java 516448 2007-03-09 16:25:47Z ate $
33 */
34 public class Streams
35 {
36 static final int BLOCK_SIZE=4096;
37
38 public static void drain(InputStream r,OutputStream w) throws IOException
39 {
40 byte[] bytes=new byte[BLOCK_SIZE];
41 try
42 {
43 int length=r.read(bytes);
44 while(length!=-1)
45 {
46 if(length!=0)
47 {
48 w.write(bytes,0,length);
49 }
50 length=r.read(bytes);
51 }
52 }
53 finally
54 {
55 bytes=null;
56 }
57
58 }
59
60 public static void drain(Reader r,Writer w) throws IOException
61 {
62 char[] bytes=new char[BLOCK_SIZE];
63 try
64 {
65 int length=r.read(bytes);
66 while(length!=-1)
67 {
68 if(length!=0)
69 {
70 w.write(bytes,0,length);
71 }
72 length=r.read(bytes);
73 }
74 }
75 finally
76 {
77 bytes=null;
78 }
79
80 }
81
82 /***
83 * @deprecated encoding?
84 * @param r character reader
85 * @param os byte stream
86 * @throws IOException
87 */
88 public static void drain(Reader r,OutputStream os) throws IOException
89 {
90 Writer w=new OutputStreamWriter(os);
91 drain(r,w);
92 w.flush();
93 }
94
95 /***
96 * @deprecated how can it know the encoding?
97 * @param is input stream (encoding?)
98 * @param w writer
99 * @throws IOException
100 */
101 public static void drain(InputStream is, Writer w) throws IOException
102 {
103 Reader r = new InputStreamReader(is);
104 drain(r,w);
105 w.flush();
106 }
107
108 public static byte[] drain(InputStream r) throws IOException
109 {
110 ByteArrayOutputStream bytes=new ByteArrayOutputStream();
111 drain(r,bytes);
112 return bytes.toByteArray();
113 }
114
115 /***
116 * @deprecated encoding?
117 * @param is input stream
118 * @return
119 */
120 public static String getAsString(InputStream is)
121 {
122 int c=0;
123 char lineBuffer[]=new char[128], buf[]=lineBuffer;
124 int room= buf.length, offset=0;
125 try
126 {
127 loop: while (true)
128 {
129
130 switch (c = is.read() )
131 {
132 case -1: break loop;
133
134 default: if (--room < 0)
135 {
136 buf = new char[offset + 128];
137 room = buf.length - offset - 1;
138 System.arraycopy(lineBuffer, 0,
139 buf, 0, offset);
140 lineBuffer = buf;
141 }
142 buf[offset++] = (char) c;
143 break;
144 }
145 }
146 }
147 catch(IOException ioe)
148 {
149 ioe.printStackTrace();
150 }
151 if ((c == -1) && (offset == 0))
152 {
153 return null;
154 }
155 return String.copyValueOf(buf, 0, offset);
156 }
157
158 }