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.nio.charset.Charset;
023
024import org.apache.mina.core.buffer.IoBuffer;
025import org.apache.mina.core.service.IoHandlerAdapter;
026import org.apache.mina.core.session.IoSession;
027import org.slf4j.Logger;
028import org.slf4j.LoggerFactory;
029
030/**
031 * Base class of {@link org.apache.mina.core.service.IoHandler} classes which handle
032 * proxied connections.
033 *
034 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
035 */
036public abstract class AbstractProxyIoHandler extends IoHandlerAdapter {
037    private static final Charset CHARSET = Charset.forName("iso8859-1");
038    public static final String OTHER_IO_SESSION = AbstractProxyIoHandler.class.getName()+".OtherIoSession";
039
040    private final static Logger LOGGER = LoggerFactory.getLogger(AbstractProxyIoHandler.class);
041    
042    /**
043     * {@inheritDoc}
044     */
045    @Override
046    public void sessionCreated(IoSession session) throws Exception {
047        session.suspendRead();
048        session.suspendWrite();
049    }
050
051    /**
052     * {@inheritDoc}
053     */
054    @Override
055    public void sessionClosed(IoSession session) throws Exception {
056        if (session.getAttribute( OTHER_IO_SESSION ) != null) {
057            IoSession sess = (IoSession) session.getAttribute(OTHER_IO_SESSION);
058            sess.setAttribute(OTHER_IO_SESSION, null);
059            sess.closeOnFlush();
060            session.setAttribute(OTHER_IO_SESSION, null);
061        }
062    }
063
064    /**
065     * {@inheritDoc}
066     */
067    @Override
068    public void messageReceived(IoSession session, Object message)
069            throws Exception {
070        IoBuffer rb = (IoBuffer) message;
071        IoBuffer wb = IoBuffer.allocate(rb.remaining());
072        rb.mark();
073        wb.put(rb);
074        wb.flip();
075        ((IoSession) session.getAttribute(OTHER_IO_SESSION)).write(wb);
076        rb.reset();
077        LOGGER.info(rb.getString(CHARSET.newDecoder()));
078    }
079}