1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
package org.mule.transport.tcp.protocols; |
12 | |
|
13 | |
import java.io.DataInputStream; |
14 | |
import java.io.DataOutputStream; |
15 | |
import java.io.IOException; |
16 | |
import java.io.InputStream; |
17 | |
import java.io.OutputStream; |
18 | |
|
19 | |
import org.apache.commons.logging.Log; |
20 | |
import org.apache.commons.logging.LogFactory; |
21 | |
|
22 | |
|
23 | |
|
24 | |
|
25 | |
|
26 | |
|
27 | |
|
28 | |
|
29 | |
|
30 | |
|
31 | |
public class LengthProtocol extends DirectProtocol |
32 | |
{ |
33 | |
|
34 | 2 | private static final Log logger = LogFactory.getLog(LengthProtocol.class); |
35 | |
|
36 | |
private static final int SIZE_INT = 4; |
37 | |
public static final int NO_MAX_LENGTH = -1; |
38 | |
private int maxMessageLength; |
39 | |
|
40 | |
public LengthProtocol() |
41 | |
{ |
42 | 184 | this(NO_MAX_LENGTH); |
43 | 184 | } |
44 | |
|
45 | |
public LengthProtocol(int maxMessageLength) |
46 | |
{ |
47 | 344 | super(NO_STREAM, SIZE_INT); |
48 | 344 | this.setMaxMessageLength(maxMessageLength); |
49 | 344 | } |
50 | |
|
51 | |
public Object read(InputStream is) throws IOException |
52 | |
{ |
53 | |
|
54 | |
|
55 | |
|
56 | |
|
57 | 503 | DataInputStream dis = new DataInputStream(is); |
58 | 503 | dis.mark(SIZE_INT); |
59 | |
|
60 | 503 | if (null == super.read(dis, SIZE_INT)) |
61 | |
{ |
62 | 65 | return null; |
63 | |
} |
64 | |
|
65 | |
|
66 | 437 | dis.reset(); |
67 | 437 | int length = dis.readInt(); |
68 | 437 | if (logger.isDebugEnabled()) |
69 | |
{ |
70 | 0 | logger.debug("length: " + length); |
71 | |
} |
72 | |
|
73 | 437 | if (length < 0 || (getMaxMessageLength() > 0 && length > getMaxMessageLength())) |
74 | |
{ |
75 | 7 | throw new IOException("Length " + length + " exceeds limit: " + getMaxMessageLength()); |
76 | |
} |
77 | |
|
78 | |
|
79 | 430 | byte[] buffer = new byte[length]; |
80 | 430 | dis.readFully(buffer); |
81 | 430 | if (logger.isDebugEnabled()) |
82 | |
{ |
83 | 0 | logger.debug("length read: " + buffer.length); |
84 | |
} |
85 | |
|
86 | 430 | return buffer; |
87 | |
} |
88 | |
|
89 | |
|
90 | |
protected void writeByteArray(OutputStream os, byte[] data) throws IOException |
91 | |
{ |
92 | |
|
93 | 475 | DataOutputStream dos = new DataOutputStream(os); |
94 | 475 | dos.writeInt(data.length); |
95 | 475 | dos.write(data); |
96 | 454 | dos.flush(); |
97 | 454 | } |
98 | |
|
99 | |
|
100 | |
|
101 | |
|
102 | |
|
103 | |
|
104 | |
|
105 | |
|
106 | |
|
107 | |
protected boolean isRepeat(int len, int available) |
108 | |
{ |
109 | 19 | return true; |
110 | |
} |
111 | |
|
112 | |
public int getMaxMessageLength() |
113 | |
{ |
114 | 504 | return maxMessageLength; |
115 | |
} |
116 | |
|
117 | |
public void setMaxMessageLength(int maxMessageLength) |
118 | |
{ |
119 | 348 | this.maxMessageLength = maxMessageLength; |
120 | 348 | } |
121 | |
|
122 | |
} |