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 org.apache.camel.CamelExchangeException;
020    import org.apache.camel.Exchange;
021    import org.apache.commons.logging.Log;
022    import org.apache.commons.logging.LogFactory;
023    import org.apache.mina.common.IoSession;
024    import org.apache.mina.common.WriteFuture;
025    
026    /**
027     * Helper class used internally by camel-mina using Apache MINA.
028     */
029    public final class MinaHelper {
030    
031        private static final transient Log LOG = LogFactory.getLog(MinaHelper.class);
032    
033        private MinaHelper() {
034            //Utility Class
035        }
036    
037        /**
038         * Writes the given body to MINA session. Will wait until the body has been written.
039         *
040         * @param session  the MINA session
041         * @param body     the body to write (send)
042         * @param exchange the exchange
043         * @throws CamelExchangeException is thrown if the body could not be written for some reasons
044         *                                (eg remote connection is closed etc.)
045         */
046        public static void writeBody(IoSession session, Object body, Exchange exchange) throws CamelExchangeException {
047            // the write operation is asynchronous. Use WriteFuture to wait until the session has been written
048            WriteFuture future = session.write(body);
049            // must use a timeout (we use 10s) as in some very high performance scenarios a write can cause 
050            // thread hanging forever
051            if (LOG.isTraceEnabled()) {
052                LOG.trace("Waiting for write to complete");
053            }
054            future.join(10 * 1000L);
055            if (!future.isWritten()) {
056                LOG.warn("Cannot write body: " + body + " using session: " + session);
057                throw new CamelExchangeException("Cannot write body", exchange);
058            }
059        }
060    
061    }