View Javadoc

1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *  
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *  
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License. 
18   *  
19   */
20  package org.apache.mina.filter;
21  
22  import java.util.Iterator;
23  import java.util.List;
24  
25  import org.apache.mina.common.ByteBuffer;
26  import org.apache.mina.common.DefaultIoFilterChainBuilder;
27  import org.apache.mina.common.IoFilterAdapter;
28  import org.apache.mina.common.IoFilterChain;
29  import org.apache.mina.common.IoSession;
30  import org.apache.mina.filter.executor.ExecutorFilter;
31  
32  /**
33   * This filter will automatically disable reads on an <code>IoSession</code> once the data
34   * batched for that session in the {@link ExecutorFilter} reaches a defined threshold (the
35   * default is 1 megabytes). It accomplishes this by being in the filter chain before
36   * <strong>and</strong> after the {@link ExecutorFilter}. It is possible to subvert the
37   * behavior of this filter by adding filters immediately after the {@link ExecutorFilter}
38   * after adding this filter. Thus, it is recommended to add this filter towards the end of
39   * your filter chain construction, if you need to ensure that other filters need to be right
40   * after the {@link ExecutorFilter}
41   *
42   * <p>Usage:
43   *
44   * <pre><code>
45   * DefaultFilterChainBuilder builder = ...
46   * ReadThrottleFilterBuilder filter = new ReadThrottleFilterBuilder();
47   * filter.attach( builder );
48   * </code></pre>
49   *
50   * or
51   *
52   * <pre><code>
53   * IoFilterChain chain = ...
54   * ReadThrottleFilterBuilder filter = new ReadThrottleFilterBuilder();
55   * filter.attach( chain );
56   * </code></pre>
57   *
58   * @author The Apache Directory Project (mina-dev@directory.apache.org)
59   * @version $Rev: 406554 $, $Date: 2006-05-15 06:46:02Z $
60   */
61  public class ReadThrottleFilterBuilder {
62      public static final String COUNTER = ReadThrottleFilterBuilder.class
63              .getName()
64              + ".counter";
65  
66      public static final String SUSPENDED_READS = ReadThrottleFilterBuilder.class
67              .getName()
68              + ".suspendedReads";
69  
70      private volatile int maximumConnectionBufferSize = 1024 * 1024; // 1mb
71  
72      /**
73       * Set the maximum amount of data to buffer in the ThreadPoolFilter prior to disabling
74       * reads. Changing the value will only take effect when new data is received for a
75       * connection, including existing connections. Default value is 1 megabytes.
76       *
77       * @param maximumConnectionBufferSize New buffer size. Must be > 0
78       */
79      public void setMaximumConnectionBufferSize(int maximumConnectionBufferSize) {
80          this.maximumConnectionBufferSize = maximumConnectionBufferSize;
81      }
82  
83      /**
84       * Attach this filter to the specified filter chain. It will search for the ThreadPoolFilter, and attach itself
85       * before and after that filter.
86       *
87       * @param chain {@link IoFilterChain} to attach self to.
88       */
89      public void attach(IoFilterChain chain) {
90          String name = getThreadPoolFilterEntryName(chain.getAll());
91  
92          chain.addBefore(name, getClass().getName() + ".add", new Add());
93          chain.addAfter(name, getClass().getName() + ".release", new Release());
94      }
95  
96      /**
97       * Attach this filter to the specified builder. It will search for the
98       * {@link ExecutorFilter}, and attach itself before and after that filter.
99       *
100      * @param builder {@link DefaultIoFilterChainBuilder} to attach self to.
101      */
102     public void attach(DefaultIoFilterChainBuilder builder) {
103         String name = getThreadPoolFilterEntryName(builder.getAll());
104 
105         builder.addBefore(name, getClass().getName() + ".add", new Add());
106         builder
107                 .addAfter(name, getClass().getName() + ".release",
108                         new Release());
109     }
110 
111     private String getThreadPoolFilterEntryName(List entries) {
112         Iterator i = entries.iterator();
113 
114         while (i.hasNext()) {
115             IoFilterChain.Entry entry = (IoFilterChain.Entry) i.next();
116 
117             if (entry.getFilter().getClass().isAssignableFrom(
118                     ExecutorFilter.class)) {
119                 return entry.getName();
120             }
121         }
122 
123         throw new IllegalStateException(
124                 "Chain does not contain a ExecutorFilter");
125     }
126 
127     private void add(IoSession session, int size) {
128         synchronized (session) {
129             int counter = getCounter(session) + size;
130 
131             session.setAttribute(COUNTER, new Integer(counter));
132 
133             if (counter >= maximumConnectionBufferSize
134                     && session.getTrafficMask().isReadable()) {
135                 session.suspendRead();
136                 session.setAttribute(SUSPENDED_READS);
137             }
138         }
139     }
140 
141     private void release(IoSession session, int size) {
142         synchronized (session) {
143             int counter = Math.max(0, getCounter(session) - size);
144 
145             session.setAttribute(COUNTER, new Integer(counter));
146 
147             if (counter < maximumConnectionBufferSize
148                     && isSuspendedReads(session)) {
149                 session.resumeRead();
150                 session.removeAttribute(SUSPENDED_READS);
151             }
152 
153         }
154     }
155 
156     private boolean isSuspendedReads(IoSession session) {
157         Boolean flag = (Boolean) session.getAttribute(SUSPENDED_READS);
158 
159         return null != flag && flag.booleanValue();
160     }
161 
162     private int getCounter(IoSession session) {
163         Integer i = (Integer) session.getAttribute(COUNTER);
164         return null == i ? 0 : i.intValue();
165     }
166 
167     private class Add extends IoFilterAdapter {
168         public void messageReceived(NextFilter nextFilter, IoSession session,
169                 Object message) throws Exception {
170             if (message instanceof ByteBuffer) {
171                 add(session, ((ByteBuffer) message).remaining());
172             }
173 
174             nextFilter.messageReceived(session, message);
175         }
176     }
177 
178     private class Release extends IoFilterAdapter {
179         public void messageReceived(NextFilter nextFilter, IoSession session,
180                 Object message) throws Exception {
181             if (message instanceof ByteBuffer) {
182                 release(session, ((ByteBuffer) message).remaining());
183             }
184 
185             nextFilter.messageReceived(session, message);
186         }
187     }
188 }