1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.codec.oneone;
17
18 import org.jboss.netty.buffer.ChannelBuffers;
19 import org.jboss.netty.channel.Channel;
20 import org.jboss.netty.channel.ChannelDownstreamHandler;
21 import org.jboss.netty.channel.ChannelEvent;
22 import org.jboss.netty.channel.ChannelHandlerContext;
23 import org.jboss.netty.channel.ChannelPipeline;
24 import org.jboss.netty.channel.MessageEvent;
25 import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
26 import org.jboss.netty.handler.codec.frame.Delimiters;
27
28 import static org.jboss.netty.channel.Channels.*;
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 public abstract class OneToOneEncoder implements ChannelDownstreamHandler {
47
48 protected OneToOneEncoder() {
49 }
50
51 public void handleDownstream(
52 ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
53 if (!(evt instanceof MessageEvent)) {
54 ctx.sendDownstream(evt);
55 return;
56 }
57
58 MessageEvent e = (MessageEvent) evt;
59 if (!doEncode(ctx, e)) {
60 ctx.sendDownstream(e);
61 }
62 }
63
64 protected boolean doEncode(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
65 Object originalMessage = e.getMessage();
66 Object encodedMessage = encode(ctx, e.getChannel(), originalMessage);
67 if (originalMessage == encodedMessage) {
68 return false;
69 }
70 if (encodedMessage != null) {
71 write(ctx, e.getFuture(), encodedMessage, e.getRemoteAddress());
72 }
73 return true;
74 }
75
76
77
78
79
80
81
82 protected abstract Object encode(
83 ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception;
84 }