001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 *
019 */
020package org.apache.mina.example.proxy;
021
022import java.net.SocketAddress;
023
024import org.apache.mina.core.RuntimeIoException;
025import org.apache.mina.core.future.ConnectFuture;
026import org.apache.mina.core.future.IoFutureListener;
027import org.apache.mina.core.service.IoConnector;
028import org.apache.mina.core.session.IoSession;
029
030/**
031 * Handles the client to proxy part of the proxied connection.
032 *
033 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
034 */
035public class ClientToProxyIoHandler extends AbstractProxyIoHandler {
036    private final ServerToProxyIoHandler connectorHandler = new ServerToProxyIoHandler();
037
038    private final IoConnector connector;
039
040    private final SocketAddress remoteAddress;
041
042    public ClientToProxyIoHandler(IoConnector connector,
043            SocketAddress remoteAddress) {
044        this.connector = connector;
045        this.remoteAddress = remoteAddress;
046        connector.setHandler(connectorHandler);
047    }
048
049    @Override
050    public void sessionOpened(final IoSession session) throws Exception {
051
052        connector.connect(remoteAddress).addListener(new IoFutureListener<ConnectFuture>() {
053            public void operationComplete(ConnectFuture future) {
054                try {
055                    future.getSession().setAttribute(OTHER_IO_SESSION, session);
056                    session.setAttribute(OTHER_IO_SESSION, future.getSession());
057                    IoSession session2 = future.getSession();
058                    session2.resumeRead();
059                    session2.resumeWrite();
060                } catch (RuntimeIoException e) {
061                    // Connect failed
062                    session.close(true);
063                } finally {
064                    session.resumeRead();
065                    session.resumeWrite();
066                }
067            }
068        });
069    }
070}