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