1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.transport.vmpipe;
21
22 import java.io.IOException;
23 import java.net.SocketAddress;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.Map;
27
28 import org.apache.mina.common.IoHandler;
29 import org.apache.mina.common.IoServiceConfig;
30 import org.apache.mina.common.IoSessionConfig;
31 import org.apache.mina.common.support.BaseIoAcceptor;
32 import org.apache.mina.common.support.BaseIoAcceptorConfig;
33 import org.apache.mina.common.support.BaseIoSessionConfig;
34 import org.apache.mina.transport.vmpipe.support.VmPipe;
35
36
37
38
39
40
41
42
43 public class VmPipeAcceptor extends BaseIoAcceptor {
44 static final Map<SocketAddress, VmPipe> boundHandlers = new HashMap<SocketAddress, VmPipe>();
45
46 private static final IoSessionConfig CONFIG = new BaseIoSessionConfig() {
47 };
48
49 private final IoServiceConfig defaultConfig = new BaseIoAcceptorConfig() {
50 public IoSessionConfig getSessionConfig() {
51 return CONFIG;
52 }
53 };
54
55 public void bind(SocketAddress address, IoHandler handler,
56 IoServiceConfig config) throws IOException {
57 if (handler == null)
58 throw new NullPointerException("handler");
59 if (address != null && !(address instanceof VmPipeAddress))
60 throw new IllegalArgumentException("address must be VmPipeAddress.");
61
62 if (config == null) {
63 config = getDefaultConfig();
64 }
65
66 synchronized (boundHandlers) {
67 if (address == null || ((VmPipeAddress) address).getPort() == 0) {
68 for (int i = 1; i < Integer.MAX_VALUE; i++) {
69 address = new VmPipeAddress(i);
70 if (!boundHandlers.containsKey(address)) {
71 break;
72 }
73 }
74 } else if (boundHandlers.containsKey(address)) {
75 throw new IOException("Address already bound: " + address);
76 }
77
78 boundHandlers.put(address, new VmPipe(this,
79 (VmPipeAddress) address, handler, config, getListeners()));
80 }
81
82 getListeners().fireServiceActivated(this, address, handler, config);
83 }
84
85 public void unbind(SocketAddress address) {
86 if (address == null)
87 throw new NullPointerException("address");
88
89 VmPipe pipe;
90 synchronized (boundHandlers) {
91 if (!boundHandlers.containsKey(address)) {
92 throw new IllegalArgumentException("Address not bound: "
93 + address);
94 }
95
96 pipe = boundHandlers.remove(address);
97 }
98
99 getListeners().fireServiceDeactivated(this, pipe.getAddress(),
100 pipe.getHandler(), pipe.getConfig());
101 }
102
103 public void unbindAll() {
104 synchronized (boundHandlers) {
105 for (SocketAddress address : new ArrayList<SocketAddress>(
106 boundHandlers.keySet())) {
107 unbind(address);
108 }
109 }
110 }
111
112 public IoServiceConfig getDefaultConfig() {
113 return defaultConfig;
114 }
115 }