01: /*
02: * Copyright 1999,2004 The Apache Software Foundation.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.apache.catalina.cluster.io;
18:
19: /**
20: * The object reader object is an object used in conjunction with
21: * java.nio TCP messages. This object stores the message bytes in a
22: * <code>XByteBuffer</code> until a full package has been received.
23: * When a full package has been received, the append method will call messageDataReceived
24: * on the callback object associated with this object reader.<BR>
25: * This object uses an XByteBuffer which is an extendable object buffer that also allows
26: * for message encoding and decoding.
27: *
28: * @author Filip Hanik
29: * @version $Revision: 1.5 $, $Date: 2004/02/27 14:58:55 $
30: */
31:
32: import java.nio.channels.SocketChannel;
33: import java.nio.channels.Selector;
34: import java.nio.ByteBuffer;
35: import java.io.IOException;
36: import org.apache.catalina.cluster.io.XByteBuffer;
37:
38: public class ObjectReader {
39: private SocketChannel channel;
40: private Selector selector;
41: private ListenCallback callback;
42: private XByteBuffer buffer;
43:
44: public ObjectReader(SocketChannel channel, Selector selector,
45: ListenCallback callback) {
46: this .channel = channel;
47: this .selector = selector;
48: this .callback = callback;
49: this .buffer = new XByteBuffer();
50: }
51:
52: public SocketChannel getChannel() {
53: return this .channel;
54: }
55:
56: public int append(byte[] data, int off, int len)
57: throws java.io.IOException {
58: boolean result = false;
59: buffer.append(data, off, len);
60: int pkgCnt = buffer.countPackages();
61: return pkgCnt;
62: }
63:
64: public int execute() throws java.io.IOException {
65: int pkgCnt = 0;
66: boolean pkgExists = buffer.doesPackageExist();
67: while (pkgExists) {
68: byte[] b = buffer.extractPackage(true);
69: callback.messageDataReceived(b);
70: pkgCnt++;
71: pkgExists = buffer.doesPackageExist();
72: }//end if
73: return pkgCnt;
74: }
75:
76: public int write(ByteBuffer buf) throws java.io.IOException {
77: return getChannel().write(buf);
78: }
79:
80: }
|