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.core.session;
21  
22  import java.io.IOException;
23  import java.net.SocketAddress;
24  import java.util.List;
25  import java.util.Set;
26  import java.util.concurrent.Executor;
27  
28  import org.apache.mina.core.file.FileRegion;
29  import org.apache.mina.core.filterchain.DefaultIoFilterChain;
30  import org.apache.mina.core.filterchain.IoFilter;
31  import org.apache.mina.core.filterchain.IoFilterChain;
32  import org.apache.mina.core.future.IoFuture;
33  import org.apache.mina.core.service.AbstractIoAcceptor;
34  import org.apache.mina.core.service.DefaultTransportMetadata;
35  import org.apache.mina.core.service.IoAcceptor;
36  import org.apache.mina.core.service.IoHandler;
37  import org.apache.mina.core.service.IoHandlerAdapter;
38  import org.apache.mina.core.service.IoProcessor;
39  import org.apache.mina.core.service.IoService;
40  import org.apache.mina.core.service.TransportMetadata;
41  import org.apache.mina.core.write.WriteRequest;
42  
43  /**
44   * A dummy {@link IoSession} for unit-testing or non-network-use of
45   * the classes that depends on {@link IoSession}.
46   *
47   * <h2>Overriding I/O request methods</h2>
48   * All I/O request methods (i.e. {@link #close()}, {@link #write(Object)} and
49   * {@link #setTrafficMask(TrafficMask)}) are final and therefore cannot be
50   * overridden, but you can always add your custom {@link IoFilter} to the
51   * {@link IoFilterChain} to intercept any I/O events and requests.
52   *
53   * @author The Apache MINA Project (dev@mina.apache.org)
54   * @version $Rev: 713957 $, $Date: 2008-11-14 10:27:16 +0100 (Fri, 14 Nov 2008) $
55   */
56  public class DummySession extends AbstractIoSession {
57  
58      private static final TransportMetadata TRANSPORT_METADATA =
59              new DefaultTransportMetadata(
60                      "mina", "dummy", false, false,
61                      SocketAddress.class, IoSessionConfig.class, Object.class);
62  
63      private static final SocketAddress ANONYMOUS_ADDRESS = new SocketAddress() {
64          private static final long serialVersionUID = -496112902353454179L;
65  
66          @Override
67          public String toString() {
68              return "?";
69          }
70      };
71  
72      private volatile IoService service;
73  
74      private volatile IoSessionConfig config = new AbstractIoSessionConfig() {
75          @Override
76          protected void doSetAll(IoSessionConfig config) {
77          }
78      };
79  
80      private final IoFilterChain filterChain = new DefaultIoFilterChain(this);
81      private final IoProcessor<AbstractIoSession> processor;
82  
83      private volatile IoHandler handler = new IoHandlerAdapter();
84      private volatile SocketAddress localAddress = ANONYMOUS_ADDRESS;
85      private volatile SocketAddress remoteAddress = ANONYMOUS_ADDRESS;
86      private volatile TransportMetadata transportMetadata = TRANSPORT_METADATA;
87  
88      /**
89       * Creates a new instance.
90       */
91      public DummySession() {
92          // Initialize dummy service.
93          IoAcceptor acceptor = new AbstractIoAcceptor(
94                  new AbstractIoSessionConfig() {
95                      @Override
96                      protected void doSetAll(IoSessionConfig config) {}
97                  },
98                  new Executor() {
99                      public void execute(Runnable command) {}
100                 }) {
101 
102             @Override
103             protected Set<SocketAddress> bind0(List<? extends SocketAddress> localAddresses) throws Exception {
104                 throw new UnsupportedOperationException();
105             }
106 
107             @Override
108             protected void unbind0(List<? extends SocketAddress> localAddresses) throws Exception {
109                 throw new UnsupportedOperationException();
110             }
111 
112             public IoSession newSession(SocketAddress remoteAddress, SocketAddress localAddress) {
113                 throw new UnsupportedOperationException();
114             }
115 
116             public TransportMetadata getTransportMetadata() {
117                 return TRANSPORT_METADATA;
118             }
119 
120             @Override
121             protected IoFuture dispose0() throws Exception {
122                 return null;
123             }
124         };
125 
126         // Set meaningless default values.
127         acceptor.setHandler(new IoHandlerAdapter());
128 
129         service = acceptor;
130 
131         processor = new IoProcessor<AbstractIoSession>() {
132             public void add(AbstractIoSession session) {
133             }
134 
135             public void flush(AbstractIoSession session) {
136                 DummySession s = (DummySession) session;
137                 WriteRequest req = s.getWriteRequestQueue().poll(session);
138                 Object m = req.getMessage();
139                 if (m instanceof FileRegion) {
140                     FileRegion file = (FileRegion) m;
141                     try {
142                         file.getFileChannel().position(file.getPosition() + file.getRemainingBytes());
143                         file.update(file.getRemainingBytes());
144                     } catch (IOException e) {
145                         s.getFilterChain().fireExceptionCaught(e);
146                     }
147                 }
148                 getFilterChain().fireMessageSent(req);
149             }
150 
151             public void remove(AbstractIoSession session) {
152             }
153 
154             public void updateTrafficControl(AbstractIoSession session) {
155             }
156 
157             public void dispose() {
158             }
159 
160             public boolean isDisposed() {
161                 return false;
162             }
163 
164             public boolean isDisposing() {
165                 return false;
166             }
167 
168         };
169 
170         try {
171             IoSessionDataStructureFactory factory = new DefaultIoSessionDataStructureFactory();
172             setAttributeMap(factory.getAttributeMap(this));
173             setWriteRequestQueue(factory.getWriteRequestQueue(this));
174         } catch (Exception e) {
175             throw new InternalError();
176         }
177     }
178 
179     public IoSessionConfig getConfig() {
180         return config;
181     }
182 
183     /**
184      * Sets the configuration of this session.
185      */
186     public void setConfig(IoSessionConfig config) {
187         if (config == null) {
188             throw new NullPointerException("config");
189         }
190 
191         this.config = config;
192     }
193 
194     public IoFilterChain getFilterChain() {
195         return filterChain;
196     }
197 
198     public IoHandler getHandler() {
199         return handler;
200     }
201 
202     /**
203      * Sets the {@link IoHandler} which handles this session.
204      */
205     public void setHandler(IoHandler handler) {
206         if (handler == null) {
207             throw new NullPointerException("handler");
208         }
209 
210         this.handler = handler;
211     }
212 
213     public SocketAddress getLocalAddress() {
214         return localAddress;
215     }
216 
217     public SocketAddress getRemoteAddress() {
218         return remoteAddress;
219     }
220 
221     /**
222      * Sets the socket address of local machine which is associated with
223      * this session.
224      */
225     public void setLocalAddress(SocketAddress localAddress) {
226         if (localAddress == null) {
227             throw new NullPointerException("localAddress");
228         }
229 
230         this.localAddress = localAddress;
231     }
232 
233     /**
234      * Sets the socket address of remote peer.
235      */
236     public void setRemoteAddress(SocketAddress remoteAddress) {
237         if (remoteAddress == null) {
238             throw new NullPointerException("remoteAddress");
239         }
240 
241         this.remoteAddress = remoteAddress;
242     }
243 
244     public IoService getService() {
245         return service;
246     }
247 
248     /**
249      * Sets the {@link IoService} which provides I/O service to this session.
250      */
251     public void setService(IoService service) {
252         if (service == null) {
253             throw new NullPointerException("service");
254         }
255 
256         this.service = service;
257     }
258 
259     @Override
260     public final IoProcessor<AbstractIoSession> getProcessor() {
261         return processor;
262     }
263 
264     public TransportMetadata getTransportMetadata() {
265         return transportMetadata;
266     }
267 
268     /**
269      * Sets the {@link TransportMetadata} that this session runs on.
270      */
271     public void setTransportMetadata(TransportMetadata transportMetadata) {
272         if (transportMetadata == null) {
273             throw new NullPointerException("transportMetadata");
274         }
275 
276         this.transportMetadata = transportMetadata;
277     }
278 
279     @Override
280     public void setScheduledWriteBytes(int byteCount){
281         super.setScheduledWriteBytes(byteCount);
282     }
283 
284     @Override
285     public void setScheduledWriteMessages(int messages) {
286         super.setScheduledWriteMessages(messages);
287     }
288 
289     /**
290      * Update all statistical properties related with throughput.  By default
291      * this method returns silently without updating the throughput properties
292      * if they were calculated already within last
293      * {@link IoSessionConfig#getThroughputCalculationInterval() calculation interval}.
294      * If, however, <tt>force</tt> is specified as <tt>true</tt>, this method
295      * updates the throughput properties immediately.
296      */
297     public void updateThroughput(boolean force) {
298         super.updateThroughput(System.currentTimeMillis(), force);
299     }
300 }