1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
package org.mule.transport.tcp.protocols; |
8 | |
|
9 | |
import java.io.IOException; |
10 | |
import java.io.InputStream; |
11 | |
import java.text.MessageFormat; |
12 | |
|
13 | |
import org.apache.commons.io.output.ByteArrayOutputStream; |
14 | |
import org.apache.commons.logging.Log; |
15 | |
import org.apache.commons.logging.LogFactory; |
16 | |
|
17 | |
|
18 | |
|
19 | |
|
20 | |
|
21 | |
|
22 | |
|
23 | |
|
24 | |
|
25 | |
|
26 | |
|
27 | |
public class DirectProtocol extends AbstractByteProtocol |
28 | |
{ |
29 | |
|
30 | |
protected static final int UNLIMITED = -1; |
31 | |
|
32 | 0 | private static final Log logger = LogFactory.getLog(DirectProtocol.class); |
33 | |
private static final int DEFAULT_BUFFER_SIZE = 8192; |
34 | |
|
35 | |
protected int bufferSize; |
36 | |
|
37 | |
public DirectProtocol() |
38 | |
{ |
39 | 0 | this(STREAM_OK, DEFAULT_BUFFER_SIZE); |
40 | 0 | } |
41 | |
|
42 | |
public DirectProtocol(boolean streamOk, int bufferSize) |
43 | |
{ |
44 | 0 | super(streamOk); |
45 | 0 | this.bufferSize = bufferSize; |
46 | 0 | } |
47 | |
|
48 | |
public Object read(InputStream is) throws IOException |
49 | |
{ |
50 | 0 | return read(is, UNLIMITED); |
51 | |
} |
52 | |
|
53 | |
public Object read(InputStream is, int limit) throws IOException |
54 | |
{ |
55 | |
|
56 | 0 | ByteArrayOutputStream baos = new ByteArrayOutputStream(bufferSize); |
57 | |
|
58 | |
try |
59 | |
{ |
60 | 0 | byte[] buffer = new byte[bufferSize]; |
61 | |
int len; |
62 | 0 | int remain = remaining(limit, limit, 0); |
63 | |
boolean repeat; |
64 | |
do |
65 | |
{ |
66 | |
|
67 | 0 | len = copy(is, buffer, baos, remain); |
68 | 0 | remain = remaining(limit, remain, len); |
69 | 0 | repeat = EOF != len && remain > 0 && isRepeat(len, is.available()); |
70 | |
|
71 | 0 | if (logger.isDebugEnabled()) |
72 | |
{ |
73 | 0 | logger.debug(MessageFormat.format( |
74 | |
"len/limit/repeat: {0}/{1}/{2}", |
75 | |
len, limit, repeat)); |
76 | |
} |
77 | |
} |
78 | 0 | while (repeat); |
79 | |
} |
80 | |
finally |
81 | |
{ |
82 | 0 | baos.flush(); |
83 | 0 | baos.close(); |
84 | 0 | } |
85 | 0 | return nullEmptyArray(baos.toByteArray()); |
86 | |
} |
87 | |
|
88 | |
protected int remaining(int limit, int remain, int len) |
89 | |
{ |
90 | 0 | if (UNLIMITED == limit) |
91 | |
{ |
92 | 0 | return bufferSize; |
93 | |
} |
94 | 0 | else if (EOF != len) |
95 | |
{ |
96 | 0 | return remain - len; |
97 | |
} |
98 | |
else |
99 | |
{ |
100 | 0 | return remain; |
101 | |
} |
102 | |
} |
103 | |
|
104 | |
|
105 | |
|
106 | |
|
107 | |
|
108 | |
|
109 | |
|
110 | |
|
111 | |
|
112 | |
|
113 | |
|
114 | |
protected boolean isRepeat(int len, int available) |
115 | |
{ |
116 | |
|
117 | |
|
118 | |
|
119 | 0 | return available > 0; |
120 | |
} |
121 | |
|
122 | |
} |