View Javadoc

1   // ========================================================================
2   // Copyright (c) 2011 Intalio, Inc.
3   // ------------------------------------------------------------------------
4   // All rights reserved. This program and the accompanying materials
5   // are made available under the terms of the Eclipse Public License v1.0
6   // and Apache License v2.0 which accompanies this distribution.
7   // The Eclipse Public License is available at
8   // http://www.eclipse.org/legal/epl-v10.html
9   // The Apache License v2.0 is available at
10  // http://www.opensource.org/licenses/apache2.0.php
11  // You may elect to redistribute this code under either of these licenses.
12  // ========================================================================
13  
14  package org.eclipse.jetty.server.nio;
15  
16  import java.io.IOException;
17  import java.nio.channels.SelectionKey;
18  import java.nio.channels.SocketChannel;
19  import java.util.ConcurrentModificationException;
20  import java.util.List;
21  import java.util.concurrent.CopyOnWriteArrayList;
22  
23  import org.eclipse.jetty.io.NetworkTrafficListener;
24  import org.eclipse.jetty.io.nio.NetworkTrafficSelectChannelEndPoint;
25  import org.eclipse.jetty.io.nio.SelectChannelEndPoint;
26  import org.eclipse.jetty.io.nio.SelectorManager;
27  
28  /**
29   * <p>A specialized version of {@link SelectChannelConnector} that supports {@link NetworkTrafficListener}s.</p>
30   * <p>{@link NetworkTrafficListener}s can be added and removed dynamically before and after this connector has
31   * been started without causing {@link ConcurrentModificationException}s.</p>
32   */
33  public class NetworkTrafficSelectChannelConnector extends SelectChannelConnector
34  {
35      private final List<NetworkTrafficListener> listeners = new CopyOnWriteArrayList<NetworkTrafficListener>();
36  
37      /**
38       * @param listener the listener to add
39       */
40      public void addNetworkTrafficListener(NetworkTrafficListener listener)
41      {
42          listeners.add(listener);
43      }
44  
45      /**
46       * @param listener the listener to remove
47       */
48      public void removeNetworkTrafficListener(NetworkTrafficListener listener)
49      {
50          listeners.remove(listener);
51      }
52  
53      @Override
54      protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectorManager.SelectSet selectSet, SelectionKey key) throws IOException
55      {
56          NetworkTrafficSelectChannelEndPoint endPoint = new NetworkTrafficSelectChannelEndPoint(channel, selectSet, key, _maxIdleTime, listeners);
57          endPoint.notifyOpened();
58          return endPoint;
59      }
60  
61      @Override
62      protected void endPointClosed(SelectChannelEndPoint endpoint)
63      {
64          super.endPointClosed(endpoint);
65          ((NetworkTrafficSelectChannelEndPoint)endpoint).notifyClosed();
66      }
67  }