KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > net > protocol > transport > WireProtocolAdaptorImpl


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.net.protocol.transport;
5
6 import com.tc.bytes.TCByteBuffer;
7 import com.tc.logging.TCLogger;
8 import com.tc.logging.TCLogging;
9 import com.tc.net.core.TCConnection;
10 import com.tc.net.protocol.AbstractTCNetworkHeader;
11 import com.tc.net.protocol.AbstractTCProtocolAdaptor;
12 import com.tc.net.protocol.TCNetworkHeader;
13 import com.tc.net.protocol.TCNetworkMessage;
14 import com.tc.net.protocol.TCProtocolException;
15
16 /**
17  * Connection adaptor to parse wire protocol messages
18  *
19  * @author teck
20  */

21 public class WireProtocolAdaptorImpl extends AbstractTCProtocolAdaptor implements WireProtocolAdaptor {
22   private static final TCLogger logger = TCLogging.getLogger(WireProtocolAdaptorImpl.class);
23
24   private final WireProtocolMessageSink sink;
25
26   protected WireProtocolAdaptorImpl(WireProtocolMessageSink sink) {
27     super(logger);
28     this.sink = sink;
29   }
30
31   public void addReadData(TCConnection source, TCByteBuffer[] data, int length) throws TCProtocolException {
32     final boolean msgDone = this.processIncomingData(source, data, length);
33
34     if (msgDone) {
35       try {
36         WireProtocolMessage msg = getWireProtocolMessage();
37         // TODO: validate the src/dest IP and port in header against the connection it came in on
38

39         if (logger.isDebugEnabled()) {
40           logger.debug("\nRECEIVE\n" + msg.toString());
41         }
42
43         sink.putMessage(msg);
44       } finally {
45         init();
46       }
47     }
48
49     return;
50   }
51
52   protected AbstractTCNetworkHeader getNewProtocolHeader() {
53     return new WireProtocolHeader();
54   }
55
56   private WireProtocolMessage getWireProtocolMessage() {
57     WireProtocolMessage rv = (WireProtocolMessage) collectMessage();
58     return rv;
59   }
60
61   protected int computeDataLength(TCNetworkHeader header) {
62     WireProtocolHeader wph = (WireProtocolHeader) header;
63     return wph.getTotalPacketLength() - wph.getHeaderByteLength();
64   }
65
66   protected TCNetworkMessage createMessage(TCConnection source, TCNetworkHeader hdr, TCByteBuffer[] data)
67       throws TCProtocolException {
68     if (data == null) { throw new TCProtocolException("Wire protocol messages must have a payload"); }
69     WireProtocolHeader wph = (WireProtocolHeader) hdr;
70     final WireProtocolMessage rv;
71
72     if (wph.isTransportHandshakeMessage()) {
73       rv = new TransportHandshakeMessageImpl(source, wph, data);
74     } else {
75       rv = new WireProtocolMessageImpl(source, wph, data);
76     }
77
78     return rv;
79   }
80 }
Popular Tags