View Javadoc

1   /*
2    *  Copyright 2006 Simon Raess
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package net.sf.beep4j.internal;
17  
18  import java.util.HashMap;
19  import java.util.Map;
20  
21  import net.sf.beep4j.internal.util.Assert;
22  
23  /**
24   * FrameHandler implementation that delegates to a unique {@link FrameHandler}
25   * per channel. It uses
26   * 
27   * @author Simon Raess
28   */
29  public class DelegatingFrameHandler implements FrameHandler, SessionListener {
30  	
31  	private final FrameHandlerFactory factory;
32  	
33  	private final Map<Integer, FrameHandler> handlers = new HashMap<Integer, FrameHandler>();
34  	
35  	public DelegatingFrameHandler(FrameHandlerFactory factory) {
36  		Assert.notNull("factory", factory);
37  		this.factory = factory;
38  	}
39  	
40  	public void handleFrame(Frame frame) {
41  		FrameHandler handler = handlers.get(frame.getChannelNumber());
42  		if (handler == null) {
43  			throw new IllegalStateException("there must be a FrameHandler for channel "
44  					+ frame.getChannelNumber() + "; channelStarted was not called");
45  		}
46  		handler.handleFrame(frame);
47  	}
48  	
49  	public void channelStarted(int channelNumber) {
50  		FrameHandler handler = factory.createFrameHandler();
51  		handlers.put(channelNumber, handler);
52  	}
53  	
54  	public void channelClosed(int channelNumber) {
55  		handlers.remove(channelNumber);
56  	}
57  	
58  }