001    /**
002     *
003     * Licensed to the Apache Software Foundation (ASF) under one or more
004     * contributor license agreements.  See the NOTICE file distributed with
005     * this work for additional information regarding copyright ownership.
006     * The ASF licenses this file to You under the Apache License, Version 2.0
007     * (the "License"); you may not use this file except in compliance with
008     * 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, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    package org.apache.camel.component.mina;
019    
020    import org.apache.camel.Processor;
021    import org.apache.camel.impl.DefaultConsumer;
022    import org.apache.commons.logging.Log;
023    import org.apache.commons.logging.LogFactory;
024    import org.apache.mina.common.IoAcceptor;
025    import org.apache.mina.common.IoHandler;
026    import org.apache.mina.common.IoHandlerAdapter;
027    import org.apache.mina.common.IoSession;
028    
029    import java.net.SocketAddress;
030    
031    /**
032     * A @{link Consumer} for MINA
033     *
034     * @version $Revision: 534145 $
035     */
036    public class MinaConsumer extends DefaultConsumer<MinaExchange> {
037        private static final transient Log log = LogFactory.getLog(MinaConsumer.class);
038    
039        private final MinaEndpoint endpoint;
040        private final SocketAddress address;
041        private final IoAcceptor acceptor;
042    
043        public MinaConsumer(final MinaEndpoint endpoint, Processor processor) {
044            super(endpoint, processor);
045            this.endpoint = endpoint;
046             address = endpoint.getAddress();
047             acceptor = endpoint.getAcceptor();
048        }
049    
050        @Override
051        protected void doStart() throws Exception {
052    
053            if (log.isDebugEnabled()) {
054                log.debug("Binding to server address: " + address + " using acceptor: " + acceptor);
055            }
056    
057            IoHandler handler = new IoHandlerAdapter() {
058                @Override
059                public void messageReceived(IoSession session, Object object) throws Exception {
060                    getProcessor().process(endpoint.createExchange(session, object));
061                }
062            };
063    
064            acceptor.bind(address, handler, endpoint.getConfig());
065        }
066    
067        @Override
068        protected void doStop() throws Exception {
069            acceptor.unbind(address);
070            super.doStop();
071        }
072    }