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 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 this(NO_MAX_LENGTH);
43 }
44
45 public LengthProtocol(int maxMessageLength)
46 {
47 super(NO_STREAM, SIZE_INT);
48 this.setMaxMessageLength(maxMessageLength);
49 }
50
51 public Object read(InputStream is) throws IOException
52 {
53
54
55
56
57 DataInputStream dis = new DataInputStream(is);
58 dis.mark(SIZE_INT);
59
60 if (null == super.read(dis, SIZE_INT))
61 {
62 return null;
63 }
64
65
66 dis.reset();
67 int length = dis.readInt();
68 if (logger.isDebugEnabled())
69 {
70 logger.debug("length: " + length);
71 }
72
73 if (length < 0 || (getMaxMessageLength() > 0 && length > getMaxMessageLength()))
74 {
75 throw new IOException("Length " + length + " exceeds limit: " + getMaxMessageLength());
76 }
77
78
79 byte[] buffer = new byte[length];
80 dis.readFully(buffer);
81 if (logger.isDebugEnabled())
82 {
83 logger.debug("length read: " + buffer.length);
84 }
85
86 return buffer;
87 }
88
89 @Override
90 protected void writeByteArray(OutputStream os, byte[] data) throws IOException
91 {
92
93 DataOutputStream dos = new DataOutputStream(os);
94 dos.writeInt(data.length);
95 dos.write(data);
96
97
98 if (dos.size() != data.length + SIZE_INT)
99 {
100
101 dos.flush();
102 }
103 }
104
105
106
107
108
109
110
111
112 @Override
113 protected boolean isRepeat(int len, int available)
114 {
115 return true;
116 }
117
118 public int getMaxMessageLength()
119 {
120 return maxMessageLength;
121 }
122
123 public void setMaxMessageLength(int maxMessageLength)
124 {
125 this.maxMessageLength = maxMessageLength;
126 }
127
128 }