camel-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ningji...@apache.org
Subject [04/12] CAMEL-6555 Created camel-netty4 module based on latest camel-netty code
Date Fri, 18 Jul 2014 15:15:31 GMT
http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/SingleUDPNettyServerBootstrapFactory.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/SingleUDPNettyServerBootstrapFactory.java b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/SingleUDPNettyServerBootstrapFactory.java
new file mode 100644
index 0000000..8c73c96
--- /dev/null
+++ b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/SingleUDPNettyServerBootstrapFactory.java
@@ -0,0 +1,195 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+import java.net.InetSocketAddress;
+import java.net.NetworkInterface;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.support.ServiceSupport;
+import org.apache.camel.util.ObjectHelper;
+import org.jboss.netty.bootstrap.ConnectionlessBootstrap;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelPipelineFactory;
+import org.jboss.netty.channel.FixedReceiveBufferSizePredictorFactory;
+import org.jboss.netty.channel.group.ChannelGroup;
+import org.jboss.netty.channel.group.ChannelGroupFuture;
+import org.jboss.netty.channel.group.DefaultChannelGroup;
+import org.jboss.netty.channel.socket.DatagramChannel;
+import org.jboss.netty.channel.socket.DatagramChannelFactory;
+import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;
+import org.jboss.netty.channel.socket.nio.NioDatagramWorkerPool;
+import org.jboss.netty.channel.socket.nio.WorkerPool;
+import org.jboss.netty.handler.ipfilter.IpV4Subnet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link NettyServerBootstrapFactory} which is used by a single consumer (not shared).
+ */
+public class SingleUDPNettyServerBootstrapFactory extends ServiceSupport implements NettyServerBootstrapFactory {
+
+    protected static final Logger LOG = LoggerFactory.getLogger(SingleUDPNettyServerBootstrapFactory.class);
+    private static final String LOOPBACK_INTERFACE = "lo";
+    private static final String MULTICAST_SUBNET = "224.0.0.0/4";
+    private final ChannelGroup allChannels;
+    private CamelContext camelContext;
+    private ThreadFactory threadFactory;
+    private NettyServerBootstrapConfiguration configuration;
+    private ChannelPipelineFactory pipelineFactory;
+    private DatagramChannelFactory datagramChannelFactory;
+    private ConnectionlessBootstrap connectionlessBootstrap;
+    private NetworkInterface multicastNetworkInterface;
+    private DatagramChannel datagramChannel;
+    private Channel channel;
+    private WorkerPool workerPool;
+
+    public SingleUDPNettyServerBootstrapFactory() {
+        this.allChannels = new DefaultChannelGroup(SingleUDPNettyServerBootstrapFactory.class.getName());
+    }
+
+    public void init(CamelContext camelContext, NettyServerBootstrapConfiguration configuration, ChannelPipelineFactory pipelineFactory) {
+        this.camelContext = camelContext;
+        this.configuration = configuration;
+        this.pipelineFactory = pipelineFactory;
+    }
+
+    public void init(ThreadFactory threadFactory, NettyServerBootstrapConfiguration configuration, ChannelPipelineFactory pipelineFactory) {
+        this.threadFactory = threadFactory;
+        this.configuration = configuration;
+        this.pipelineFactory = pipelineFactory;
+    }
+
+    public void addChannel(Channel channel) {
+        allChannels.add(channel);
+    }
+
+    public void removeChannel(Channel channel) {
+        allChannels.remove(channel);
+    }
+
+    public void addConsumer(NettyConsumer consumer) {
+        // does not allow sharing
+    }
+
+    public void removeConsumer(NettyConsumer consumer) {
+        // does not allow sharing
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        if (camelContext == null && threadFactory == null) {
+            throw new IllegalArgumentException("Either CamelContext or ThreadFactory must be set on " + this);
+        }
+        startServerBootstrap();
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        stopServerBootstrap();
+    }
+
+    @Override
+    protected void doResume() throws Exception {
+        // noop
+    }
+
+    @Override
+    protected void doSuspend() throws Exception {
+        // noop
+    }
+
+    protected void startServerBootstrap() throws Exception {
+        // create non-shared worker pool
+        int count = configuration.getWorkerCount() > 0 ? configuration.getWorkerCount() : NettyHelper.DEFAULT_IO_THREADS;
+        workerPool = new NioDatagramWorkerPool(Executors.newCachedThreadPool(), count);
+
+        datagramChannelFactory = new NioDatagramChannelFactory(workerPool);
+
+        connectionlessBootstrap = new ConnectionlessBootstrap(datagramChannelFactory);
+        connectionlessBootstrap.setOption("child.keepAlive", configuration.isKeepAlive());
+        connectionlessBootstrap.setOption("child.tcpNoDelay", configuration.isTcpNoDelay());
+        connectionlessBootstrap.setOption("reuseAddress", configuration.isReuseAddress());
+        connectionlessBootstrap.setOption("child.reuseAddress", configuration.isReuseAddress());
+        connectionlessBootstrap.setOption("child.connectTimeoutMillis", configuration.getConnectTimeout());
+        connectionlessBootstrap.setOption("child.broadcast", configuration.isBroadcast());
+        connectionlessBootstrap.setOption("sendBufferSize", configuration.getSendBufferSize());
+        connectionlessBootstrap.setOption("receiveBufferSize", configuration.getReceiveBufferSize());
+        // only set this if user has specified
+        if (configuration.getReceiveBufferSizePredictor() > 0) {
+            connectionlessBootstrap.setOption("receiveBufferSizePredictorFactory",
+                    new FixedReceiveBufferSizePredictorFactory(configuration.getReceiveBufferSizePredictor()));
+        }
+        if (configuration.getBacklog() > 0) {
+            connectionlessBootstrap.setOption("backlog", configuration.getBacklog());
+        }
+
+        // set any additional netty options
+        if (configuration.getOptions() != null) {
+            for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
+                connectionlessBootstrap.setOption(entry.getKey(), entry.getValue());
+            }
+        }
+
+        LOG.debug("Created ConnectionlessBootstrap {} with options: {}", connectionlessBootstrap, connectionlessBootstrap.getOptions());
+
+        // set the pipeline factory, which creates the pipeline for each newly created channels
+        connectionlessBootstrap.setPipelineFactory(pipelineFactory);
+
+        InetSocketAddress hostAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
+        IpV4Subnet multicastSubnet = new IpV4Subnet(MULTICAST_SUBNET);
+
+        if (multicastSubnet.contains(configuration.getHost())) {
+            datagramChannel = (DatagramChannel)connectionlessBootstrap.bind(hostAddress);
+            String networkInterface = configuration.getNetworkInterface() == null ? LOOPBACK_INTERFACE : configuration.getNetworkInterface();
+            multicastNetworkInterface = NetworkInterface.getByName(networkInterface);
+            ObjectHelper.notNull(multicastNetworkInterface, "No network interface found for '" + networkInterface + "'.");
+            LOG.info("ConnectionlessBootstrap joining {}:{} using network interface: {}", new Object[]{configuration.getHost(), configuration.getPort(), multicastNetworkInterface.getName()});
+            datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly();
+            allChannels.add(datagramChannel);
+        } else {
+            LOG.info("ConnectionlessBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
+            channel = connectionlessBootstrap.bind(hostAddress);
+            allChannels.add(channel);
+        }
+    }
+
+    protected void stopServerBootstrap() {
+        // close all channels
+        LOG.info("ConnectionlessBootstrap disconnecting from {}:{}", configuration.getHost(), configuration.getPort());
+
+        LOG.trace("Closing {} channels", allChannels.size());
+        ChannelGroupFuture future = allChannels.close();
+        future.awaitUninterruptibly();
+
+        // close server external resources
+        if (datagramChannelFactory != null) {
+            datagramChannelFactory.releaseExternalResources();
+            datagramChannelFactory = null;
+        }
+
+        // and then shutdown the thread pools
+        if (workerPool != null) {
+            workerPool.shutdown();
+            workerPool = null;
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/TextLineDelimiter.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/TextLineDelimiter.java b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/TextLineDelimiter.java
new file mode 100644
index 0000000..9791e57
--- /dev/null
+++ b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/TextLineDelimiter.java
@@ -0,0 +1,26 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+/**
+ * Possible text line delimiters to be used with the textline codec.
+ *
+ * @version 
+ */
+public enum TextLineDelimiter {
+    LINE, NULL;
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ClientChannelHandler.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ClientChannelHandler.java b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ClientChannelHandler.java
new file mode 100644
index 0000000..b0f82d5
--- /dev/null
+++ b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ClientChannelHandler.java
@@ -0,0 +1,235 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4.handlers;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.CamelExchangeException;
+import org.apache.camel.Exchange;
+import org.apache.camel.Message;
+import org.apache.camel.component.netty4.NettyCamelState;
+import org.apache.camel.component.netty4.NettyConstants;
+import org.apache.camel.component.netty4.NettyHelper;
+import org.apache.camel.component.netty4.NettyPayloadHelper;
+import org.apache.camel.component.netty4.NettyProducer;
+import org.apache.camel.util.ExchangeHelper;
+import org.jboss.netty.channel.ChannelHandler;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.channel.ChannelStateEvent;
+import org.jboss.netty.channel.ExceptionEvent;
+import org.jboss.netty.channel.MessageEvent;
+import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Client handler which cannot be shared
+ */
+public class ClientChannelHandler extends SimpleChannelUpstreamHandler {
+    // use NettyProducer as logger to make it easier to read the logs as this is part of the producer
+    private static final Logger LOG = LoggerFactory.getLogger(NettyProducer.class);
+    private final NettyProducer producer;
+    private volatile boolean messageReceived;
+    private volatile boolean exceptionHandled;
+
+    public ClientChannelHandler(NettyProducer producer) {
+        this.producer = producer;
+    }
+
+    @Override
+    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent channelStateEvent) throws Exception {
+        if (LOG.isTraceEnabled()) {
+            LOG.trace("Channel open: {}", ctx.getChannel());
+        }
+        // to keep track of open sockets
+        producer.getAllChannels().add(channelStateEvent.getChannel());
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent exceptionEvent) throws Exception {
+        if (LOG.isTraceEnabled()) {
+            LOG.trace("Exception caught at Channel: " + ctx.getChannel(), exceptionEvent.getCause());
+        }
+         
+        if (exceptionHandled) {
+            // ignore subsequent exceptions being thrown
+            return;
+        }
+
+        exceptionHandled = true;
+        Throwable cause = exceptionEvent.getCause();
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Closing channel as an exception was thrown from Netty", cause);
+        }
+
+        Exchange exchange = getExchange(ctx);
+        AsyncCallback callback = getAsyncCallback(ctx);
+
+        // the state may not be set
+        if (exchange != null && callback != null) {
+            // set the cause on the exchange
+            exchange.setException(cause);
+
+            // close channel in case an exception was thrown
+            NettyHelper.close(exceptionEvent.getChannel());
+
+            // signal callback
+            callback.done(false);
+        }
+    }
+
+    @Override
+    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
+        if (LOG.isTraceEnabled()) {
+            LOG.trace("Channel closed: {}", ctx.getChannel());
+        }
+
+        Exchange exchange = getExchange(ctx);
+        AsyncCallback callback = getAsyncCallback(ctx);
+
+        // remove state
+        producer.removeState(ctx.getChannel());
+
+        // to keep track of open sockets
+        producer.getAllChannels().remove(ctx.getChannel());
+
+        if (producer.getConfiguration().isSync() && !messageReceived && !exceptionHandled) {
+            // To avoid call the callback.done twice 
+            exceptionHandled = true;
+            // session was closed but no message received. This could be because the remote server had an internal error
+            // and could not return a response. We should count down to stop waiting for a response
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Channel closed but no message received from address: {}", producer.getConfiguration().getAddress());
+            }
+            exchange.setException(new CamelExchangeException("No response received from remote server: " + producer.getConfiguration().getAddress(), exchange));
+            // signal callback
+            callback.done(false);
+        }
+    }
+
+    @Override
+    public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
+        messageReceived = true;
+
+        if (LOG.isTraceEnabled()) {
+            LOG.trace("Message received: {}", messageEvent);
+        }
+
+        if (producer.getConfiguration().getRequestTimeout() > 0) {
+            ChannelHandler handler = ctx.getPipeline().get("timeout");
+            if (handler != null) {
+                LOG.trace("Removing timeout channel as we received message");
+                ctx.getPipeline().remove(handler);
+            }
+        }
+
+        Exchange exchange = getExchange(ctx);
+        if (exchange == null) {
+            // we just ignore the received message as the channel is closed
+            return;
+        }
+        AsyncCallback callback = getAsyncCallback(ctx);
+
+        Message message;
+        try {
+            message = getResponseMessage(exchange, messageEvent);
+        } catch (Exception e) {
+            exchange.setException(e);
+            callback.done(false);
+            return;
+        }
+
+        // set the result on either IN or OUT on the original exchange depending on its pattern
+        if (ExchangeHelper.isOutCapable(exchange)) {
+            exchange.setOut(message);
+        } else {
+            exchange.setIn(message);
+        }
+
+        try {
+            // should channel be closed after complete?
+            Boolean close;
+            if (ExchangeHelper.isOutCapable(exchange)) {
+                close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
+            } else {
+                close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
+            }
+            
+            // check the setting on the exchange property
+            if (close == null) {
+                close = exchange.getProperty(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
+            }
+            
+            // should we disconnect, the header can override the configuration
+            boolean disconnect = producer.getConfiguration().isDisconnect();
+            if (close != null) {
+                disconnect = close;
+            }
+            if (disconnect) {
+                if (LOG.isTraceEnabled()) {
+                    LOG.trace("Closing channel when complete at address: {}", producer.getConfiguration().getAddress());
+                }
+                NettyHelper.close(ctx.getChannel());
+            }
+        } finally {
+            // signal callback
+            callback.done(false);
+        }
+    }
+
+    /**
+     * Gets the Camel {@link Message} to use as the message to be set on the current {@link Exchange} when
+     * we have received a reply message.
+     * <p/>
+     *
+     * @param exchange      the current exchange
+     * @param messageEvent  the incoming event which has the response message from Netty.
+     * @return the Camel {@link Message} to set on the current {@link Exchange} as the response message.
+     * @throws Exception is thrown if error getting the response message
+     */
+    protected Message getResponseMessage(Exchange exchange, MessageEvent messageEvent) throws Exception {
+        Object body = messageEvent.getMessage();
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Channel: {} received body: {}", new Object[]{messageEvent.getChannel(), body});
+        }
+
+        // if textline enabled then covert to a String which must be used for textline
+        if (producer.getConfiguration().isTextline()) {
+            body = producer.getContext().getTypeConverter().mandatoryConvertTo(String.class, exchange, body);
+        }
+
+        // set the result on either IN or OUT on the original exchange depending on its pattern
+        if (ExchangeHelper.isOutCapable(exchange)) {
+            NettyPayloadHelper.setOut(exchange, body);
+            return exchange.getOut();
+        } else {
+            NettyPayloadHelper.setIn(exchange, body);
+            return exchange.getIn();
+        }
+    }
+
+    private Exchange getExchange(ChannelHandlerContext ctx) {
+        NettyCamelState state = producer.getState(ctx.getChannel());
+        return state != null ? state.getExchange() : null;
+    }
+
+    private AsyncCallback getAsyncCallback(ChannelHandlerContext ctx) {
+        NettyCamelState state = producer.getState(ctx.getChannel());
+        return state != null ? state.getCallback() : null;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ServerChannelHandler.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ServerChannelHandler.java b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ServerChannelHandler.java
new file mode 100644
index 0000000..2af3cc6
--- /dev/null
+++ b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ServerChannelHandler.java
@@ -0,0 +1,214 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4.handlers;
+
+import java.net.SocketAddress;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.component.netty4.NettyConsumer;
+import org.apache.camel.component.netty4.NettyHelper;
+import org.apache.camel.component.netty4.NettyPayloadHelper;
+import org.apache.camel.util.CamelLogger;
+import org.apache.camel.util.IOHelper;
+import org.jboss.netty.channel.ChannelFutureListener;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.channel.ChannelStateEvent;
+import org.jboss.netty.channel.ExceptionEvent;
+import org.jboss.netty.channel.MessageEvent;
+import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Client handler which cannot be shared
+ */
+public class ServerChannelHandler extends SimpleChannelUpstreamHandler {
+    // use NettyConsumer as logger to make it easier to read the logs as this is part of the consumer
+    private static final Logger LOG = LoggerFactory.getLogger(NettyConsumer.class);
+    private final NettyConsumer consumer;
+    private final CamelLogger noReplyLogger;
+
+    public ServerChannelHandler(NettyConsumer consumer) {
+        this.consumer = consumer;    
+        this.noReplyLogger = new CamelLogger(LOG, consumer.getConfiguration().getNoReplyLogLevel());
+    }
+
+    @Override
+    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
+        if (LOG.isTraceEnabled()) {
+            LOG.trace("Channel open: {}", e.getChannel());
+        }
+        // to keep track of open sockets
+        consumer.getNettyServerBootstrapFactory().addChannel(e.getChannel());
+    }
+
+    @Override
+    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
+        if (LOG.isTraceEnabled()) {
+            LOG.trace("Channel closed: {}", e.getChannel());
+        }
+        // to keep track of open sockets
+        consumer.getNettyServerBootstrapFactory().removeChannel(e.getChannel());
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent exceptionEvent) throws Exception {
+        // only close if we are still allowed to run
+        if (consumer.isRunAllowed()) {
+            // let the exception handler deal with it
+            consumer.getExceptionHandler().handleException("Closing channel as an exception was thrown from Netty", exceptionEvent.getCause());
+            // close channel in case an exception was thrown
+            NettyHelper.close(exceptionEvent.getChannel());
+        }
+    }
+    
+    @Override
+    public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent messageEvent) throws Exception {
+        Object in = messageEvent.getMessage();
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Channel: {} received body: {}", new Object[]{messageEvent.getChannel(), in});
+        }
+
+        // create Exchange and let the consumer process it
+        final Exchange exchange = consumer.getEndpoint().createExchange(ctx, messageEvent);
+
+        if (consumer.getConfiguration().isSync()) {
+            exchange.setPattern(ExchangePattern.InOut);
+        }
+        // set the exchange charset property for converting
+        if (consumer.getConfiguration().getCharsetName() != null) {
+            exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.normalizeCharset(consumer.getConfiguration().getCharsetName()));
+        }
+
+        // we want to handle the UoW
+        consumer.createUoW(exchange);
+
+        beforeProcess(exchange, messageEvent);
+
+        // process accordingly to endpoint configuration
+        if (consumer.getEndpoint().isSynchronous()) {
+            processSynchronously(exchange, messageEvent);
+        } else {
+            processAsynchronously(exchange, messageEvent);
+        }
+    }
+
+    /**
+     * Allows any custom logic before the {@link Exchange} is processed by the routing engine.
+     *
+     * @param exchange       the exchange
+     * @param messageEvent   the Netty message event
+     */
+    protected void beforeProcess(final Exchange exchange, final MessageEvent messageEvent) {
+        // noop
+    }
+
+    private void processSynchronously(final Exchange exchange, final MessageEvent messageEvent) {
+        try {
+            consumer.getProcessor().process(exchange);
+            if (consumer.getConfiguration().isSync()) {
+                sendResponse(messageEvent, exchange);
+            }
+        } catch (Throwable e) {
+            consumer.getExceptionHandler().handleException(e);
+        } finally {
+            consumer.doneUoW(exchange);
+        }
+    }
+
+    private void processAsynchronously(final Exchange exchange, final MessageEvent messageEvent) {
+        consumer.getAsyncProcessor().process(exchange, new AsyncCallback() {
+            @Override
+            public void done(boolean doneSync) {
+                // send back response if the communication is synchronous
+                try {
+                    if (consumer.getConfiguration().isSync()) {
+                        sendResponse(messageEvent, exchange);
+                    }
+                } catch (Throwable e) {
+                    consumer.getExceptionHandler().handleException(e);
+                } finally {
+                    consumer.doneUoW(exchange);
+                }
+            }
+        });
+    }
+
+    private void sendResponse(MessageEvent messageEvent, Exchange exchange) throws Exception {
+        Object body = getResponseBody(exchange);
+
+        if (body == null) {
+            noReplyLogger.log("No payload to send as reply for exchange: " + exchange);
+            if (consumer.getConfiguration().isDisconnectOnNoReply()) {
+                // must close session if no data to write otherwise client will never receive a response
+                // and wait forever (if not timing out)
+                if (LOG.isTraceEnabled()) {
+                    LOG.trace("Closing channel as no payload to send as reply at address: {}", messageEvent.getRemoteAddress());
+                }
+                NettyHelper.close(messageEvent.getChannel());
+            }
+        } else {
+            // if textline enabled then covert to a String which must be used for textline
+            if (consumer.getConfiguration().isTextline()) {
+                body = NettyHelper.getTextlineBody(body, exchange, consumer.getConfiguration().getDelimiter(), consumer.getConfiguration().isAutoAppendDelimiter());
+            }
+
+            // we got a body to write
+            ChannelFutureListener listener = createResponseFutureListener(consumer, exchange, messageEvent.getRemoteAddress());
+            if (consumer.getConfiguration().isTcp()) {
+                NettyHelper.writeBodyAsync(LOG, messageEvent.getChannel(), null, body, exchange, listener);
+            } else {
+                NettyHelper.writeBodyAsync(LOG, messageEvent.getChannel(), messageEvent.getRemoteAddress(), body, exchange, listener);
+            }
+        }
+    }
+
+    /**
+     * Gets the object we want to use as the response object for sending to netty.
+     *
+     * @param exchange the exchange
+     * @return the object to use as response
+     * @throws Exception is thrown if error getting the response body
+     */
+    protected Object getResponseBody(Exchange exchange) throws Exception {
+        // if there was an exception then use that as response body
+        boolean exception = exchange.getException() != null && !consumer.getEndpoint().getConfiguration().isTransferExchange();
+        if (exception) {
+            return exchange.getException();
+        }
+        if (exchange.hasOut()) {
+            return NettyPayloadHelper.getOut(consumer.getEndpoint(), exchange);
+        } else {
+            return NettyPayloadHelper.getIn(consumer.getEndpoint(), exchange);
+        }
+    }
+
+    /**
+     * Creates the {@link ChannelFutureListener} to execute when writing the response is complete.
+     *
+     * @param consumer          the netty consumer
+     * @param exchange          the exchange
+     * @param remoteAddress     the remote address of the message
+     * @return the listener.
+     */
+    protected ChannelFutureListener createResponseFutureListener(NettyConsumer consumer, Exchange exchange, SocketAddress remoteAddress) {
+        return new ServerResponseFutureListener(consumer, exchange, remoteAddress);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ServerResponseFutureListener.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ServerResponseFutureListener.java b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ServerResponseFutureListener.java
new file mode 100644
index 0000000..3da9a22
--- /dev/null
+++ b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/handlers/ServerResponseFutureListener.java
@@ -0,0 +1,77 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4.handlers;
+
+import java.net.SocketAddress;
+
+import org.apache.camel.CamelExchangeException;
+import org.apache.camel.Exchange;
+import org.apache.camel.component.netty4.NettyConstants;
+import org.apache.camel.component.netty4.NettyConsumer;
+import org.apache.camel.component.netty4.NettyHelper;
+import org.jboss.netty.channel.ChannelFuture;
+import org.jboss.netty.channel.ChannelFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link org.jboss.netty.channel.ChannelFutureListener} that performs the disconnect logic when
+ * sending the response is complete.
+ */
+public class ServerResponseFutureListener implements ChannelFutureListener {
+
+    // use NettyConsumer as logger to make it easier to read the logs as this is part of the consumer
+    private static final Logger LOG = LoggerFactory.getLogger(NettyConsumer.class);
+    private final NettyConsumer consumer;
+    private final Exchange exchange;
+    private final SocketAddress remoteAddress;
+
+    public ServerResponseFutureListener(NettyConsumer consumer, Exchange exchange, SocketAddress remoteAddress) {
+        this.consumer = consumer;
+        this.exchange = exchange;
+        this.remoteAddress = remoteAddress;
+    }
+
+    @Override
+    public void operationComplete(ChannelFuture future) throws Exception {
+        // if it was not a success then thrown an exception
+        if (!future.isSuccess()) {
+            Exception e = new CamelExchangeException("Cannot write response to " + remoteAddress, exchange, future.getCause());
+            consumer.getExceptionHandler().handleException(e);
+        }
+
+        // should channel be closed after complete?
+        Boolean close;
+        if (exchange.hasOut()) {
+            close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
+        } else {
+            close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
+        }
+
+        // should we disconnect, the header can override the configuration
+        boolean disconnect = consumer.getConfiguration().isDisconnect();
+        if (close != null) {
+            disconnect = close;
+        }
+        if (disconnect) {
+            if (LOG.isTraceEnabled()) {
+                LOG.trace("Closing channel when complete at address: {}", remoteAddress);
+            }
+            NettyHelper.close(future.getChannel());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/ssl/SSLEngineFactory.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/ssl/SSLEngineFactory.java b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/ssl/SSLEngineFactory.java
new file mode 100644
index 0000000..2630082
--- /dev/null
+++ b/components/camel-netty4/src/main/java/org/apache/camel/component/netty4/ssl/SSLEngineFactory.java
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4.ssl;
+
+import java.io.InputStream;
+import java.security.KeyStore;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.TrustManagerFactory;
+
+import org.apache.camel.spi.ClassResolver;
+import org.apache.camel.util.IOHelper;
+import org.apache.camel.util.ResourceHelper;
+
+public final class SSLEngineFactory {
+
+    private static final String SSL_PROTOCOL = "TLS";
+
+    public SSLEngineFactory() {
+    }
+
+    public SSLContext createSSLContext(ClassResolver classResolver, String keyStoreFormat, String securityProvider,
+                                       String keyStoreResource, String trustStoreResource, char[] passphrase) throws Exception {
+        SSLContext answer;
+        KeyStore ks = KeyStore.getInstance(keyStoreFormat);
+
+        InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(classResolver, keyStoreResource);
+        try {
+            ks.load(is, passphrase);
+        } finally {
+            IOHelper.close(is);
+        }
+
+        KeyManagerFactory kmf = KeyManagerFactory.getInstance(securityProvider);
+        kmf.init(ks, passphrase);
+
+        answer = SSLContext.getInstance(SSL_PROTOCOL);
+
+        if (trustStoreResource != null) {
+            KeyStore ts = KeyStore.getInstance(keyStoreFormat);
+            is = ResourceHelper.resolveMandatoryResourceAsInputStream(classResolver, trustStoreResource);
+            try {
+                ts.load(is, passphrase);
+            } finally {
+                IOHelper.close(is);
+            }
+            TrustManagerFactory tmf = TrustManagerFactory.getInstance(securityProvider);
+            tmf.init(ts);
+            answer.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+        } else {
+            answer.init(kmf.getKeyManagers(), null, null);
+        }
+
+        return answer;
+    }
+
+    public SSLEngine createServerSSLEngine(SSLContext sslContext) {
+        SSLEngine serverEngine = sslContext.createSSLEngine();
+        serverEngine.setUseClientMode(false);
+        serverEngine.setNeedClientAuth(true);
+        return serverEngine;
+    }
+
+    public SSLEngine createClientSSLEngine(SSLContext sslContext) {
+        SSLEngine clientEngine = sslContext.createSSLEngine();
+        clientEngine.setUseClientMode(true);
+        return clientEngine;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/main/resources/META-INF/LICENSE.txt
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/main/resources/META-INF/LICENSE.txt b/components/camel-netty4/src/main/resources/META-INF/LICENSE.txt
new file mode 100644
index 0000000..6b0b127
--- /dev/null
+++ b/components/camel-netty4/src/main/resources/META-INF/LICENSE.txt
@@ -0,0 +1,203 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/main/resources/META-INF/NOTICE.txt
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/main/resources/META-INF/NOTICE.txt b/components/camel-netty4/src/main/resources/META-INF/NOTICE.txt
new file mode 100644
index 0000000..2e215bf
--- /dev/null
+++ b/components/camel-netty4/src/main/resources/META-INF/NOTICE.txt
@@ -0,0 +1,11 @@
+   =========================================================================
+   ==  NOTICE file corresponding to the section 4 d of                    ==
+   ==  the Apache License, Version 2.0,                                   ==
+   ==  in this case for the Apache Camel distribution.                    ==
+   =========================================================================
+
+   This product includes software developed by
+   The Apache Software Foundation (http://www.apache.org/).
+
+   Please read the different LICENSE files present in the licenses directory of
+   this distribution.

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/main/resources/META-INF/services/org/apache/camel/TypeConverter
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/main/resources/META-INF/services/org/apache/camel/TypeConverter b/components/camel-netty4/src/main/resources/META-INF/services/org/apache/camel/TypeConverter
new file mode 100644
index 0000000..33f2e2f
--- /dev/null
+++ b/components/camel-netty4/src/main/resources/META-INF/services/org/apache/camel/TypeConverter
@@ -0,0 +1,18 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+org.apache.camel.component.netty4.NettyConverter
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/main/resources/META-INF/services/org/apache/camel/component/netty4
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/main/resources/META-INF/services/org/apache/camel/component/netty4 b/components/camel-netty4/src/main/resources/META-INF/services/org/apache/camel/component/netty4
new file mode 100644
index 0000000..140b453
--- /dev/null
+++ b/components/camel-netty4/src/main/resources/META-INF/services/org/apache/camel/component/netty4
@@ -0,0 +1,17 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+class=org.apache.camel.component.netty4.NettyComponent

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/test/data/message1.txt
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/test/data/message1.txt b/components/camel-netty4/src/test/data/message1.txt
new file mode 100644
index 0000000..5e1c309
--- /dev/null
+++ b/components/camel-netty4/src/test/data/message1.txt
@@ -0,0 +1 @@
+Hello World
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/BaseNettyTest.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/BaseNettyTest.java b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/BaseNettyTest.java
new file mode 100644
index 0000000..1800801
--- /dev/null
+++ b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/BaseNettyTest.java
@@ -0,0 +1,95 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.Properties;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.component.properties.PropertiesComponent;
+import org.apache.camel.converter.IOConverter;
+import org.apache.camel.impl.JndiRegistry;
+import org.apache.camel.test.AvailablePortFinder;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+
+/**
+ *
+ */
+public class BaseNettyTest extends CamelTestSupport {
+    private static volatile int port;
+
+    @BeforeClass
+    public static void initPort() throws Exception {
+        File file = new File("target/nettyport.txt");
+
+        if (!file.exists()) {
+            // start from somewhere in the 25xxx range
+            port = AvailablePortFinder.getNextAvailable(25000);
+        } else {
+            // read port number from file
+            String s = IOConverter.toString(file, null);
+            port = Integer.parseInt(s);
+            // use next free port
+            port = AvailablePortFinder.getNextAvailable(port + 1);
+        }
+
+    }
+
+    @AfterClass
+    public static void savePort() throws Exception {
+        File file = new File("target/nettyport.txt");
+
+        // save to file, do not append
+        FileOutputStream fos = new FileOutputStream(file, false);
+        try {
+            fos.write(String.valueOf(port).getBytes());
+        } finally {
+            fos.close();
+        }
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext context = super.createCamelContext();
+        context.addComponent("properties", new PropertiesComponent("ref:prop"));
+        return context;
+    }
+
+    @Override
+    protected JndiRegistry createRegistry() throws Exception {
+        JndiRegistry jndi = super.createRegistry();
+
+        Properties prop = new Properties();
+        prop.setProperty("port", "" + getPort());
+        jndi.bind("prop", prop);
+
+        return jndi;
+    }
+
+    protected int getNextPort() {
+        port = AvailablePortFinder.getNextAvailable(port + 1);
+        return port;
+    }
+
+    protected int getPort() {
+        return port;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MultipleCodecsSpringTest.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MultipleCodecsSpringTest.java b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MultipleCodecsSpringTest.java
new file mode 100644
index 0000000..5b553ef
--- /dev/null
+++ b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MultipleCodecsSpringTest.java
@@ -0,0 +1,43 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.spring.CamelSpringTestSupport;
+import org.junit.Test;
+import org.springframework.context.support.AbstractXmlApplicationContext;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+public class MultipleCodecsSpringTest extends CamelSpringTestSupport {
+
+    @Override
+    protected AbstractXmlApplicationContext createApplicationContext() {
+        return new ClassPathXmlApplicationContext("/org/apache/camel/component/netty/multiple-codecs.xml");
+    }
+
+    @Test
+    public void canSupplyMultipleCodecsToEndpointPipeline() throws Exception {
+        String poem = new Poetry().getPoem();
+        MockEndpoint mock = getMockEndpoint("mock:multiple-codec");
+        mock.expectedBodiesReceived(poem);
+        sendBody("direct:multiple-codec", poem);
+        mock.await(1, TimeUnit.SECONDS);
+        mock.assertIsSatisfied();
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MultipleCodecsTest.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MultipleCodecsTest.java b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MultipleCodecsTest.java
new file mode 100644
index 0000000..f54288b
--- /dev/null
+++ b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MultipleCodecsTest.java
@@ -0,0 +1,86 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.impl.JndiRegistry;
+import org.jboss.netty.channel.ChannelHandler;
+import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
+import org.jboss.netty.handler.codec.string.StringDecoder;
+import org.jboss.netty.handler.codec.string.StringEncoder;
+import org.junit.Test;
+
+public class MultipleCodecsTest extends BaseNettyTest {
+
+    @Override
+    protected JndiRegistry createRegistry() throws Exception {
+        JndiRegistry registry = super.createRegistry();
+
+        // START SNIPPET: registry-beans
+        ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4);
+
+        StringDecoder stringDecoder = new StringDecoder();
+        registry.bind("length-decoder", lengthDecoder);
+        registry.bind("string-decoder", stringDecoder);
+
+        LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4);
+        StringEncoder stringEncoder = new StringEncoder();
+        registry.bind("length-encoder", lengthEncoder);
+        registry.bind("string-encoder", stringEncoder);
+
+        List<ChannelHandler> decoders = new ArrayList<ChannelHandler>();
+        decoders.add(lengthDecoder);
+        decoders.add(stringDecoder);
+
+        List<ChannelHandler> encoders = new ArrayList<ChannelHandler>();
+        encoders.add(lengthEncoder);
+        encoders.add(stringEncoder);
+
+        registry.bind("encoders", encoders);
+        registry.bind("decoders", decoders);
+        // END SNIPPET: registry-beans
+        return registry;
+    }
+
+    @Test
+    public void canSupplyMultipleCodecsToEndpointPipeline() throws Exception {
+        String poem = new Poetry().getPoem();
+        MockEndpoint mock = getMockEndpoint("mock:multiple-codec");
+        mock.expectedBodiesReceived(poem);
+        sendBody("direct:multiple-codec", poem);
+        mock.await(1, TimeUnit.SECONDS);
+        mock.assertIsSatisfied();
+
+    }
+
+    protected RouteBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            public void configure() throws Exception {
+                // START SNIPPET: routes
+                from("direct:multiple-codec").to("netty:tcp://localhost:{{port}}?encoders=#encoders&sync=false");
+                
+                from("netty:tcp://localhost:{{port}}?decoders=#length-decoder,#string-decoder&sync=false").to("mock:multiple-codec");
+                // START SNIPPET: routes
+            }
+        };
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MyCustomCodec.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MyCustomCodec.java b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MyCustomCodec.java
new file mode 100644
index 0000000..ee8ba36
--- /dev/null
+++ b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/MyCustomCodec.java
@@ -0,0 +1,81 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+import org.jboss.netty.buffer.ChannelBuffer;
+import org.jboss.netty.buffer.ChannelBuffers;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelHandler;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
+import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
+
+import static org.jboss.netty.buffer.ChannelBuffers.copiedBuffer;
+
+public final class MyCustomCodec {
+    
+    private static ChannelBuffer nullDelimiter = ChannelBuffers.wrappedBuffer(new byte[]{0});
+    
+    private MyCustomCodec() {
+        // Helper class
+    }
+
+    public static ChannelHandlerFactory createMyCustomDecoder() {
+        ChannelBuffer[] delimiters = new ChannelBuffer[]{nullDelimiter, nullDelimiter};
+        return ChannelHandlerFactories.newDelimiterBasedFrameDecoder(4096, delimiters);
+    }
+
+    public static ChannelHandler createMyCustomDecoder2() {
+        return new BytesDecoder();
+    }
+
+    public static ChannelHandler createMyCustomEncoder() {
+        return new BytesEncoder();
+    }
+
+    @ChannelHandler.Sharable
+    public static class BytesDecoder extends OneToOneDecoder {
+
+        @Override
+        protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
+            if (!(msg instanceof ChannelBuffer)) {
+                return msg;
+            } else {
+                // it may be empty, then return null
+                ChannelBuffer cb = (ChannelBuffer) msg;
+                if (cb.hasArray() && cb.readable()) {
+                    return cb.array();
+                } else {
+                    return null;
+                }
+            }
+        }
+
+    }
+
+    @ChannelHandler.Sharable
+    public static class BytesEncoder extends OneToOneEncoder {
+
+        @Override
+        protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
+            if (msg instanceof byte[]) {
+                return copiedBuffer((byte[]) msg);
+            }
+            return msg;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/Netty2978IssueTest.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/Netty2978IssueTest.java b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/Netty2978IssueTest.java
new file mode 100644
index 0000000..bb5298d
--- /dev/null
+++ b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/Netty2978IssueTest.java
@@ -0,0 +1,123 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * @version 
+ */
+@Ignore("This test can cause CI servers to hang")
+public class Netty2978IssueTest extends BaseNettyTest {
+
+    @Test
+    public void testNetty2978() throws Exception {
+        CamelClient client = new CamelClient(context);
+        try {
+            for (int i = 0; i < 1000; i++) {
+                Object reply = client.lookup(i);
+                assertEquals("Bye " + i, reply);
+            }
+        } finally {
+            client.close();
+        }
+    }
+
+    @Test
+    public void testNetty2978Concurrent() throws Exception {
+        final CamelClient client = new CamelClient(context);
+        try {
+            final List<Callable<String>> callables = new ArrayList<Callable<String>>();
+            for (int count = 0; count < 1000; count++) {
+                final int i = count;
+                callables.add(new Callable<String>() {
+                    public String call() {
+                        return client.lookup(i);
+                    }
+                });
+            }
+
+            final ExecutorService executorService = Executors.newFixedThreadPool(10);
+            final List<Future<String>> results = executorService.invokeAll(callables);
+            final Set<String> replies = new HashSet<String>();
+            for (Future<String> future : results) {
+                // wait at most 60 sec to not hang test
+                String reply = future.get(60, TimeUnit.SECONDS);
+                assertTrue(reply.startsWith("Bye "));
+                replies.add(reply);
+            }
+
+            // should be 1000 unique replies
+            assertEquals(1000, replies.size());
+            executorService.shutdownNow();
+        } finally {
+            client.close();
+        }
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            @Override
+            public void configure() throws Exception {
+                from("netty:tcp://localhost:{{port}}?sync=true")
+                        .process(new Processor() {
+                            public void process(final Exchange exchange) {
+                                String body = exchange.getIn().getBody(String.class);
+                                exchange.getOut().setBody("Bye " + body);
+                            }
+                        });
+            }
+        };
+    }
+
+    private static final class CamelClient {
+        private final Endpoint endpoint;
+        private final ProducerTemplate producerTemplate;
+
+        public CamelClient(CamelContext camelContext) {
+            this.endpoint = camelContext.getEndpoint("netty:tcp://localhost:{{port}}?sync=true");
+            this.producerTemplate = camelContext.createProducerTemplate();
+        }
+
+        public void close() throws Exception {
+            producerTemplate.stop();
+        }
+
+        public String lookup(int num) {
+            return producerTemplate.requestBody(endpoint, num, String.class);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyBacklogTest.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyBacklogTest.java b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyBacklogTest.java
new file mode 100644
index 0000000..9c9ed89
--- /dev/null
+++ b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyBacklogTest.java
@@ -0,0 +1,46 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.RouteBuilder;
+
+public class NettyBacklogTest extends NettyTCPSyncTest {
+    
+    @Override
+    protected RouteBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            @Override
+            public void configure() throws Exception {
+                from("netty:tcp://localhost:{{port}}?sync=true&backlog=500")
+                    .process(new Processor() {
+                        public void process(Exchange exchange) throws Exception {
+                            if (exchange.getIn().getBody() instanceof Poetry) {
+                                Poetry poetry = (Poetry) exchange.getIn().getBody();
+                                poetry.setPoet("Dr. Sarojini Naidu");
+                                exchange.getOut().setBody(poetry);
+                                return;
+                            }
+                            exchange.getOut().setBody("When You Go Home, Tell Them Of Us And Say, For Your Tomorrow, We Gave Our Today.");                           
+                        }
+                    });                
+            }
+        };
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyComponentConfigurationAndDocumentationTest.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyComponentConfigurationAndDocumentationTest.java b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyComponentConfigurationAndDocumentationTest.java
new file mode 100644
index 0000000..cd6b0ee
--- /dev/null
+++ b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyComponentConfigurationAndDocumentationTest.java
@@ -0,0 +1,57 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ComponentConfiguration;
+import org.apache.camel.EndpointConfiguration;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.junit.Test;
+
+public class NettyComponentConfigurationAndDocumentationTest extends CamelTestSupport {
+
+    @Override
+    public boolean isUseRouteBuilder() {
+        return false;
+    }
+
+    @Test
+    public void testComponentConfiguration() throws Exception {
+        NettyComponent comp = context.getComponent("netty", NettyComponent.class);
+        EndpointConfiguration conf = comp.createConfiguration("netty:tcp://localhost:5150?sync=true"
+                + "&maximumPoolSize=32&ssl=true&passphrase=#password");
+
+        assertEquals("true", conf.getParameter("sync"));
+        assertEquals("32", conf.getParameter("maximumPoolSize"));
+
+        ComponentConfiguration compConf = comp.createComponentConfiguration();
+        String json = compConf.createParameterJsonSchema();
+        assertNotNull(json);
+
+        assertTrue(json.contains("\"producerPoolMinEvictableIdle\": { \"type\": \"long\" }"));
+        assertTrue(json.contains("\"allowDefaultCodec\": { \"type\": \"boolean\" }"));
+    }
+
+    @Test
+    public void testComponentDocumentation() throws Exception {
+        CamelContext context = new DefaultCamelContext();
+        String html = context.getComponentDocumentation("netty");
+        assertNotNull("Should have found some auto-generated HTML if on Java 7", html);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyComponentWithConfigurationTest.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyComponentWithConfigurationTest.java b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyComponentWithConfigurationTest.java
new file mode 100644
index 0000000..c81152d
--- /dev/null
+++ b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyComponentWithConfigurationTest.java
@@ -0,0 +1,57 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.junit.Test;
+
+/**
+ * @version 
+ */
+public class NettyComponentWithConfigurationTest extends CamelTestSupport {
+
+    @Test
+    public void testNettyComponentWithConfiguration() throws Exception {
+        NettyComponent comp = context.getComponent("netty", NettyComponent.class);
+
+        NettyConfiguration cfg = new NettyConfiguration();
+
+        comp.setConfiguration(cfg);
+        assertSame(cfg, comp.getConfiguration());
+
+        NettyEndpoint e1 = (NettyEndpoint) comp.createEndpoint("netty://tcp://localhost:4455");
+        NettyEndpoint e2 = (NettyEndpoint) comp.createEndpoint("netty://tcp://localhost:5566?sync=false&needClientAuth=true");
+
+        // should not be same
+        assertNotSame(e1, e2);
+        assertNotSame(e1.getConfiguration(), e2.getConfiguration());
+        
+        assertEquals(0, e2.getConfiguration().getReceiveBufferSizePredictor());
+        e2.getConfiguration().setReceiveBufferSizePredictor(1024);
+        assertEquals(1024, e2.getConfiguration().getReceiveBufferSizePredictor());
+
+        e2.getConfiguration().setPort(5566);
+
+        assertEquals(true, e1.getConfiguration().isSync());
+        assertEquals(false, e1.getConfiguration().isNeedClientAuth());
+        assertEquals(false, e2.getConfiguration().isSync());
+        assertEquals(true, e2.getConfiguration().isNeedClientAuth());
+        assertEquals(4455, e1.getConfiguration().getPort());
+        assertEquals(5566, e2.getConfiguration().getPort());
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/7b054480/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyConcurrentTest.java
----------------------------------------------------------------------
diff --git a/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyConcurrentTest.java b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyConcurrentTest.java
new file mode 100644
index 0000000..1da8861
--- /dev/null
+++ b/components/camel-netty4/src/test/java/org/apache/camel/component/netty4/NettyConcurrentTest.java
@@ -0,0 +1,105 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty4;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.builder.NotifyBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.util.StopWatch;
+import org.junit.Ignore;
+import org.junit.Test;
+
+public class NettyConcurrentTest extends BaseNettyTest {
+
+    @Test
+    public void testNoConcurrentProducers() throws Exception {
+        doSendMessages(1, 1);
+    }
+
+    @Test
+    public void testSmallConcurrentProducers() throws Exception {
+        doSendMessages(10, 5);
+    }
+
+    @Test
+    @Ignore
+    public void testLargeConcurrentProducers() throws Exception {
+        doSendMessages(250000, 100);
+    }
+
+    private void doSendMessages(int files, int poolSize) throws Exception {
+        StopWatch watch = new StopWatch();
+        NotifyBuilder notify = new NotifyBuilder(context).whenDone(files).create();
+
+        ExecutorService executor = Executors.newFixedThreadPool(poolSize);
+        // we access the responses Map below only inside the main thread,
+        // so no need for a thread-safe Map implementation
+        Map<Integer, Future<String>> responses = new HashMap<Integer, Future<String>>();
+        for (int i = 0; i < files; i++) {
+            final int index = i;
+            Future<String> out = executor.submit(new Callable<String>() {
+                public String call() throws Exception {
+                    String reply = template.requestBody("netty:tcp://localhost:{{port}}", index, String.class);
+                    log.debug("Sent {} received {}", index, reply);
+                    assertEquals("Bye " + index, reply);
+                    return reply;
+                }
+            });
+            responses.put(index, out);
+        }
+
+        notify.matches(2, TimeUnit.MINUTES);
+        log.info("Took " + watch.taken() + " millis to process " + files + " messages using " + poolSize + " client threads.");
+        assertEquals(files, responses.size());
+
+        // get all responses
+        Set<String> unique = new HashSet<String>();
+        for (Future<String> future : responses.values()) {
+            unique.add(future.get());
+        }
+
+        // should be 'files' unique responses
+        assertEquals("Should be " + files + " unique responses", files, unique.size());
+        executor.shutdownNow();
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            public void configure() throws Exception {
+                from("netty:tcp://localhost:{{port}}?sync=true").process(new Processor() {
+                    public void process(Exchange exchange) throws Exception {
+                        String body = exchange.getIn().getBody(String.class);
+                        exchange.getOut().setBody("Bye " + body);
+                    }
+                }).to("log:progress?groupSize=1000");
+            }
+        };
+    }
+
+}


Mime
View raw message