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.transport.vmpipe;
21  
22  import java.io.IOException;
23  import java.net.SocketAddress;
24  import java.util.HashSet;
25  import java.util.Set;
26  import java.util.concurrent.Executor;
27  
28  import org.apache.mina.core.filterchain.IoFilterChain;
29  import org.apache.mina.core.future.ConnectFuture;
30  import org.apache.mina.core.future.DefaultConnectFuture;
31  import org.apache.mina.core.future.IoFuture;
32  import org.apache.mina.core.future.IoFutureListener;
33  import org.apache.mina.core.service.AbstractIoConnector;
34  import org.apache.mina.core.service.IoHandler;
35  import org.apache.mina.core.service.TransportMetadata;
36  import org.apache.mina.core.session.IdleStatusChecker;
37  import org.apache.mina.core.session.IoSessionInitializer;
38  import org.apache.mina.util.ExceptionMonitor;
39  
40  /**
41   * Connects to {@link IoHandler}s which is bound on the specified
42   * {@link VmPipeAddress}.
43   *
44   * @author The Apache MINA Project (dev@mina.apache.org)
45   * @version $Rev: 713957 $, $Date: 2008-11-14 10:27:16 +0100 (Fri, 14 Nov 2008) $
46   */
47  public final class VmPipeConnector extends AbstractIoConnector {
48  
49  	// object used for checking session idle
50  	private IdleStatusChecker idleChecker;
51  	
52      /**
53       * Creates a new instance.
54       */
55      public VmPipeConnector() {
56          this(null);
57      }
58      
59      /**
60       * Creates a new instance.
61       */
62      public VmPipeConnector(Executor executor) {
63          super(new DefaultVmPipeSessionConfig(), executor);
64          idleChecker = new IdleStatusChecker();
65          // we schedule the idle status checking task in this service exceutor
66          // it will be woke up every seconds
67          executeWorker(idleChecker.getNotifyingTask(), "idleStatusChecker");
68      }
69  
70      public TransportMetadata getTransportMetadata() {
71          return VmPipeSession.METADATA;
72      }
73  
74      @Override
75      public VmPipeSessionConfig getSessionConfig() {
76          return (VmPipeSessionConfig) super.getSessionConfig();
77      }
78  
79      @Override
80      protected ConnectFuture connect0(SocketAddress remoteAddress,
81                                        SocketAddress localAddress,
82                                        IoSessionInitializer<? extends ConnectFuture> sessionInitializer) {
83          VmPipe entry = VmPipeAcceptor.boundHandlers.get(remoteAddress);
84          if (entry == null) {
85              return DefaultConnectFuture.newFailedFuture(new IOException(
86                      "Endpoint unavailable: " + remoteAddress));
87          }
88  
89          DefaultConnectFuture future = new DefaultConnectFuture();
90  
91          // Assign the local address dynamically,
92          VmPipeAddress actualLocalAddress;
93          try {
94              actualLocalAddress = nextLocalAddress();
95          } catch (IOException e) {
96              return DefaultConnectFuture.newFailedFuture(e);
97          }
98  
99          VmPipeSession localSession = new VmPipeSession(this,
100                 getListeners(), actualLocalAddress, getHandler(), entry);
101 
102         finishSessionInitialization(localSession, future, sessionInitializer);
103 
104         // and reclaim the local address when the connection is closed.
105         localSession.getCloseFuture().addListener(LOCAL_ADDRESS_RECLAIMER);
106 
107         // initialize connector session
108         try {
109             IoFilterChain filterChain = localSession.getFilterChain();
110             this.getFilterChainBuilder().buildFilterChain(filterChain);
111 
112             // The following sentences don't throw any exceptions.
113             getListeners().fireSessionCreated(localSession);
114             idleChecker.addSession(localSession);
115         } catch (Throwable t) {
116             future.setException(t);
117             return future;
118         }
119 
120         // initialize acceptor session
121         VmPipeSession remoteSession = localSession.getRemoteSession();
122         ((VmPipeAcceptor) remoteSession.getService()).doFinishSessionInitialization(remoteSession, null);
123         try {
124             IoFilterChain filterChain = remoteSession.getFilterChain();
125             entry.getAcceptor().getFilterChainBuilder().buildFilterChain(
126                     filterChain);
127 
128             // The following sentences don't throw any exceptions.
129             entry.getListeners().fireSessionCreated(remoteSession);
130             idleChecker.addSession(remoteSession);
131         } catch (Throwable t) {
132             ExceptionMonitor.getInstance().exceptionCaught(t);
133             remoteSession.close(true);
134         }
135 
136         // Start chains, and then allow and messages read/written to be processed. This is to ensure that
137         // sessionOpened gets received before a messageReceived
138         ((VmPipeFilterChain) localSession.getFilterChain()).start();
139         ((VmPipeFilterChain) remoteSession.getFilterChain()).start();
140 
141         return future;
142     }
143 
144     @Override
145     protected IoFuture dispose0() throws Exception {
146     	// stop the idle checking task
147     	idleChecker.getNotifyingTask().cancel();
148         return null;
149     }
150 
151     private static final Set<VmPipeAddress> TAKEN_LOCAL_ADDRESSES = new HashSet<VmPipeAddress>();
152 
153     private static int nextLocalPort = -1;
154 
155     private static final IoFutureListener<IoFuture> LOCAL_ADDRESS_RECLAIMER = new LocalAddressReclaimer();
156 
157     private static VmPipeAddress nextLocalAddress() throws IOException {
158         synchronized (TAKEN_LOCAL_ADDRESSES) {
159             if (nextLocalPort >= 0) {
160                 nextLocalPort = -1;
161             }
162             for (int i = 0; i < Integer.MAX_VALUE; i++) {
163                 VmPipeAddress answer = new VmPipeAddress(nextLocalPort--);
164                 if (!TAKEN_LOCAL_ADDRESSES.contains(answer)) {
165                     TAKEN_LOCAL_ADDRESSES.add(answer);
166                     return answer;
167                 }
168             }
169         }
170 
171         throw new IOException("Can't assign a local VM pipe port.");
172     }
173 
174     private static class LocalAddressReclaimer implements IoFutureListener<IoFuture> {
175         public void operationComplete(IoFuture future) {
176             synchronized (TAKEN_LOCAL_ADDRESSES) {
177                 TAKEN_LOCAL_ADDRESSES.remove(future.getSession()
178                         .getLocalAddress());
179             }
180         }
181     }
182 }