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.netty; 018 019 import java.net.SocketAddress; 020 021 import org.apache.camel.CamelExchangeException; 022 import org.apache.camel.Exchange; 023 import org.apache.commons.logging.Log; 024 import org.apache.commons.logging.LogFactory; 025 import org.jboss.netty.channel.Channel; 026 import org.jboss.netty.channel.ChannelFuture; 027 028 /** 029 * Helper class used internally by camel-netty using Netty. 030 * 031 * @version $Revision: 941713 $ 032 */ 033 public final class NettyHelper { 034 035 private static final transient Log LOG = LogFactory.getLog(NettyHelper.class); 036 037 private NettyHelper() { 038 // Utility class 039 } 040 041 /** 042 * Writes the given body to Netty channel. Will wait until the body has been written. 043 * 044 * @param channel the Netty channel 045 * @param body the body to write (send) 046 * @param exchange the exchange 047 * @throws CamelExchangeException is thrown if the body could not be written for some reasons 048 * (eg remote connection is closed etc.) 049 */ 050 public static void writeBody(Channel channel, SocketAddress remoteAddress, Object body, Exchange exchange) throws CamelExchangeException { 051 // the write operation is asynchronous. Use future to wait until the session has been written 052 ChannelFuture future; 053 if (remoteAddress != null) { 054 future = channel.write(body, remoteAddress); 055 } else { 056 future = channel.write(body); 057 } 058 059 // wait for the write 060 if (LOG.isTraceEnabled()) { 061 LOG.trace("Waiting for write to complete"); 062 } 063 future.awaitUninterruptibly(); 064 065 // if it was not a success then thrown an exception 066 if (!future.isSuccess()) { 067 LOG.warn("Cannot write body: " + body + " using channel: " + channel); 068 throw new CamelExchangeException("Cannot write body", exchange, future.getCause()); 069 } 070 } 071 072 public static void close(Channel channel) { 073 if (channel != null) { 074 if (LOG.isTraceEnabled()) { 075 LOG.trace("Closing channel: " + channel); 076 } 077 channel.close().awaitUninterruptibly(); 078 } 079 } 080 081 }