1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.io;
20
21 import java.io.IOException;
22 import java.nio.ByteBuffer;
23 import java.nio.channels.SelectionKey;
24 import java.nio.channels.SocketChannel;
25 import java.util.List;
26
27 import org.eclipse.jetty.util.log.Log;
28 import org.eclipse.jetty.util.log.Logger;
29 import org.eclipse.jetty.util.thread.Scheduler;
30
31 public class NetworkTrafficSelectChannelEndPoint extends SelectChannelEndPoint
32 {
33 private static final Logger LOG = Log.getLogger(NetworkTrafficSelectChannelEndPoint.class);
34
35 private final List<NetworkTrafficListener> listeners;
36
37 public NetworkTrafficSelectChannelEndPoint(SocketChannel channel, SelectorManager.ManagedSelector selectSet, SelectionKey key, Scheduler scheduler, long idleTimeout, List<NetworkTrafficListener> listeners) throws IOException
38 {
39 super(channel, selectSet, key, scheduler, idleTimeout);
40 this.listeners = listeners;
41 }
42
43 @Override
44 public int fill(ByteBuffer buffer) throws IOException
45 {
46 int read = super.fill(buffer);
47 notifyIncoming(buffer, read);
48 return read;
49 }
50
51 @Override
52 public boolean flush(ByteBuffer... buffers) throws IOException
53 {
54 boolean flushed=true;
55 for (ByteBuffer b : buffers)
56 {
57 if (b.hasRemaining())
58 {
59 int position = b.position();
60 flushed&=super.flush(b);
61 int l=b.position()-position;
62 notifyOutgoing(b, position, l);
63 if (!flushed)
64 break;
65 }
66 }
67 return flushed;
68 }
69
70
71 public void notifyOpened()
72 {
73 if (listeners != null && !listeners.isEmpty())
74 {
75 for (NetworkTrafficListener listener : listeners)
76 {
77 try
78 {
79 listener.opened(getSocket());
80 }
81 catch (Exception x)
82 {
83 LOG.warn(x);
84 }
85 }
86 }
87 }
88
89 public void notifyIncoming(ByteBuffer buffer, int read)
90 {
91 if (listeners != null && !listeners.isEmpty() && read > 0)
92 {
93 for (NetworkTrafficListener listener : listeners)
94 {
95 try
96 {
97 ByteBuffer view = buffer.asReadOnlyBuffer();
98 listener.incoming(getSocket(), view);
99 }
100 catch (Exception x)
101 {
102 LOG.warn(x);
103 }
104 }
105 }
106 }
107
108 public void notifyOutgoing(ByteBuffer buffer, int position, int written)
109 {
110 if (listeners != null && !listeners.isEmpty() && written > 0)
111 {
112 for (NetworkTrafficListener listener : listeners)
113 {
114 try
115 {
116 ByteBuffer view = buffer.slice();
117 view.position(position);
118 view.limit(position + written);
119 listener.outgoing(getSocket(), view);
120 }
121 catch (Exception x)
122 {
123 LOG.warn(x);
124 }
125 }
126 }
127 }
128
129 public void notifyClosed()
130 {
131 if (listeners != null && !listeners.isEmpty())
132 {
133 for (NetworkTrafficListener listener : listeners)
134 {
135 try
136 {
137 listener.closed(getSocket());
138 }
139 catch (Exception x)
140 {
141 LOG.warn(x);
142 }
143 }
144 }
145 }
146 }