001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.component.mina;
018
019 import java.net.SocketAddress;
020
021 import org.apache.camel.Exchange;
022 import org.apache.camel.impl.DefaultProducer;
023 import org.apache.commons.logging.Log;
024 import org.apache.commons.logging.LogFactory;
025 import org.apache.mina.common.ConnectFuture;
026 import org.apache.mina.common.IoConnector;
027 import org.apache.mina.common.IoHandler;
028 import org.apache.mina.common.IoHandlerAdapter;
029 import org.apache.mina.common.IoSession;
030
031 /**
032 * A {@link Producer} implementation for MINA
033 *
034 * @version $Revision: 563665 $
035 */
036 public class MinaProducer extends DefaultProducer {
037 private static final transient Log LOG = LogFactory.getLog(MinaProducer.class);
038 private IoSession session;
039 private MinaEndpoint endpoint;
040
041 public MinaProducer(MinaEndpoint endpoint) {
042 super(endpoint);
043 this.endpoint = endpoint;
044 }
045
046 public void process(Exchange exchange) {
047 if (session == null) {
048 throw new IllegalStateException("Not started yet!");
049 }
050 Object body = exchange.getIn().getBody();
051 if (body == null) {
052 LOG.warn("No payload for exchange: " + exchange);
053 } else {
054 session.write(body);
055 }
056 }
057
058 @Override
059 protected void doStart() throws Exception {
060 SocketAddress address = endpoint.getAddress();
061 IoConnector connector = endpoint.getConnector();
062 if (LOG.isDebugEnabled()) {
063 LOG.debug("Creating connector to address: " + address + " using connector: " + connector);
064 }
065 IoHandler ioHandler = new IoHandlerAdapter() {
066 @Override
067 public void messageReceived(IoSession ioSession, Object object) throws Exception {
068 super.messageReceived(ioSession, object);
069 /** TODO */
070 }
071 };
072 ConnectFuture future = connector.connect(address, ioHandler, endpoint.getConfig());
073 future.join();
074 session = future.getSession();
075 }
076
077 @Override
078 protected void doStop() throws Exception {
079 if (session != null) {
080 session.close().join(2000);
081 }
082 }
083 }