├── .gitignore
├── LICENSE.txt
├── NOTICE.txt
├── README.md
├── pom.xml
└── src
├── main
└── java
│ ├── Channel.uml
│ └── org
│ └── jboss
│ └── netty
│ ├── bootstrap
│ ├── Bootstrap.java
│ ├── ClientBootstrap.java
│ └── ServerBootstrap.java
│ ├── buffer
│ ├── ChannelBuffer.java
│ ├── ChannelBufferFactory.java
│ ├── ChannelBufferIndexFinder.java
│ ├── WrappedChannelBuffer.java
│ └── impl
│ │ ├── AbstractChannelBuffer.java
│ │ ├── AbstractChannelBufferFactory.java
│ │ ├── BigEndianHeapChannelBuffer.java
│ │ ├── ChannelBuffers.java
│ │ ├── CompositeChannelBuffer.java
│ │ ├── DuplicatedChannelBuffer.java
│ │ ├── EmptyChannelBuffer.java
│ │ ├── HeapChannelBuffer.java
│ │ ├── HeapChannelBufferFactory.java
│ │ ├── LittleEndianHeapChannelBuffer.java
│ │ ├── SlicedChannelBuffer.java
│ │ └── TruncatedChannelBuffer.java
│ ├── channel
│ ├── core
│ │ ├── Channel.java
│ │ ├── ChannelConfig.java
│ │ ├── ChannelDownstreamHandler.java
│ │ ├── ChannelFactory.java
│ │ ├── ChannelHandler.java
│ │ ├── ChannelHandlerContext.java
│ │ ├── ChannelPipeline.java
│ │ ├── ChannelPipelineFactory.java
│ │ ├── ChannelSink.java
│ │ ├── ChannelState.java
│ │ ├── ChannelUpstreamHandler.java
│ │ ├── Channels.java
│ │ ├── FileRegion.java
│ │ ├── LifeCycleAwareChannelHandler.java
│ │ ├── ReceiveBufferSizePredictor.java
│ │ ├── ReceiveBufferSizePredictorFactory.java
│ │ ├── ServerChannel.java
│ │ ├── ServerChannelFactory.java
│ │ └── impl
│ │ │ ├── AbstractChannel.java
│ │ │ ├── AbstractChannelSink.java
│ │ │ ├── AbstractServerChannel.java
│ │ │ ├── AdaptiveReceiveBufferSizePredictor.java
│ │ │ ├── AdaptiveReceiveBufferSizePredictorFactory.java
│ │ │ ├── DefaultChannelConfig.java
│ │ │ ├── DefaultChannelPipeline.java
│ │ │ ├── DefaultFileRegion.java
│ │ │ ├── DefaultServerChannelConfig.java
│ │ │ ├── FixedReceiveBufferSizePredictor.java
│ │ │ ├── FixedReceiveBufferSizePredictorFactory.java
│ │ │ ├── SimpleChannelDownstreamHandler.java
│ │ │ ├── SimpleChannelHandler.java
│ │ │ └── SimpleChannelUpstreamHandler.java
│ ├── event
│ │ ├── ChannelEvent.java
│ │ ├── ChannelStateEvent.java
│ │ ├── ChildChannelStateEvent.java
│ │ ├── ExceptionEvent.java
│ │ ├── MessageEvent.java
│ │ ├── WriteCompletionEvent.java
│ │ └── impl
│ │ │ ├── DefaultChildChannelStateEvent.java
│ │ │ ├── DefaultExceptionEvent.java
│ │ │ ├── DefaultWriteCompletionEvent.java
│ │ │ ├── DownstreamChannelStateEvent.java
│ │ │ ├── DownstreamMessageEvent.java
│ │ │ ├── UpstreamChannelStateEvent.java
│ │ │ └── UpstreamMessageEvent.java
│ ├── exception
│ │ ├── ChannelException.java
│ │ ├── ChannelHandlerLifeCycleException.java
│ │ ├── ChannelPipelineException.java
│ │ └── ConnectTimeoutException.java
│ ├── future
│ │ ├── ChannelFuture.java
│ │ ├── ChannelFutureListener.java
│ │ ├── ChannelFutureProgressListener.java
│ │ └── impl
│ │ │ ├── CompleteChannelFuture.java
│ │ │ ├── DefaultChannelFuture.java
│ │ │ ├── FailedChannelFuture.java
│ │ │ └── SucceededChannelFuture.java
│ └── socket
│ │ ├── ChannelRunnableWrapper.java
│ │ ├── ClientSocketChannelFactory.java
│ │ ├── DefaultServerSocketChannelConfig.java
│ │ ├── DefaultSocketChannelConfig.java
│ │ ├── InternetProtocolFamily.java
│ │ ├── ServerSocketChannel.java
│ │ ├── ServerSocketChannelConfig.java
│ │ ├── ServerSocketChannelFactory.java
│ │ ├── SocketChannel.java
│ │ ├── SocketChannelConfig.java
│ │ ├── Worker.java
│ │ └── nio
│ │ ├── AbstractNioBossPool.java
│ │ ├── AbstractNioChannel.java
│ │ ├── AbstractNioChannelSink.java
│ │ ├── AbstractNioSelector.java
│ │ ├── AbstractNioWorker.java
│ │ ├── AbstractNioWorkerPool.java
│ │ ├── Boss.java
│ │ ├── BossPool.java
│ │ ├── DefaultNioSocketChannelConfig.java
│ │ ├── NioChannelConfig.java
│ │ ├── NioSelector.java
│ │ ├── NioSelectorPool.java
│ │ ├── NioSocketChannel.java
│ │ ├── NioSocketChannelConfig.java
│ │ ├── NioWorker.java
│ │ ├── NioWorkerPool.java
│ │ ├── ProtocolFamilyConverter.java
│ │ ├── SelectorUtil.java
│ │ ├── ShareableWorkerPool.java
│ │ ├── SocketReceiveBufferAllocator.java
│ │ ├── SocketSendBufferPool.java
│ │ ├── WorkerPool.java
│ │ ├── client
│ │ ├── NioClientBoss.java
│ │ ├── NioClientBossPool.java
│ │ ├── NioClientSocketChannel.java
│ │ ├── NioClientSocketChannelFactory.java
│ │ └── NioClientSocketPipelineSink.java
│ │ └── server
│ │ ├── NioAcceptedSocketChannel.java
│ │ ├── NioServerBoss.java
│ │ ├── NioServerBossPool.java
│ │ ├── NioServerSocketChannel.java
│ │ ├── NioServerSocketChannelFactory.java
│ │ └── NioServerSocketPipelineSink.java
│ ├── logging
│ ├── AbstractInternalLogger.java
│ ├── InternalLogLevel.java
│ ├── InternalLogger.java
│ ├── InternalLoggerFactory.java
│ ├── JdkLogger.java
│ └── JdkLoggerFactory.java
│ └── util
│ ├── CharsetUtil.java
│ ├── DebugUtil.java
│ ├── DefaultObjectSizeEstimator.java
│ ├── EstimatableObjectWrapper.java
│ ├── ExternalResourceReleasable.java
│ ├── ExternalResourceUtil.java
│ ├── HashedWheelTimer.java
│ ├── MapBackedSet.java
│ ├── NetUtil.java
│ ├── ObjectSizeEstimator.java
│ ├── ThreadNameDeterminer.java
│ ├── ThreadRenamingRunnable.java
│ ├── Timeout.java
│ ├── Timer.java
│ ├── TimerTask.java
│ ├── Version.java
│ ├── VirtualExecutorService.java
│ └── internal
│ ├── AtomicFieldUpdaterUtil.java
│ ├── ByteBufferUtil.java
│ ├── CaseIgnoringComparator.java
│ ├── ConcurrentHashMap.java
│ ├── ConcurrentIdentityHashMap.java
│ ├── ConcurrentIdentityWeakKeyHashMap.java
│ ├── ConcurrentWeakKeyHashMap.java
│ ├── ConversionUtil.java
│ ├── DeadLockProofWorker.java
│ ├── DetectionUtil.java
│ ├── EmptyArrays.java
│ ├── ExecutorUtil.java
│ ├── NativeLibraryLoader.java
│ ├── NonReentrantLock.java
│ ├── ReusableIterator.java
│ ├── SharedResourceMisuseDetector.java
│ ├── StringUtil.java
│ ├── SystemPropertyUtil.java
│ ├── ThreadLocalBoolean.java
│ ├── ThreadLocalRandom.java
│ └── UnterminatableExecutor.java
└── test
└── java
└── com
└── nyankosama
└── test
├── EchoServer.java
├── EchoServerHandler.java
└── SimpleClient.java
/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | /doc/
3 | /jar/
4 | /license/
5 | /.idea/
6 | /*.iml
7 | .DS_Store
8 | .gitignore
9 |
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #Simple Netty Source
2 |
3 | 本项目是netty.3.9.4.Final源码的精简版本,删除掉netty中不必要的功能,只保留了核心模块,方便进行源码学习。
4 |
5 | ##Change log
6 |
7 | * **0.1.0**
8 | * 在保证interface的方法完整性的前提下,删除了核心逻辑package下的所有不必要的class
9 | * 重新组织了channel包下的类,添加了event, exception和future包,使每个package下的类的职能更明确,方便理解
10 |
11 | * **0.0.1**
12 | * 以packge为粒度,删除了所有不必要的包
13 | * 确保netty的网络部分的核心逻辑的完整性
14 |
15 |
16 | ##模块变更
17 |
18 | *以下的表格列出了保留的模块*
19 |
20 | | Modules | Function |
21 | |-----------------|-----------------------------------------------------------------------|
22 | | bootstrap | 组织netty模块工作并启动相关模块的工具类 |
23 | | buffer | Buffer的具体相关实现 |
24 | | channel | 对java nio中的channel的重新封装的相关实现 |
25 | | channel-socket | netty的网络核心模块,包括Boss、Worker、Selector、核心主循环等相关实现 |
26 | | logging(不重要) | 相关的log工具类实现 |
27 | | util(不重要) | 相关的工具类实现,包括Timer、StringUtil、ByteBufferUtil等 |
28 |
29 | **注:其中logging和util并不重要,阅读源码时可以略过,这里由于一些依赖关系所以保留**
30 |
31 | *以下表格列出了删除掉的模块*
32 |
33 | | Modules | Function |
34 | |---------------------|------------------------------------|
35 | | channel-group | Channel Group相关实现 |
36 | | channel-local | local transport的相关支持 |
37 | | channel-socket-http | http handler的相关实现 |
38 | | channel-socket-oio | oio模式下的核心网络模块 |
39 | | container | 一些无关紧要的适配 |
40 | | example | Netty官方自带的一些例子 |
41 | | handler | Netty异常强大功能全面的handler实现 |
42 | | netty-test | Netty的单元测试集|
43 |
44 | ##源码阅读指南
45 |
46 | 由于netty模块内部的对象协作关系较为复杂,所以这里推荐从最为简单的EchoServer作为入口阅读相关源码。(Example代码已经附在了test中)
47 |
48 | ###关键源码阅读路径
49 |
50 | * **new NioServerSocketChannelFactory()** ====> **new NioWorkerPool()** ====> **AbstractNioWorkerPool.init()** ====> **AbstractNioWorkerPool.newWorker(Executor)** ====> **NioWorkerPool.createWorker(Executor)** ====> **new AbstractNioSelector(Executor, ThreadNameDeterminer)** ====> **AbstractNioSelector.openSelector(ThreadNameDeterminer)**
51 | * **new NioServerSocketChannelFactory()** ====> **new NioServerBossPool()** ====> **NioServerBossPool.init()** ====> **AbstractNioBossPool.newBoss(Executor)** ====> **NioServerBossPool.newBoss(Executor)** ====> **new NioServerBoss(Executor, ThreadNameDeterminer)** ====> **AbstractNioSelector.openSelector(ThreadNameDeterminer)**
52 | * **AbstractNioSelector.run()** ====> **AbstractNioSelector.process()**
53 | * **AbstractNioSelector.run()** ====> **NioServerBoss.process()**
54 | * **AbstractNioSelector.run()** ====> **AbstractNioSelector.processTaskQueue()**
55 |
56 | ###注意事项
57 |
58 | 在阅读过程中需要注意以下几点:
59 |
60 | * NioWorker和NioServerBoss分别是Worker和Boss的线程runnable实现,Netty的核心nio网络处理代码就在这两个类以及其相关父类中
61 | * 顺着ServerBootstrap的创建,就可以摸清楚NioWorker和NioServerBoss是如何被创建,如何run起来的
62 | * NioWorker和NioServerBoss中的firexxx一系列方法即为触发channelPipeline寻找已添加的handler分发对应的事件的入口方法
63 | * DefaultChannelPipeline实现了ChannelPipeline,其中以链表维护具体的handler列表。具体事件的分发分为两个方向,即upStream和downStream,前者代表read事件的分发,后者代表write事件的分发
64 | * buffer包中为ChannelBuffer的相关实现,在NioWorker中的process方法的read调用里面可以清晰看到ChannelBuffer的创建和分发的upStream的具体过程。
65 | * ChannelBuffer的实现主要去看ChannelBuffer -> AbstractChannelBuffer -> HeapChannelBuffer -> BigEndianHeapChannelBuffer这条线即可
66 | * 善于在关键路径运用断点查看调用栈,一目了然
67 |
68 | ##License
69 | Apache License v2
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | 4.0.0
20 | io.netty
21 | netty
22 | 3.9.4.Final.Custom
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/src/main/java/Channel.uml:
--------------------------------------------------------------------------------
1 |
2 |
3 | JAVA
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | All
12 |
13 |
14 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/buffer/WrappedChannelBuffer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.buffer;
17 |
18 | /**
19 | * The common interface for buffer wrappers and derived buffers. Most users won't
20 | * need to use this interface. It is used internally in most cases.
21 | */
22 | public interface WrappedChannelBuffer extends ChannelBuffer {
23 | /**
24 | * Returns this buffer's parent that this buffer is wrapping.
25 | */
26 | ChannelBuffer unwrap();
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/buffer/impl/AbstractChannelBufferFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.buffer.impl;
17 |
18 | import org.jboss.netty.buffer.ChannelBuffer;
19 | import org.jboss.netty.buffer.ChannelBufferFactory;
20 |
21 | import java.nio.ByteOrder;
22 |
23 | /**
24 | * A skeletal implementation of {@link ChannelBufferFactory}.
25 | */
26 | public abstract class AbstractChannelBufferFactory implements ChannelBufferFactory {
27 |
28 | private final ByteOrder defaultOrder;
29 |
30 | /**
31 | * Creates a new factory whose default {@link ByteOrder} is
32 | * {@link ByteOrder#BIG_ENDIAN}.
33 | */
34 | protected AbstractChannelBufferFactory() {
35 | this(ByteOrder.BIG_ENDIAN);
36 | }
37 |
38 | /**
39 | * Creates a new factory with the specified default {@link ByteOrder}.
40 | *
41 | * @param defaultOrder the default {@link ByteOrder} of this factory
42 | */
43 | protected AbstractChannelBufferFactory(ByteOrder defaultOrder) {
44 | if (defaultOrder == null) {
45 | throw new NullPointerException("defaultOrder");
46 | }
47 | this.defaultOrder = defaultOrder;
48 | }
49 |
50 | public ChannelBuffer getBuffer(int capacity) {
51 | return getBuffer(getDefaultOrder(), capacity);
52 | }
53 |
54 | public ChannelBuffer getBuffer(byte[] array, int offset, int length) {
55 | return getBuffer(getDefaultOrder(), array, offset, length);
56 | }
57 |
58 | public ByteOrder getDefaultOrder() {
59 | return defaultOrder;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/buffer/impl/HeapChannelBufferFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.buffer.impl;
17 |
18 | import org.jboss.netty.buffer.ChannelBuffer;
19 | import org.jboss.netty.buffer.ChannelBufferFactory;
20 |
21 | import java.nio.ByteBuffer;
22 | import java.nio.ByteOrder;
23 |
24 | /**
25 | * A {@link ChannelBufferFactory} which merely allocates a heap buffer with
26 | * the specified capacity. {@link HeapChannelBufferFactory} should perform
27 | * very well in most situations because it relies on the JVM garbage collector,
28 | * which is highly optimized for heap allocation.
29 | */
30 | public class HeapChannelBufferFactory extends AbstractChannelBufferFactory {
31 |
32 | private static final HeapChannelBufferFactory INSTANCE_BE =
33 | new HeapChannelBufferFactory(ByteOrder.BIG_ENDIAN);
34 |
35 | private static final HeapChannelBufferFactory INSTANCE_LE =
36 | new HeapChannelBufferFactory(ByteOrder.LITTLE_ENDIAN);
37 |
38 | public static ChannelBufferFactory getInstance() {
39 | return INSTANCE_BE;
40 | }
41 |
42 | public static ChannelBufferFactory getInstance(ByteOrder endianness) {
43 | if (endianness == ByteOrder.BIG_ENDIAN) {
44 | return INSTANCE_BE;
45 | } else if (endianness == ByteOrder.LITTLE_ENDIAN) {
46 | return INSTANCE_LE;
47 | } else if (endianness == null) {
48 | throw new NullPointerException("endianness");
49 | } else {
50 | throw new IllegalStateException("Should not reach here");
51 | }
52 | }
53 |
54 | /**
55 | * Creates a new factory whose default {@link ByteOrder} is
56 | * {@link ByteOrder#BIG_ENDIAN}.
57 | */
58 | public HeapChannelBufferFactory() {
59 | }
60 |
61 | /**
62 | * Creates a new factory with the specified default {@link ByteOrder}.
63 | *
64 | * @param defaultOrder the default {@link ByteOrder} of this factory
65 | */
66 | public HeapChannelBufferFactory(ByteOrder defaultOrder) {
67 | super(defaultOrder);
68 | }
69 |
70 | public ChannelBuffer getBuffer(ByteOrder order, int capacity) {
71 | return ChannelBuffers.buffer(order, capacity);
72 | }
73 |
74 | public ChannelBuffer getBuffer(ByteOrder order, byte[] array, int offset, int length) {
75 | return ChannelBuffers.wrappedBuffer(order, array, offset, length);
76 | }
77 |
78 | public ChannelBuffer getBuffer(ByteBuffer nioBuffer) {
79 | if (nioBuffer.hasArray()) {
80 | return ChannelBuffers.wrappedBuffer(nioBuffer);
81 | }
82 |
83 | ChannelBuffer buf = getBuffer(nioBuffer.order(), nioBuffer.remaining());
84 | int pos = nioBuffer.position();
85 | buf.writeBytes(nioBuffer);
86 | nioBuffer.position(pos);
87 | return buf;
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/ChannelDownstreamHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core;
17 |
18 | import org.jboss.netty.channel.event.ChannelEvent;
19 | import org.jboss.netty.channel.event.impl.UpstreamChannelStateEvent;
20 | import org.jboss.netty.channel.core.impl.SimpleChannelDownstreamHandler;
21 |
22 | /**
23 | * Handles or intercepts a downstream {@link ChannelEvent}, and sends a
24 | * {@link ChannelEvent} to the next handler in a {@link ChannelPipeline}.
25 | *
26 | * The most common use case of this interface is to intercept an I/O request
27 | * such as {@link Channel#write(Object)} and {@link Channel#close()}.
28 | *
29 | *
{@link SimpleChannelDownstreamHandler}
30 | *
31 | * In most cases, you will get to use a {@link SimpleChannelDownstreamHandler}
32 | * to implement a downstream handler because it provides an individual handler
33 | * method for each event type. You might want to implement this interface
34 | * directly though if you want to handle various types of events in more
35 | * generic way.
36 | *
37 | *
Firing an event to the next handler
38 | *
39 | * You can forward the received event downstream or upstream. In most cases,
40 | * {@link ChannelDownstreamHandler} will send the event downstream
41 | * (i.e. outbound) although it is legal to send the event upstream (i.e. inbound):
42 | *
43 | *
44 | * // Sending the event downstream (outbound)
45 | * void handleDownstream({@link ChannelHandlerContext} ctx, {@link ChannelEvent} e) throws Exception {
46 | * ...
47 | * ctx.sendDownstream(e);
48 | * ...
49 | * }
50 | *
51 | * // Sending the event upstream (inbound)
52 | * void handleDownstream({@link ChannelHandlerContext} ctx, {@link ChannelEvent} e) throws Exception {
53 | * ...
54 | * ctx.sendUpstream(new {@link UpstreamChannelStateEvent}(...));
55 | * ...
56 | * }
57 | *
58 | *
59 | * Using the helper class to send an event
60 | *
61 | * You will also find various helper methods in {@link Channels} to be useful
62 | * to generate and send an artificial or manipulated event.
63 | *
64 | * Caution:
65 | *
66 | * Use the *Later(..) methods of the {@link Channels} class if you want to send an upstream event
67 | * from a {@link ChannelDownstreamHandler} otherwise you may run into threading issues.
68 | *
69 | *
State management
70 | *
71 | * Please refer to {@link ChannelHandler}.
72 | *
73 | * Thread safety
74 | *
75 | * {@link #handleDownstream(ChannelHandlerContext, ChannelEvent) handleDownstream}
76 | * may be invoked by more than one thread simultaneously. If the handler
77 | * accesses a shared resource or stores stateful information, you might need
78 | * proper synchronization in the handler implementation.
79 | *
80 | * @apiviz.exclude ^org\.jboss\.netty\.handler\..*$
81 | */
82 | public interface ChannelDownstreamHandler extends ChannelHandler {
83 |
84 | /**
85 | * Handles the specified downstream event.
86 | *
87 | * @param ctx the context object for this handler
88 | * @param e the downstream event to process or intercept
89 | */
90 | void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception;
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/ChannelFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core;
17 |
18 | import java.util.concurrent.Executor;
19 |
20 | import org.jboss.netty.channel.event.ChannelEvent;
21 | import org.jboss.netty.channel.socket.nio.server.NioServerSocketChannelFactory;
22 | import org.jboss.netty.util.ExternalResourceReleasable;
23 |
24 |
25 | /**
26 | * The main interface to a transport that creates a {@link Channel} associated
27 | * with a certain communication entity such as a network socket. For example,
28 | * the {@link NioServerSocketChannelFactory} creates a channel which has a
29 | * NIO-based server socket as its underlying communication entity.
30 | *
31 | * Once a new {@link Channel} is created, the {@link ChannelPipeline} which
32 | * was specified as a parameter in the {@link #newChannel(ChannelPipeline)}
33 | * is attached to the new {@link Channel}, and starts to handle all associated
34 | * {@link ChannelEvent}s.
35 | *
36 | *
Graceful shutdown
37 | *
38 | * To shut down a network application service which is managed by a factory.
39 | * you should follow the following steps:
40 | *
41 | * - close all channels created by the factory and their child channels
42 | * usually using {@link ChannelGroup#close()}, and
43 | * - call {@link #releaseExternalResources()}.
44 | *
45 | *
46 | * For detailed transport-specific information on shutting down a factory,
47 | * please refer to the Javadoc of {@link ChannelFactory}'s subtypes, such as
48 | * {@link NioServerSocketChannelFactory}.
49 | *
50 | * @apiviz.landmark
51 | * @apiviz.has org.jboss.netty.channel.skeleton.Channel oneway - - creates
52 | *
53 | * @apiviz.exclude ^org\.jboss\.netty\.channel\.([a-z]+\.)+.*ChannelFactory$
54 | */
55 | public interface ChannelFactory extends ExternalResourceReleasable {
56 |
57 | /**
58 | * Creates and opens a new {@link Channel} and attaches the specified
59 | * {@link ChannelPipeline} to the new {@link Channel}.
60 | *
61 | * @param pipeline the {@link ChannelPipeline} which is going to be
62 | * attached to the new {@link Channel}
63 | *
64 | * @return the newly open channel
65 | *
66 | * @throws org.jboss.netty.channel.exception.ChannelException if failed to create and open a new channel
67 | */
68 | Channel newChannel(ChannelPipeline pipeline);
69 |
70 | /**
71 | * Shudown the ChannelFactory and all the resource it created internal.
72 | */
73 | void shutdown();
74 |
75 | /**
76 | * Releases the external resources that this factory depends on to function.
77 | * An external resource is a resource that this factory didn't create by
78 | * itself. For example, {@link Executor}s that you specified in the factory
79 | * constructor are external resources. You can call this method to release
80 | * all external resources conveniently when the resources are not used by
81 | * this factory or any other part of your application. An unexpected
82 | * behavior will be resulted in if the resources are released when there's
83 | * an open channel which is managed by this factory.
84 | *
85 | * This will also call {@link #shutdown()} before do any action
86 | */
87 | void releaseExternalResources();
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/ChannelPipelineFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core;
17 |
18 | import org.jboss.netty.bootstrap.Bootstrap;
19 | import org.jboss.netty.bootstrap.ClientBootstrap;
20 |
21 | /**
22 | * Creates a new {@link ChannelPipeline} for a new {@link Channel}.
23 | *
24 | * When a {@linkplain ServerChannel server-side channel} accepts a new incoming
25 | * connection, a new child channel is created for each newly accepted connection.
26 | * A new child channel uses a new {@link ChannelPipeline}, which is created by
27 | * the {@link ChannelPipelineFactory} specified in the server-side channel's
28 | * {@link ChannelConfig#getPipelineFactory() "pipelineFactory"} option.
29 | *
30 | * Also, when a {@link ClientBootstrap} or {@link ConnectionlessBootstrap}
31 | * creates a new channel, it uses the {@link Bootstrap#getPipelineFactory() "pipelineFactory"}
32 | * property to create a new {@link ChannelPipeline} for each new channel.
33 | *
34 | * @apiviz.has org.jboss.netty.channel.skeleton.ChannelPipeline oneway - - creates
35 | */
36 | public interface ChannelPipelineFactory {
37 |
38 | /**
39 | * Returns a newly created {@link ChannelPipeline}.
40 | */
41 | ChannelPipeline getPipeline() throws Exception;
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/ChannelSink.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core;
17 |
18 |
19 | import org.jboss.netty.channel.event.ChannelEvent;
20 | import org.jboss.netty.channel.exception.ChannelPipelineException;
21 | import org.jboss.netty.channel.future.ChannelFuture;
22 |
23 | /**
24 | * Receives and processes the terminal downstream {@link ChannelEvent}s.
25 | *
26 | * A {@link ChannelSink} is an internal component which is supposed to be
27 | * implemented by a transport provider. Most users will not see this type
28 | * in their code.
29 | *
30 | * @apiviz.uses org.jboss.netty.channel.skeleton.ChannelPipeline - - sends events upstream
31 | */
32 | public interface ChannelSink {
33 |
34 | /**
35 | * Invoked by {@link ChannelPipeline} when a downstream {@link ChannelEvent}
36 | * has reached its terminal (the head of the pipeline).
37 | */
38 | void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception;
39 |
40 | /**
41 | * Invoked by {@link ChannelPipeline} when an exception was raised while
42 | * one of its {@link ChannelHandler}s process a {@link ChannelEvent}.
43 | */
44 | void exceptionCaught(ChannelPipeline pipeline, ChannelEvent e, ChannelPipelineException cause) throws Exception;
45 |
46 | /**
47 | * Execute the given {@link Runnable} later in the io-thread.
48 | * Some implementation may not support this and just execute it directly.
49 | */
50 | ChannelFuture execute(ChannelPipeline pipeline, Runnable task);
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/FileRegion.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core;
17 |
18 | import java.io.IOException;
19 | import java.nio.channels.FileChannel;
20 | import java.nio.channels.WritableByteChannel;
21 |
22 | import org.jboss.netty.util.ExternalResourceReleasable;
23 |
24 | /**
25 | * A region of a file that is sent via a {@link Channel} which supports
26 | * zero-copy file transfer.
27 | *
28 | *
Upgrade your JDK / JRE
29 | *
30 | * {@link FileChannel#transferTo(long, long, WritableByteChannel)} has at least
31 | * four known bugs in the old versions of Sun JDK and perhaps its derived ones.
32 | * Please upgrade your JDK to 1.6.0_18 or later version if you are going to use
33 | * zero-copy file transfer.
34 | *
35 | * - 5103988
36 | * - FileChannel.transferTo() should return -1 for EAGAIN instead throws IOException
37 | * - 6253145
38 | * - FileChannel.transferTo() on Linux fails when going beyond 2GB boundary
39 | * - 6427312
40 | * - FileChannel.transferTo() throws IOException "system call interrupted"
41 | * - 6470086
42 | * - FileChannel.transferTo(2147483647, 1, channel) causes "Value too large" exception
43 | *
44 | *
45 | * Check your operating system and JDK / JRE
46 | *
47 | * If your operating system (or JDK / JRE) does not support zero-copy file
48 | * transfer, sending a file with {@link FileRegion} might fail or yield worse
49 | * performance. For example, sending a large file doesn't work well in Windows.
50 | *
51 | * Not all transports support it
52 | *
53 | * Currently, the NIO transport is the only transport that supports {@link FileRegion}.
54 | * Attempting to write a {@link FileRegion} to non-NIO {@link Channel} will trigger
55 | * a {@link ClassCastException} or a similar exception.
56 | */
57 | public interface FileRegion extends ExternalResourceReleasable {
58 |
59 | // FIXME Make sure all transports support writing a FileRegion
60 | // Even if zero copy cannot be achieved, all transports should emulate it.
61 |
62 | /**
63 | * Returns the offset in the file where the transfer began.
64 | */
65 | long getPosition();
66 |
67 | /**
68 | * Returns the number of bytes to transfer.
69 | */
70 | long getCount();
71 |
72 | /**
73 | * Transfers the content of this file region to the specified channel.
74 | *
75 | * @param target the destination of the transfer
76 | * @param position the relative offset of the file where the transfer
77 | * begins from. For example, 0 will make the
78 | * transfer start from {@link #getPosition()}th byte and
79 | * {@link #getCount()} - 1 will make the last
80 | * byte of the region transferred.
81 | */
82 | long transferTo(WritableByteChannel target, long position) throws IOException;
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/LifeCycleAwareChannelHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core;
17 |
18 | import org.jboss.netty.channel.event.ChannelEvent;
19 |
20 | /**
21 | * A {@link ChannelHandler} that is notified when it is added to or removed
22 | * from a {@link ChannelPipeline}.
23 | *
24 | * Invalid access to the {@link ChannelHandlerContext}
25 | *
26 | * Calling {@link ChannelHandlerContext#sendUpstream(ChannelEvent)} or
27 | * {@link ChannelHandlerContext#sendDownstream(ChannelEvent)} in
28 | * {@link #beforeAdd(ChannelHandlerContext)} or {@link #afterRemove(ChannelHandlerContext)}
29 | * might lead to an unexpected behavior. It is because the context object
30 | * might not have been fully added to the pipeline or the context object is not
31 | * a part of the pipeline anymore respectively.
32 | */
33 | public interface LifeCycleAwareChannelHandler extends ChannelHandler {
34 | void beforeAdd(ChannelHandlerContext ctx) throws Exception;
35 | void afterAdd(ChannelHandlerContext ctx) throws Exception;
36 | void beforeRemove(ChannelHandlerContext ctx) throws Exception;
37 | void afterRemove(ChannelHandlerContext ctx) throws Exception;
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/ReceiveBufferSizePredictor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core;
17 |
18 | import org.jboss.netty.buffer.ChannelBuffer;
19 |
20 | /**
21 | * Predicts the number of readable bytes in the receive buffer of a
22 | * {@link Channel}.
23 | *
24 | * It calculates the close-to-optimal capacity of the {@link ChannelBuffer}
25 | * for the next read operation depending on the actual number of read bytes
26 | * in the previous read operation. More accurate the prediction is, more
27 | * effective the memory utilization will be.
28 | *
29 | * Once a read operation is performed and the actual number of read bytes is
30 | * known, an I/O thread will call {@link #previousReceiveBufferSize(int)} to
31 | * update the predictor so it can predict more accurately next time.
32 | */
33 | public interface ReceiveBufferSizePredictor {
34 |
35 | /**
36 | * Predicts the capacity of the {@link ChannelBuffer} for the next
37 | * read operation depending on the actual number of read bytes in the
38 | * previous read operation.
39 | *
40 | * @return the expected number of readable bytes this time
41 | */
42 | int nextReceiveBufferSize();
43 |
44 | /**
45 | * Updates this predictor by specifying the actual number of read bytes
46 | * in the previous read operation.
47 | *
48 | * @param previousReceiveBufferSize
49 | * the actual number of read bytes in the previous read operation
50 | */
51 | void previousReceiveBufferSize(int previousReceiveBufferSize);
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/ReceiveBufferSizePredictorFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core;
17 |
18 | /**
19 | * Creates a new {@link ReceiveBufferSizePredictor}.
20 | *
21 | * @apiviz.has org.jboss.netty.channel.skeleton.ReceiveBufferSizePredictor oneway - - creates
22 | */
23 | public interface ReceiveBufferSizePredictorFactory {
24 |
25 | /**
26 | * Returns a newly created {@link ReceiveBufferSizePredictor}.
27 | */
28 | ReceiveBufferSizePredictor getPredictor() throws Exception;
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/ServerChannel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core;
17 |
18 | import org.jboss.netty.channel.socket.ServerSocketChannel;
19 |
20 | /**
21 | * A {@link Channel} that accepts an incoming connection attempt and creates
22 | * its child {@link Channel}s by accepting them. {@link ServerSocketChannel} is
23 | * a good example.
24 | */
25 | public interface ServerChannel extends Channel {
26 | // This is a tag interface.
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/ServerChannelFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core;
17 |
18 | /**
19 | * A {@link ChannelFactory} that creates a {@link ServerChannel}.
20 | *
21 | * @apiviz.has org.jboss.netty.channel.skeleton.ServerChannel oneway - - creates
22 | */
23 | public interface ServerChannelFactory extends ChannelFactory {
24 | ServerChannel newChannel(ChannelPipeline pipeline);
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/impl/AbstractChannelSink.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core.impl;
17 |
18 | import org.jboss.netty.channel.event.ChannelEvent;
19 | import org.jboss.netty.channel.exception.ChannelPipelineException;
20 | import org.jboss.netty.channel.future.ChannelFuture;
21 | import org.jboss.netty.channel.core.ChannelHandler;
22 | import org.jboss.netty.channel.core.ChannelPipeline;
23 | import org.jboss.netty.channel.core.ChannelSink;
24 | import org.jboss.netty.channel.core.Channels;
25 |
26 | /**
27 | * A skeletal {@link ChannelSink} implementation.
28 | */
29 | public abstract class AbstractChannelSink implements ChannelSink {
30 |
31 | /**
32 | * Creates a new instance.
33 | */
34 | protected AbstractChannelSink() {
35 | }
36 |
37 | /**
38 | * Sends an {@link org.jboss.netty.channel.event.ExceptionEvent} upstream with the specified
39 | * {@code cause}.
40 | *
41 | * @param event the {@link ChannelEvent} which caused a
42 | * {@link ChannelHandler} to raise an exception
43 | * @param cause the exception raised by a {@link ChannelHandler}
44 | */
45 | public void exceptionCaught(ChannelPipeline pipeline,
46 | ChannelEvent event, ChannelPipelineException cause) throws Exception {
47 | Throwable actualCause = cause.getCause();
48 | if (actualCause == null) {
49 | actualCause = cause;
50 | }
51 | if (isFireExceptionCaughtLater(event, actualCause)) {
52 | Channels.fireExceptionCaughtLater(event.getChannel(), actualCause);
53 | } else {
54 | Channels.fireExceptionCaught(event.getChannel(), actualCause);
55 | }
56 | }
57 |
58 | /**
59 | * Returns {@code true} if and only if the specified {@code actualCause}, which was raised while
60 | * handling the specified {@code event}, must trigger an {@code exceptionCaught()} event in
61 | * an I/O thread.
62 | *
63 | * @param event the event which raised exception
64 | * @param actualCause the raised exception
65 | */
66 | protected boolean isFireExceptionCaughtLater(ChannelEvent event, Throwable actualCause) {
67 | return false;
68 | }
69 |
70 | /**
71 | * This implementation just directly call {@link Runnable#run()}.
72 | * Sub-classes should override this if they can handle it in a better way
73 | */
74 | public ChannelFuture execute(ChannelPipeline pipeline, Runnable task) {
75 | try {
76 | task.run();
77 | return Channels.succeededFuture(pipeline.getChannel());
78 | } catch (Throwable t) {
79 | return Channels.failedFuture(pipeline.getChannel(), t);
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/impl/AbstractServerChannel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core.impl;
17 |
18 | import org.jboss.netty.channel.future.ChannelFuture;
19 | import org.jboss.netty.channel.core.Channel;
20 | import org.jboss.netty.channel.core.ChannelFactory;
21 | import org.jboss.netty.channel.core.ChannelPipeline;
22 | import org.jboss.netty.channel.core.ChannelSink;
23 | import org.jboss.netty.channel.core.ServerChannel;
24 |
25 | import java.net.SocketAddress;
26 |
27 | /**
28 | * A skeletal server-side {@link Channel} implementation. A server-side
29 | * {@link Channel} does not allow the following operations:
30 | *
31 | * - {@link #connect(SocketAddress)}
32 | * - {@link #disconnect()}
33 | * - {@link #getInterestOps()}
34 | * - {@link #setInterestOps(int)}
35 | * - {@link #write(Object)}
36 | * - {@link #write(Object, SocketAddress)}
37 | * - and the shortcut methods which calls the methods mentioned above
38 | *
39 | */
40 | public abstract class AbstractServerChannel extends AbstractChannel implements ServerChannel {
41 |
42 | /**
43 | * Creates a new instance.
44 | *
45 | * @param factory
46 | * the factory which created this channel
47 | * @param pipeline
48 | * the pipeline which is going to be attached to this channel
49 | * @param sink
50 | * the sink which will receive downstream events from the pipeline
51 | * and send upstream events to the pipeline
52 | */
53 | protected AbstractServerChannel(
54 | ChannelFactory factory,
55 | ChannelPipeline pipeline,
56 | ChannelSink sink) {
57 | super(null, factory, pipeline, sink);
58 | }
59 |
60 | @Override
61 | public ChannelFuture connect(SocketAddress remoteAddress) {
62 | return getUnsupportedOperationFuture();
63 | }
64 |
65 | @Override
66 | public ChannelFuture disconnect() {
67 | return getUnsupportedOperationFuture();
68 | }
69 |
70 | @Override
71 | public int getInterestOps() {
72 | return OP_NONE;
73 | }
74 |
75 | @Override
76 | public ChannelFuture setInterestOps(int interestOps) {
77 | return getUnsupportedOperationFuture();
78 | }
79 |
80 | @Override
81 | protected void setInterestOpsNow(int interestOps) {
82 | // Ignore.
83 | }
84 |
85 | @Override
86 | public ChannelFuture write(Object message) {
87 | return getUnsupportedOperationFuture();
88 | }
89 |
90 | @Override
91 | public ChannelFuture write(Object message, SocketAddress remoteAddress) {
92 | return getUnsupportedOperationFuture();
93 | }
94 |
95 | public boolean isConnected() {
96 | return false;
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/impl/AdaptiveReceiveBufferSizePredictorFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core.impl;
17 |
18 | import org.jboss.netty.channel.core.ReceiveBufferSizePredictor;
19 | import org.jboss.netty.channel.core.ReceiveBufferSizePredictorFactory;
20 |
21 | /**
22 | * The {@link ReceiveBufferSizePredictorFactory} that creates a new
23 | * {@link AdaptiveReceiveBufferSizePredictor}.
24 | */
25 | public class AdaptiveReceiveBufferSizePredictorFactory implements
26 | ReceiveBufferSizePredictorFactory {
27 |
28 | private final int minimum;
29 | private final int initial;
30 | private final int maximum;
31 |
32 | /**
33 | * Creates a new factory with the default parameters. With the default
34 | * parameters, the expected buffer size starts from {@code 1024}, does not
35 | * go down below {@code 64}, and does not go up above {@code 65536}.
36 | */
37 | public AdaptiveReceiveBufferSizePredictorFactory() {
38 | this(AdaptiveReceiveBufferSizePredictor.DEFAULT_MINIMUM,
39 | AdaptiveReceiveBufferSizePredictor.DEFAULT_INITIAL,
40 | AdaptiveReceiveBufferSizePredictor.DEFAULT_MAXIMUM);
41 | }
42 |
43 | /**
44 | * Creates a new factory with the specified parameters.
45 | *
46 | * @param minimum the inclusive lower bound of the expected buffer size
47 | * @param initial the initial buffer size when no feed back was received
48 | * @param maximum the inclusive upper bound of the expected buffer size
49 | */
50 | public AdaptiveReceiveBufferSizePredictorFactory(int minimum, int initial, int maximum) {
51 | if (minimum <= 0) {
52 | throw new IllegalArgumentException("minimum: " + minimum);
53 | }
54 | if (initial < minimum) {
55 | throw new IllegalArgumentException("initial: " + initial);
56 | }
57 | if (maximum < initial) {
58 | throw new IllegalArgumentException("maximum: " + maximum);
59 | }
60 |
61 | this.minimum = minimum;
62 | this.initial = initial;
63 | this.maximum = maximum;
64 | }
65 |
66 | public ReceiveBufferSizePredictor getPredictor() throws Exception {
67 | return new AdaptiveReceiveBufferSizePredictor(minimum, initial, maximum);
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/impl/DefaultChannelConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core.impl;
17 |
18 | import org.jboss.netty.buffer.ChannelBufferFactory;
19 | import org.jboss.netty.buffer.impl.HeapChannelBufferFactory;
20 | import org.jboss.netty.channel.core.ChannelConfig;
21 | import org.jboss.netty.channel.core.ChannelPipelineFactory;
22 | import org.jboss.netty.channel.socket.SocketChannelConfig;
23 | import org.jboss.netty.util.internal.ConversionUtil;
24 |
25 | import java.util.Map;
26 | import java.util.Map.Entry;
27 |
28 | /**
29 | * The default {@link SocketChannelConfig} implementation.
30 | */
31 | public class DefaultChannelConfig implements ChannelConfig {
32 |
33 | private volatile ChannelBufferFactory bufferFactory = HeapChannelBufferFactory.getInstance();
34 | private volatile int connectTimeoutMillis = 10000; // 10 seconds
35 |
36 | public void setOptions(Map options) {
37 | for (Entry e: options.entrySet()) {
38 | setOption(e.getKey(), e.getValue());
39 | }
40 | }
41 |
42 | public boolean setOption(String key, Object value) {
43 | if (key == null) {
44 | throw new NullPointerException("key");
45 | }
46 |
47 | if ("pipelineFactory".equals(key)) {
48 | setPipelineFactory((ChannelPipelineFactory) value);
49 | } else if ("connectTimeoutMillis".equals(key)) {
50 | setConnectTimeoutMillis(ConversionUtil.toInt(value));
51 | } else if ("bufferFactory".equals(key)) {
52 | setBufferFactory((ChannelBufferFactory) value);
53 | } else {
54 | return false;
55 | }
56 | return true;
57 | }
58 |
59 | public int getConnectTimeoutMillis() {
60 | return connectTimeoutMillis;
61 | }
62 |
63 | public ChannelBufferFactory getBufferFactory() {
64 | return bufferFactory;
65 | }
66 |
67 | public void setBufferFactory(ChannelBufferFactory bufferFactory) {
68 | if (bufferFactory == null) {
69 | throw new NullPointerException("bufferFactory");
70 | }
71 | this.bufferFactory = bufferFactory;
72 | }
73 |
74 | public ChannelPipelineFactory getPipelineFactory() {
75 | return null;
76 | }
77 |
78 | public void setConnectTimeoutMillis(int connectTimeoutMillis) {
79 | if (connectTimeoutMillis < 0) {
80 | throw new IllegalArgumentException("connectTimeoutMillis: " + connectTimeoutMillis);
81 | }
82 | this.connectTimeoutMillis = connectTimeoutMillis;
83 | }
84 |
85 | public void setPipelineFactory(ChannelPipelineFactory pipelineFactory) {
86 | // Unused
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/impl/DefaultFileRegion.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core.impl;
17 |
18 | import org.jboss.netty.channel.core.FileRegion;
19 | import org.jboss.netty.logging.InternalLogger;
20 | import org.jboss.netty.logging.InternalLoggerFactory;
21 |
22 | import java.io.IOException;
23 | import java.nio.channels.FileChannel;
24 | import java.nio.channels.WritableByteChannel;
25 |
26 | public class DefaultFileRegion implements FileRegion {
27 |
28 | private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultFileRegion.class);
29 |
30 | private final FileChannel file;
31 | private final long position;
32 | private final long count;
33 | private final boolean releaseAfterTransfer;
34 |
35 | public DefaultFileRegion(FileChannel file, long position, long count) {
36 | this(file, position, count, false);
37 | }
38 |
39 | public DefaultFileRegion(FileChannel file, long position, long count, boolean releaseAfterTransfer) {
40 | this.file = file;
41 | this.position = position;
42 | this.count = count;
43 | this.releaseAfterTransfer = releaseAfterTransfer;
44 | }
45 |
46 | public long getPosition() {
47 | return position;
48 | }
49 |
50 | public long getCount() {
51 | return count;
52 | }
53 |
54 | public boolean releaseAfterTransfer() {
55 | return releaseAfterTransfer;
56 | }
57 |
58 | public long transferTo(WritableByteChannel target, long position) throws IOException {
59 | long count = this.count - position;
60 | if (count < 0 || position < 0) {
61 | throw new IllegalArgumentException(
62 | "position out of range: " + position +
63 | " (expected: 0 - " + (this.count - 1) + ')');
64 | }
65 | if (count == 0) {
66 | return 0L;
67 | }
68 |
69 | return file.transferTo(this.position + position, count, target);
70 | }
71 |
72 | public void releaseExternalResources() {
73 | try {
74 | file.close();
75 | } catch (IOException e) {
76 | if (logger.isWarnEnabled()) {
77 | logger.warn("Failed to close a file.", e);
78 | }
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/impl/DefaultServerChannelConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core.impl;
17 |
18 | import org.jboss.netty.buffer.ChannelBufferFactory;
19 | import org.jboss.netty.buffer.impl.HeapChannelBufferFactory;
20 | import org.jboss.netty.channel.core.ChannelConfig;
21 | import org.jboss.netty.channel.core.ChannelPipelineFactory;
22 | import org.jboss.netty.channel.socket.ServerSocketChannelConfig;
23 |
24 | import java.util.Map;
25 | import java.util.Map.Entry;
26 |
27 | /**
28 | * The default {@link ServerSocketChannelConfig} implementation.
29 | */
30 | public class DefaultServerChannelConfig implements ChannelConfig {
31 |
32 | private volatile ChannelPipelineFactory pipelineFactory;
33 | private volatile ChannelBufferFactory bufferFactory = HeapChannelBufferFactory.getInstance();
34 |
35 | public void setOptions(Map options) {
36 | for (Entry e: options.entrySet()) {
37 | setOption(e.getKey(), e.getValue());
38 | }
39 | }
40 |
41 | /**
42 | * Sets an individual option. You can override this method to support
43 | * additional configuration parameters.
44 | */
45 | public boolean setOption(String key, Object value) {
46 | if (key == null) {
47 | throw new NullPointerException("key");
48 | }
49 | if ("pipelineFactory".equals(key)) {
50 | setPipelineFactory((ChannelPipelineFactory) value);
51 | } else if ("bufferFactory".equals(key)) {
52 | setBufferFactory((ChannelBufferFactory) value);
53 | } else {
54 | return false;
55 | }
56 | return true;
57 | }
58 |
59 | public ChannelPipelineFactory getPipelineFactory() {
60 | return pipelineFactory;
61 | }
62 |
63 | public void setPipelineFactory(ChannelPipelineFactory pipelineFactory) {
64 | if (pipelineFactory == null) {
65 | throw new NullPointerException("pipelineFactory");
66 | }
67 | this.pipelineFactory = pipelineFactory;
68 | }
69 |
70 | public ChannelBufferFactory getBufferFactory() {
71 | return bufferFactory;
72 | }
73 |
74 | public void setBufferFactory(ChannelBufferFactory bufferFactory) {
75 | if (bufferFactory == null) {
76 | throw new NullPointerException("bufferFactory");
77 | }
78 |
79 | this.bufferFactory = bufferFactory;
80 | }
81 |
82 | public int getConnectTimeoutMillis() {
83 | return 0;
84 | }
85 |
86 | public void setConnectTimeoutMillis(int connectTimeoutMillis) {
87 | // Unused
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/impl/FixedReceiveBufferSizePredictor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core.impl;
17 |
18 | import org.jboss.netty.channel.core.ReceiveBufferSizePredictor;
19 |
20 | /**
21 | * The {@link ReceiveBufferSizePredictor} that always yields the same buffer
22 | * size prediction. This predictor ignores the feed back from the I/O thread.
23 | */
24 | public class FixedReceiveBufferSizePredictor implements
25 | ReceiveBufferSizePredictor {
26 |
27 | private final int bufferSize;
28 |
29 | /**
30 | * Creates a new predictor that always returns the same prediction of
31 | * the specified buffer size.
32 | */
33 | public FixedReceiveBufferSizePredictor(int bufferSize) {
34 | if (bufferSize <= 0) {
35 | throw new IllegalArgumentException(
36 | "bufferSize must greater than 0: " + bufferSize);
37 | }
38 | this.bufferSize = bufferSize;
39 | }
40 |
41 | public int nextReceiveBufferSize() {
42 | return bufferSize;
43 | }
44 |
45 | public void previousReceiveBufferSize(int previousReceiveBufferSize) {
46 | // Ignore
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/core/impl/FixedReceiveBufferSizePredictorFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.core.impl;
17 |
18 | import org.jboss.netty.channel.core.ReceiveBufferSizePredictor;
19 | import org.jboss.netty.channel.core.ReceiveBufferSizePredictorFactory;
20 |
21 | /**
22 | * The {@link ReceiveBufferSizePredictorFactory} that returns a
23 | * {@link FixedReceiveBufferSizePredictor} with the pre-defined configuration.
24 | */
25 | public class FixedReceiveBufferSizePredictorFactory implements
26 | ReceiveBufferSizePredictorFactory {
27 |
28 | private final ReceiveBufferSizePredictor predictor;
29 |
30 | /**
31 | * Creates a new factory that returns a {@link FixedReceiveBufferSizePredictor}
32 | * which always returns the same prediction of the specified buffer size.
33 | */
34 | public FixedReceiveBufferSizePredictorFactory(int bufferSize) {
35 | predictor = new FixedReceiveBufferSizePredictor(bufferSize);
36 | }
37 |
38 | public ReceiveBufferSizePredictor getPredictor() throws Exception {
39 | return predictor;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/ChannelStateEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event;
17 |
18 |
19 | import org.jboss.netty.channel.core.Channel;
20 | import org.jboss.netty.channel.core.ChannelState;
21 |
22 | /**
23 | * A {@link ChannelEvent} which represents the change of the {@link Channel}
24 | * state. It can mean the notification of a change or the request for a
25 | * change, depending on whether it is an upstream event or a downstream event
26 | * respectively. Please refer to the {@link ChannelEvent} documentation to
27 | * find out what an upstream event and a downstream event are and what
28 | * fundamental differences they have.
29 | *
30 | * @apiviz.has org.jboss.netty.channel.skeleton.ChannelState
31 | */
32 | public interface ChannelStateEvent extends ChannelEvent {
33 |
34 | /**
35 | * Returns the changed property of the {@link Channel}.
36 | */
37 | ChannelState getState();
38 |
39 | /**
40 | * Returns the value of the changed property of the {@link Channel}.
41 | * Please refer to {@link ChannelState} documentation to find out the
42 | * allowed values for each property.
43 | */
44 | Object getValue();
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/ChildChannelStateEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 |
20 | /**
21 | * A {@link ChannelEvent} which represents the notification of the state of
22 | * a child {@link Channel}. This event is for going upstream only. Please
23 | * refer to the {@link ChannelEvent} documentation to find out what an upstream
24 | * event and a downstream event are and what fundamental differences they have.
25 | */
26 | public interface ChildChannelStateEvent extends ChannelEvent {
27 |
28 | /**
29 | * Returns the parent {@link Channel} which is associated
30 | * with this event. Please note that you should use {@link #getChildChannel()}
31 | * to get the {@link Channel} created or accepted by the parent {@link Channel}.
32 | */
33 | Channel getChannel();
34 |
35 | /**
36 | * Returns the child {@link Channel} whose state has been changed.
37 | */
38 | Channel getChildChannel();
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/ExceptionEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event;
17 |
18 | import org.jboss.netty.channel.core.ChannelHandler;
19 |
20 | /**
21 | * A {@link ChannelEvent} which represents the notification of an exception
22 | * raised by a {@link ChannelHandler} or an I/O thread. This event is for
23 | * going upstream only. Please refer to the {@link ChannelEvent} documentation
24 | * to find out what an upstream event and a downstream event are and what
25 | * fundamental differences they have.
26 | */
27 | public interface ExceptionEvent extends ChannelEvent {
28 |
29 | /**
30 | * Returns the raised exception.
31 | */
32 | Throwable getCause();
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/MessageEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event;
17 |
18 | import java.net.SocketAddress;
19 |
20 | /**
21 | * A {@link ChannelEvent} which represents the transmission or reception of a
22 | * message. It can mean the notification of a received message or the request
23 | * for writing a message, depending on whether it is an upstream event or a
24 | * downstream event respectively. Please refer to the {@link ChannelEvent}
25 | * documentation to find out what an upstream event and a downstream event are
26 | * and what fundamental differences they have.
27 | */
28 | public interface MessageEvent extends ChannelEvent {
29 |
30 | /**
31 | * Returns the message.
32 | */
33 | Object getMessage();
34 |
35 | /**
36 | * Returns the remote address of the message.
37 | */
38 | SocketAddress getRemoteAddress();
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/WriteCompletionEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 |
20 | /**
21 | * A {@link ChannelEvent} which represents the notification of the completion
22 | * of a write request on a {@link Channel}. This event is for going upstream
23 | * only. Please refer to the {@link ChannelEvent} documentation to find out
24 | * what an upstream event and a downstream event are and what fundamental
25 | * differences they have.
26 | */
27 | public interface WriteCompletionEvent extends ChannelEvent {
28 | /**
29 | * Returns the amount of data written.
30 | *
31 | * @return the number of written bytes or messages, depending on the
32 | * type of the transport
33 | */
34 | long getWrittenAmount();
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/impl/DefaultChildChannelStateEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event.impl;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 | import org.jboss.netty.channel.event.ChildChannelStateEvent;
20 | import org.jboss.netty.channel.future.ChannelFuture;
21 |
22 | import static org.jboss.netty.channel.core.Channels.*;
23 |
24 | /**
25 | * The default {@link ChildChannelStateEvent} implementation.
26 | */
27 | public class DefaultChildChannelStateEvent implements ChildChannelStateEvent {
28 |
29 | private final Channel parentChannel;
30 | private final Channel childChannel;
31 |
32 | /**
33 | * Creates a new instance.
34 | */
35 | public DefaultChildChannelStateEvent(Channel parentChannel, Channel childChannel) {
36 | if (parentChannel == null) {
37 | throw new NullPointerException("parentChannel");
38 | }
39 | if (childChannel == null) {
40 | throw new NullPointerException("childChannel");
41 | }
42 | this.parentChannel = parentChannel;
43 | this.childChannel = childChannel;
44 | }
45 |
46 | public Channel getChannel() {
47 | return parentChannel;
48 | }
49 |
50 | public ChannelFuture getFuture() {
51 | return succeededFuture(getChannel());
52 | }
53 |
54 | public Channel getChildChannel() {
55 | return childChannel;
56 | }
57 |
58 | @Override
59 | public String toString() {
60 | String channelString = getChannel().toString();
61 | StringBuilder buf = new StringBuilder(channelString.length() + 32);
62 | buf.append(channelString);
63 | buf.append(getChildChannel().isOpen()? " CHILD_OPEN: " : " CHILD_CLOSED: ");
64 | buf.append(getChildChannel().getId());
65 | return buf.toString();
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/impl/DefaultExceptionEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event.impl;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 | import org.jboss.netty.channel.event.ExceptionEvent;
20 | import org.jboss.netty.channel.future.ChannelFuture;
21 |
22 | import static org.jboss.netty.channel.core.Channels.*;
23 |
24 | /**
25 | * The default {@link ExceptionEvent} implementation.
26 | */
27 | public class DefaultExceptionEvent implements ExceptionEvent {
28 |
29 | private final Channel channel;
30 | private final Throwable cause;
31 |
32 | /**
33 | * Creates a new instance.
34 | */
35 | public DefaultExceptionEvent(Channel channel, Throwable cause) {
36 | if (channel == null) {
37 | throw new NullPointerException("channel");
38 | }
39 | if (cause == null) {
40 | throw new NullPointerException("cause");
41 | }
42 | this.channel = channel;
43 | this.cause = cause;
44 | }
45 |
46 | public Channel getChannel() {
47 | return channel;
48 | }
49 |
50 | public ChannelFuture getFuture() {
51 | return succeededFuture(getChannel());
52 | }
53 |
54 | public Throwable getCause() {
55 | return cause;
56 | }
57 |
58 | @Override
59 | public String toString() {
60 | return getChannel().toString() + " EXCEPTION: " + cause;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/impl/DefaultWriteCompletionEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event.impl;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 | import org.jboss.netty.channel.event.WriteCompletionEvent;
20 | import org.jboss.netty.channel.future.ChannelFuture;
21 |
22 | import static org.jboss.netty.channel.core.Channels.*;
23 |
24 | /**
25 | * The default {@link WriteCompletionEvent} implementation.
26 | */
27 | public class DefaultWriteCompletionEvent implements WriteCompletionEvent {
28 |
29 | private final Channel channel;
30 | private final long writtenAmount;
31 |
32 | /**
33 | * Creates a new instance.
34 | */
35 | public DefaultWriteCompletionEvent(Channel channel, long writtenAmount) {
36 | if (channel == null) {
37 | throw new NullPointerException("channel");
38 | }
39 | if (writtenAmount <= 0) {
40 | throw new IllegalArgumentException(
41 | "writtenAmount must be a positive integer: " + writtenAmount);
42 | }
43 |
44 | this.channel = channel;
45 | this.writtenAmount = writtenAmount;
46 | }
47 |
48 | public Channel getChannel() {
49 | return channel;
50 | }
51 |
52 | public ChannelFuture getFuture() {
53 | return succeededFuture(getChannel());
54 | }
55 |
56 | public long getWrittenAmount() {
57 | return writtenAmount;
58 | }
59 |
60 | @Override
61 | public String toString() {
62 | String channelString = getChannel().toString();
63 | StringBuilder buf = new StringBuilder(channelString.length() + 32);
64 | buf.append(channelString);
65 | buf.append(" WRITTEN_AMOUNT: ");
66 | buf.append(getWrittenAmount());
67 | return buf.toString();
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/impl/DownstreamChannelStateEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event.impl;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 | import org.jboss.netty.channel.event.ChannelStateEvent;
20 | import org.jboss.netty.channel.future.ChannelFuture;
21 | import org.jboss.netty.channel.core.ChannelState;
22 |
23 | /**
24 | * The default downstream {@link ChannelStateEvent} implementation.
25 | */
26 | public class DownstreamChannelStateEvent implements ChannelStateEvent {
27 |
28 | private final Channel channel;
29 | private final ChannelFuture future;
30 | private final ChannelState state;
31 | private final Object value;
32 |
33 | /**
34 | * Creates a new instance.
35 | */
36 | public DownstreamChannelStateEvent(
37 | Channel channel, ChannelFuture future,
38 | ChannelState state, Object value) {
39 |
40 | if (channel == null) {
41 | throw new NullPointerException("channel");
42 | }
43 | if (future == null) {
44 | throw new NullPointerException("future");
45 | }
46 | if (state == null) {
47 | throw new NullPointerException("state");
48 | }
49 | this.channel = channel;
50 | this.future = future;
51 | this.state = state;
52 | this.value = value;
53 | }
54 |
55 | public Channel getChannel() {
56 | return channel;
57 | }
58 |
59 | public ChannelFuture getFuture() {
60 | return future;
61 | }
62 |
63 | public ChannelState getState() {
64 | return state;
65 | }
66 |
67 | public Object getValue() {
68 | return value;
69 | }
70 |
71 | @Override
72 | public String toString() {
73 | String channelString = getChannel().toString();
74 | StringBuilder buf = new StringBuilder(channelString.length() + 64);
75 | buf.append(channelString);
76 | switch (getState()) {
77 | case OPEN:
78 | if (Boolean.TRUE.equals(getValue())) {
79 | buf.append(" OPEN");
80 | } else {
81 | buf.append(" CLOSE");
82 | }
83 | break;
84 | case BOUND:
85 | if (getValue() != null) {
86 | buf.append(" BIND: ");
87 | buf.append(getValue());
88 | } else {
89 | buf.append(" UNBIND");
90 | }
91 | break;
92 | case CONNECTED:
93 | if (getValue() != null) {
94 | buf.append(" CONNECT: ");
95 | buf.append(getValue());
96 | } else {
97 | buf.append(" DISCONNECT");
98 | }
99 | break;
100 | case INTEREST_OPS:
101 | buf.append(" CHANGE_INTEREST: ");
102 | buf.append(getValue());
103 | break;
104 | default:
105 | buf.append(' ');
106 | buf.append(getState().name());
107 | buf.append(": ");
108 | buf.append(getValue());
109 | }
110 | return buf.toString();
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/impl/DownstreamMessageEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event.impl;
17 |
18 | import java.net.SocketAddress;
19 |
20 | import org.jboss.netty.channel.core.Channel;
21 | import org.jboss.netty.channel.event.MessageEvent;
22 | import org.jboss.netty.channel.future.ChannelFuture;
23 | import org.jboss.netty.util.internal.StringUtil;
24 |
25 | /**
26 | * The default downstream {@link MessageEvent} implementation.
27 | */
28 | public class DownstreamMessageEvent implements MessageEvent {
29 |
30 | private final Channel channel;
31 | private final ChannelFuture future;
32 | private final Object message;
33 | private final SocketAddress remoteAddress;
34 |
35 | /**
36 | * Creates a new instance.
37 | */
38 | public DownstreamMessageEvent(
39 | Channel channel, ChannelFuture future,
40 | Object message, SocketAddress remoteAddress) {
41 |
42 | if (channel == null) {
43 | throw new NullPointerException("channel");
44 | }
45 | if (future == null) {
46 | throw new NullPointerException("future");
47 | }
48 | if (message == null) {
49 | throw new NullPointerException("message");
50 | }
51 | this.channel = channel;
52 | this.future = future;
53 | this.message = message;
54 | if (remoteAddress != null) {
55 | this.remoteAddress = remoteAddress;
56 | } else {
57 | this.remoteAddress = channel.getRemoteAddress();
58 | }
59 | }
60 |
61 | public Channel getChannel() {
62 | return channel;
63 | }
64 |
65 | public ChannelFuture getFuture() {
66 | return future;
67 | }
68 |
69 | public Object getMessage() {
70 | return message;
71 | }
72 |
73 | public SocketAddress getRemoteAddress() {
74 | return remoteAddress;
75 | }
76 |
77 | @Override
78 | public String toString() {
79 | if (getRemoteAddress() == getChannel().getRemoteAddress()) {
80 | return getChannel().toString() + " WRITE: " +
81 | StringUtil.stripControlCharacters(getMessage());
82 | } else {
83 | return getChannel().toString() + " WRITE: " +
84 | StringUtil.stripControlCharacters(getMessage()) + " to " +
85 | getRemoteAddress();
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/impl/UpstreamChannelStateEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event.impl;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 | import org.jboss.netty.channel.event.ChannelStateEvent;
20 | import org.jboss.netty.channel.future.ChannelFuture;
21 | import org.jboss.netty.channel.core.ChannelState;
22 |
23 | import static org.jboss.netty.channel.core.Channels.*;
24 |
25 | /**
26 | * The default upstream {@link ChannelStateEvent} implementation.
27 | */
28 | public class UpstreamChannelStateEvent implements ChannelStateEvent {
29 |
30 | private final Channel channel;
31 | private final ChannelState state;
32 | private final Object value;
33 |
34 | /**
35 | * Creates a new instance.
36 | */
37 | public UpstreamChannelStateEvent(
38 | Channel channel, ChannelState state, Object value) {
39 |
40 | if (channel == null) {
41 | throw new NullPointerException("channel");
42 | }
43 | if (state == null) {
44 | throw new NullPointerException("state");
45 | }
46 |
47 | this.channel = channel;
48 | this.state = state;
49 | this.value = value;
50 | }
51 |
52 | public Channel getChannel() {
53 | return channel;
54 | }
55 |
56 | public ChannelFuture getFuture() {
57 | return succeededFuture(getChannel());
58 | }
59 |
60 | public ChannelState getState() {
61 | return state;
62 | }
63 |
64 | public Object getValue() {
65 | return value;
66 | }
67 |
68 | @Override
69 | public String toString() {
70 | String channelString = getChannel().toString();
71 | StringBuilder buf = new StringBuilder(channelString.length() + 64);
72 | buf.append(channelString);
73 | switch (getState()) {
74 | case OPEN:
75 | if (Boolean.TRUE.equals(getValue())) {
76 | buf.append(" OPEN");
77 | } else {
78 | buf.append(" CLOSED");
79 | }
80 | break;
81 | case BOUND:
82 | if (getValue() != null) {
83 | buf.append(" BOUND: ");
84 | buf.append(getValue());
85 | } else {
86 | buf.append(" UNBOUND");
87 | }
88 | break;
89 | case CONNECTED:
90 | if (getValue() != null) {
91 | buf.append(" CONNECTED: ");
92 | buf.append(getValue());
93 | } else {
94 | buf.append(" DISCONNECTED");
95 | }
96 | break;
97 | case INTEREST_OPS:
98 | buf.append(" INTEREST_CHANGED");
99 | break;
100 | default:
101 | buf.append(getState().name());
102 | buf.append(": ");
103 | buf.append(getValue());
104 | }
105 | return buf.toString();
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/event/impl/UpstreamMessageEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.event.impl;
17 |
18 | import static org.jboss.netty.channel.core.Channels.*;
19 |
20 | import java.net.SocketAddress;
21 |
22 | import org.jboss.netty.channel.core.Channel;
23 | import org.jboss.netty.channel.event.MessageEvent;
24 | import org.jboss.netty.channel.future.ChannelFuture;
25 | import org.jboss.netty.util.internal.StringUtil;
26 |
27 | /**
28 | * The default upstream {@link MessageEvent} implementation.
29 | */
30 | public class UpstreamMessageEvent implements MessageEvent {
31 |
32 | private final Channel channel;
33 | private final Object message;
34 | private final SocketAddress remoteAddress;
35 |
36 | /**
37 | * Creates a new instance.
38 | */
39 | public UpstreamMessageEvent(
40 | Channel channel, Object message, SocketAddress remoteAddress) {
41 |
42 | if (channel == null) {
43 | throw new NullPointerException("channel");
44 | }
45 | if (message == null) {
46 | throw new NullPointerException("message");
47 | }
48 | this.channel = channel;
49 | this.message = message;
50 | if (remoteAddress != null) {
51 | this.remoteAddress = remoteAddress;
52 | } else {
53 | this.remoteAddress = channel.getRemoteAddress();
54 | }
55 | }
56 |
57 | public Channel getChannel() {
58 | return channel;
59 | }
60 |
61 | public ChannelFuture getFuture() {
62 | return succeededFuture(getChannel());
63 | }
64 |
65 | public Object getMessage() {
66 | return message;
67 | }
68 |
69 | public SocketAddress getRemoteAddress() {
70 | return remoteAddress;
71 | }
72 |
73 | @Override
74 | public String toString() {
75 | if (getRemoteAddress() == getChannel().getRemoteAddress()) {
76 | return getChannel().toString() + " RECEIVED: " +
77 | StringUtil.stripControlCharacters(getMessage());
78 | } else {
79 | return getChannel().toString() + " RECEIVED: " +
80 | StringUtil.stripControlCharacters(getMessage()) + " from " +
81 | getRemoteAddress();
82 | }
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/exception/ChannelException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.exception;
17 |
18 | /**
19 | * A {@link RuntimeException} which is thrown when an I/O operation fails.
20 | *
21 | * @apiviz.exclude
22 | */
23 | public class ChannelException extends RuntimeException {
24 |
25 | private static final long serialVersionUID = 2908618315971075004L;
26 |
27 | /**
28 | * Creates a new exception.
29 | */
30 | public ChannelException() {
31 | }
32 |
33 | /**
34 | * Creates a new exception.
35 | */
36 | public ChannelException(String message, Throwable cause) {
37 | super(message, cause);
38 | }
39 |
40 | /**
41 | * Creates a new exception.
42 | */
43 | public ChannelException(String message) {
44 | super(message);
45 | }
46 |
47 | /**
48 | * Creates a new exception.
49 | */
50 | public ChannelException(Throwable cause) {
51 | super(cause);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/exception/ChannelHandlerLifeCycleException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.exception;
17 |
18 | import org.jboss.netty.channel.core.LifeCycleAwareChannelHandler;
19 |
20 | /**
21 | * A {@link RuntimeException} which is thrown when a
22 | * {@link LifeCycleAwareChannelHandler} throws an {@link Exception}
23 | * in its handler methods.
24 | *
25 | * @apiviz.exclude
26 | */
27 | public class ChannelHandlerLifeCycleException extends RuntimeException {
28 |
29 | private static final long serialVersionUID = 8764799996088850672L;
30 |
31 | /**
32 | * Creates a new exception.
33 | */
34 | public ChannelHandlerLifeCycleException() {
35 | }
36 |
37 | /**
38 | * Creates a new exception.
39 | */
40 | public ChannelHandlerLifeCycleException(String message, Throwable cause) {
41 | super(message, cause);
42 | }
43 |
44 | /**
45 | * Creates a new exception.
46 | */
47 | public ChannelHandlerLifeCycleException(String message) {
48 | super(message);
49 | }
50 |
51 | /**
52 | * Creates a new exception.
53 | */
54 | public ChannelHandlerLifeCycleException(Throwable cause) {
55 | super(cause);
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/exception/ChannelPipelineException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.exception;
17 |
18 | import org.jboss.netty.channel.event.ChannelEvent;
19 | import org.jboss.netty.channel.core.ChannelPipeline;
20 | import org.jboss.netty.channel.core.ChannelPipelineFactory;
21 |
22 | /**
23 | * A {@link ChannelException} which is thrown when a {@link ChannelPipeline}
24 | * failed to process a {@link ChannelEvent} or when a {@link ChannelPipelineFactory}
25 | * failed to initialize a {@link ChannelPipeline}.
26 | *
27 | * @apiviz.exclude
28 | */
29 | public class ChannelPipelineException extends ChannelException {
30 |
31 | private static final long serialVersionUID = 3379174210419885980L;
32 |
33 | /**
34 | * Creates a new instance.
35 | */
36 | public ChannelPipelineException() {
37 | }
38 |
39 | /**
40 | * Creates a new instance.
41 | */
42 | public ChannelPipelineException(String message, Throwable cause) {
43 | super(message, cause);
44 | }
45 |
46 | /**
47 | * Creates a new instance.
48 | */
49 | public ChannelPipelineException(String message) {
50 | super(message);
51 | }
52 |
53 | /**
54 | * Creates a new instance.
55 | */
56 | public ChannelPipelineException(Throwable cause) {
57 | super(cause);
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/exception/ConnectTimeoutException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.exception;
17 |
18 | import java.net.ConnectException;
19 |
20 | /**
21 | * {@link ConnectException} which will be thrown if a connection could
22 | * not be established because of a connection timeout.
23 | */
24 | public class ConnectTimeoutException extends ConnectException {
25 | private static final long serialVersionUID = 2317065249988317463L;
26 |
27 | public ConnectTimeoutException(String msg) {
28 | super(msg);
29 | }
30 |
31 | public ConnectTimeoutException() {
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/future/ChannelFutureListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.future;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 |
20 | import java.util.EventListener;
21 |
22 | /**
23 | * Listens to the result of a {@link ChannelFuture}. The result of the
24 | * asynchronous {@link Channel} I/O operation is notified once this listener
25 | * is added by calling {@link ChannelFuture#addListener(ChannelFutureListener)}.
26 | *
27 | * Return the control to the caller quickly
28 | *
29 | * {@link #operationComplete(ChannelFuture)} is directly called by an I/O
30 | * thread. Therefore, performing a time consuming task or a blocking operation
31 | * in the handler method can cause an unexpected pause during I/O. If you need
32 | * to perform a blocking operation on I/O completion, try to execute the
33 | * operation in a different thread using a thread pool.
34 | */
35 | public interface ChannelFutureListener extends EventListener {
36 |
37 | /**
38 | * A {@link ChannelFutureListener} that closes the {@link Channel} which is
39 | * associated with the specified {@link ChannelFuture}.
40 | */
41 | ChannelFutureListener CLOSE = new ChannelFutureListener() {
42 | public void operationComplete(ChannelFuture future) {
43 | future.getChannel().close();
44 | }
45 | };
46 |
47 | /**
48 | * A {@link ChannelFutureListener} that closes the {@link Channel} when the
49 | * operation ended up with a failure or cancellation rather than a success.
50 | */
51 | ChannelFutureListener CLOSE_ON_FAILURE = new ChannelFutureListener() {
52 | public void operationComplete(ChannelFuture future) {
53 | if (!future.isSuccess()) {
54 | future.getChannel().close();
55 | }
56 | }
57 | };
58 |
59 | /**
60 | * Invoked when the I/O operation associated with the {@link ChannelFuture}
61 | * has been completed.
62 | *
63 | * @param future the source {@link ChannelFuture} which called this
64 | * callback
65 | */
66 | void operationComplete(ChannelFuture future) throws Exception;
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/future/ChannelFutureProgressListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.future;
17 |
18 |
19 | /**
20 | * Listens to the progress of a time-consuming I/O operation such as a large
21 | * file transfer. If this listener is added to a {@link ChannelFuture} of an
22 | * I/O operation that supports progress notification, the listener's
23 | * {@link #operationProgressed(ChannelFuture, long, long, long)} method will be
24 | * called back by an I/O thread. If the operation does not support progress
25 | * notification, {@link #operationProgressed(ChannelFuture, long, long, long)}
26 | * will not be invoked. Like a usual {@link ChannelFutureListener} that this
27 | * interface extends, {@link #operationComplete(ChannelFuture)} will be called
28 | * when the future is marked as complete.
29 | *
30 | * Return the control to the caller quickly
31 | *
32 | * {@link #operationProgressed(ChannelFuture, long, long, long)} and
33 | * {@link #operationComplete(ChannelFuture)} is directly called by an I/O
34 | * thread. Therefore, performing a time consuming task or a blocking operation
35 | * in the handler method can cause an unexpected pause during I/O. If you need
36 | * to perform a blocking operation on I/O completion, try to execute the
37 | * operation in a different thread using a thread pool.
38 | */
39 | public interface ChannelFutureProgressListener extends ChannelFutureListener {
40 |
41 | /**
42 | * Invoked when the I/O operation associated with the {@link ChannelFuture}
43 | * has been progressed.
44 | *
45 | * @param future the source {@link ChannelFuture} which called this
46 | * callback
47 | */
48 | void operationProgressed(ChannelFuture future, long amount, long current, long total) throws Exception;
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/future/impl/FailedChannelFuture.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.future.impl;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 | import org.jboss.netty.channel.exception.ChannelException;
20 | import org.jboss.netty.channel.future.ChannelFuture;
21 | import org.jboss.netty.channel.core.Channels;
22 |
23 | /**
24 | * The {@link CompleteChannelFuture} which is failed already. It is
25 | * recommended to use {@link Channels#failedFuture(Channel, Throwable)}
26 | * instead of calling the constructor of this future.
27 | */
28 | public class FailedChannelFuture extends CompleteChannelFuture {
29 |
30 | private final Throwable cause;
31 |
32 | /**
33 | * Creates a new instance.
34 | *
35 | * @param channel the {@link Channel} associated with this future
36 | * @param cause the cause of failure
37 | */
38 | public FailedChannelFuture(Channel channel, Throwable cause) {
39 | super(channel);
40 | if (cause == null) {
41 | throw new NullPointerException("cause");
42 | }
43 | this.cause = cause;
44 | }
45 |
46 | public Throwable getCause() {
47 | return cause;
48 | }
49 |
50 | public boolean isSuccess() {
51 | return false;
52 | }
53 |
54 | @Deprecated
55 | public ChannelFuture rethrowIfFailed() throws Exception {
56 | if (cause instanceof Exception) {
57 | throw (Exception) cause;
58 | }
59 |
60 | if (cause instanceof Error) {
61 | throw (Error) cause;
62 | }
63 |
64 | throw new RuntimeException(cause);
65 | }
66 |
67 | public ChannelFuture sync() throws InterruptedException {
68 | rethrow();
69 | return this;
70 | }
71 |
72 | public ChannelFuture syncUninterruptibly() {
73 | rethrow();
74 | return this;
75 | }
76 |
77 | private void rethrow() {
78 | if (cause instanceof RuntimeException) {
79 | throw (RuntimeException) cause;
80 | }
81 |
82 | if (cause instanceof Error) {
83 | throw (Error) cause;
84 | }
85 |
86 | throw new ChannelException(cause);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/future/impl/SucceededChannelFuture.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.future.impl;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 | import org.jboss.netty.channel.future.ChannelFuture;
20 | import org.jboss.netty.channel.core.Channels;
21 |
22 | /**
23 | * The {@link CompleteChannelFuture} which is succeeded already. It is
24 | * recommended to use {@link Channels#succeededFuture(Channel)} instead of
25 | * calling the constructor of this future.
26 | */
27 | public class SucceededChannelFuture extends CompleteChannelFuture {
28 |
29 | /**
30 | * Creates a new instance.
31 | *
32 | * @param channel the {@link Channel} associated with this future
33 | */
34 | public SucceededChannelFuture(Channel channel) {
35 | super(channel);
36 | }
37 |
38 | public Throwable getCause() {
39 | return null;
40 | }
41 |
42 | public boolean isSuccess() {
43 | return true;
44 | }
45 |
46 | @Deprecated
47 | public ChannelFuture rethrowIfFailed() throws Exception {
48 | return this;
49 | }
50 |
51 | public ChannelFuture sync() throws InterruptedException {
52 | return this;
53 | }
54 |
55 | public ChannelFuture syncUninterruptibly() {
56 | return this;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/ChannelRunnableWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 | import org.jboss.netty.channel.future.impl.DefaultChannelFuture;
20 |
21 | public class ChannelRunnableWrapper extends DefaultChannelFuture implements Runnable {
22 |
23 | private final Runnable task;
24 | private boolean started;
25 |
26 | public ChannelRunnableWrapper(Channel channel, Runnable task) {
27 | super(channel, true);
28 | this.task = task;
29 | }
30 |
31 | public void run() {
32 | synchronized (this) {
33 | if (!isCancelled()) {
34 | started = true;
35 | } else {
36 | return;
37 | }
38 | }
39 | try {
40 | task.run();
41 | setSuccess();
42 | } catch (Throwable t) {
43 | setFailure(t);
44 | }
45 | }
46 |
47 | @Override
48 | public synchronized boolean cancel() {
49 | if (started) {
50 | return false;
51 | }
52 | return super.cancel();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/ClientSocketChannelFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket;
17 |
18 | import org.jboss.netty.channel.core.ChannelFactory;
19 | import org.jboss.netty.channel.core.ChannelPipeline;
20 |
21 | /**
22 | * A {@link ChannelFactory} which creates a client-side {@link SocketChannel}.
23 | *
24 | * @apiviz.has org.jboss.netty.channel.socket.SocketChannel oneway - - creates
25 | */
26 | public interface ClientSocketChannelFactory extends ChannelFactory {
27 | SocketChannel newChannel(ChannelPipeline pipeline);
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/DefaultServerSocketChannelConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket;
17 |
18 | import java.net.ServerSocket;
19 | import java.net.SocketException;
20 |
21 | import org.jboss.netty.channel.exception.ChannelException;
22 | import org.jboss.netty.channel.core.impl.DefaultServerChannelConfig;
23 | import org.jboss.netty.util.internal.ConversionUtil;
24 |
25 | /**
26 | * The default {@link ServerSocketChannelConfig} implementation.
27 | */
28 | public class DefaultServerSocketChannelConfig extends DefaultServerChannelConfig
29 | implements ServerSocketChannelConfig {
30 |
31 | private final ServerSocket socket;
32 | private volatile int backlog;
33 |
34 | /**
35 | * Creates a new instance.
36 | */
37 | public DefaultServerSocketChannelConfig(ServerSocket socket) {
38 | if (socket == null) {
39 | throw new NullPointerException("socket");
40 | }
41 | this.socket = socket;
42 | }
43 |
44 | @Override
45 | public boolean setOption(String key, Object value) {
46 | if (super.setOption(key, value)) {
47 | return true;
48 | }
49 |
50 | if ("receiveBufferSize".equals(key)) {
51 | setReceiveBufferSize(ConversionUtil.toInt(value));
52 | } else if ("reuseAddress".equals(key)) {
53 | setReuseAddress(ConversionUtil.toBoolean(value));
54 | } else if ("backlog".equals(key)) {
55 | setBacklog(ConversionUtil.toInt(value));
56 | } else {
57 | return false;
58 | }
59 | return true;
60 | }
61 |
62 | public boolean isReuseAddress() {
63 | try {
64 | return socket.getReuseAddress();
65 | } catch (SocketException e) {
66 | throw new ChannelException(e);
67 | }
68 | }
69 |
70 | public void setReuseAddress(boolean reuseAddress) {
71 | try {
72 | socket.setReuseAddress(reuseAddress);
73 | } catch (SocketException e) {
74 | throw new ChannelException(e);
75 | }
76 | }
77 |
78 | public int getReceiveBufferSize() {
79 | try {
80 | return socket.getReceiveBufferSize();
81 | } catch (SocketException e) {
82 | throw new ChannelException(e);
83 | }
84 | }
85 |
86 | public void setReceiveBufferSize(int receiveBufferSize) {
87 | try {
88 | socket.setReceiveBufferSize(receiveBufferSize);
89 | } catch (SocketException e) {
90 | throw new ChannelException(e);
91 | }
92 | }
93 |
94 | public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
95 | socket.setPerformancePreferences(connectionTime, latency, bandwidth);
96 | }
97 |
98 | public int getBacklog() {
99 | return backlog;
100 | }
101 |
102 | public void setBacklog(int backlog) {
103 | if (backlog < 0) {
104 | throw new IllegalArgumentException("backlog: " + backlog);
105 | }
106 | this.backlog = backlog;
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/InternetProtocolFamily.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket;
17 |
18 | /**
19 | * Internet Protocol (IP) families
20 | */
21 | public enum InternetProtocolFamily {
22 | IPv4,
23 | IPv6
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/ServerSocketChannel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket;
17 |
18 | import java.net.InetSocketAddress;
19 |
20 | import org.jboss.netty.channel.core.ServerChannel;
21 |
22 | /**
23 | * A TCP/IP {@link ServerChannel} which accepts incoming TCP/IP connections.
24 | *
25 | * @apiviz.landmark
26 | * @apiviz.composedOf org.jboss.netty.channel.socket.ServerSocketChannelConfig
27 | */
28 | public interface ServerSocketChannel extends ServerChannel {
29 | ServerSocketChannelConfig getConfig();
30 | InetSocketAddress getLocalAddress();
31 | InetSocketAddress getRemoteAddress();
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/ServerSocketChannelConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket;
17 |
18 | import java.net.ServerSocket;
19 | import java.net.StandardSocketOptions;
20 |
21 | import org.jboss.netty.channel.core.ChannelConfig;
22 |
23 | /**
24 | * A {@link ChannelConfig} for a {@link ServerSocketChannel}.
25 | *
26 | * Available options
27 | *
28 | * In addition to the options provided by {@link ChannelConfig},
29 | * {@link ServerSocketChannelConfig} allows the following options in the
30 | * option map:
31 | *
32 | *
33 | *
34 | * Name | Associated setter method |
35 | *
36 | * {@code "backlog"} | {@link #setBacklog(int)} |
37 | *
38 | * {@code "reuseAddress"} | {@link #setReuseAddress(boolean)} |
39 | *
40 | * {@code "receiveBufferSize"} | {@link #setReceiveBufferSize(int)} |
41 | *
42 | *
43 | */
44 | public interface ServerSocketChannelConfig extends ChannelConfig {
45 |
46 | /**
47 | * Gets the backlog value to specify when the channel binds to a local
48 | * address.
49 | */
50 | int getBacklog();
51 |
52 | /**
53 | * Sets the backlog value to specify when the channel binds to a local
54 | * address.
55 | */
56 | void setBacklog(int backlog);
57 |
58 | /**
59 | * Gets the {@link StandardSocketOptions#SO_REUSEADDR} option.
60 | */
61 | boolean isReuseAddress();
62 |
63 | /**
64 | * Sets the {@link StandardSocketOptions#SO_REUSEADDR} option.
65 | */
66 | void setReuseAddress(boolean reuseAddress);
67 |
68 | /**
69 | * Gets the {@link StandardSocketOptions#SO_RCVBUF} option.
70 | */
71 | int getReceiveBufferSize();
72 |
73 | /**
74 | * Sets the {@link StandardSocketOptions#SO_RCVBUF} option.
75 | */
76 | void setReceiveBufferSize(int receiveBufferSize);
77 |
78 | /**
79 | * Sets the performance preferences as specified in
80 | * {@link ServerSocket#setPerformancePreferences(int, int, int)}.
81 | */
82 | void setPerformancePreferences(int connectionTime, int latency, int bandwidth);
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/ServerSocketChannelFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket;
17 |
18 | import org.jboss.netty.channel.core.ChannelFactory;
19 | import org.jboss.netty.channel.core.ChannelPipeline;
20 | import org.jboss.netty.channel.core.ServerChannelFactory;
21 |
22 | /**
23 | * A {@link ChannelFactory} which creates a {@link ServerSocketChannel}.
24 | *
25 | * @apiviz.has org.jboss.netty.channel.socket.ServerSocketChannel oneway - - creates
26 | */
27 | public interface ServerSocketChannelFactory extends ServerChannelFactory {
28 | ServerSocketChannel newChannel(ChannelPipeline pipeline);
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/SocketChannel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket;
17 |
18 | import java.net.InetSocketAddress;
19 |
20 | import org.jboss.netty.channel.core.Channel;
21 |
22 | /**
23 | * A TCP/IP socket {@link Channel} which was either accepted by
24 | * {@link ServerSocketChannel} or created by {@link ClientSocketChannelFactory}.
25 | *
26 | * @apiviz.landmark
27 | * @apiviz.composedOf org.jboss.netty.channel.socket.SocketChannelConfig
28 | */
29 | public interface SocketChannel extends Channel {
30 | SocketChannelConfig getConfig();
31 | InetSocketAddress getLocalAddress();
32 | InetSocketAddress getRemoteAddress();
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/Worker.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.jboss.netty.channel.socket;
18 |
19 | /**
20 | * A {@link Worker} is responsible to dispatch IO operations
21 | *
22 | */
23 | public interface Worker extends Runnable {
24 |
25 | /**
26 | * Execute the given {@link Runnable} in the IO-Thread. This may be now or
27 | * later once the IO-Thread do some other work.
28 | *
29 | * @param task
30 | * the {@link Runnable} to execute
31 | */
32 | void executeInIoThread(Runnable task);
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/AbstractNioChannelSink.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.jboss.netty.channel.socket.nio;
18 |
19 | import org.jboss.netty.channel.core.impl.AbstractChannelSink;
20 | import org.jboss.netty.channel.core.Channel;
21 | import org.jboss.netty.channel.event.ChannelEvent;
22 | import org.jboss.netty.channel.future.ChannelFuture;
23 | import org.jboss.netty.channel.core.ChannelPipeline;
24 | import org.jboss.netty.channel.socket.ChannelRunnableWrapper;
25 |
26 | public abstract class AbstractNioChannelSink extends AbstractChannelSink {
27 |
28 | @Override
29 | public ChannelFuture execute(ChannelPipeline pipeline, final Runnable task) {
30 | Channel ch = pipeline.getChannel();
31 | if (ch instanceof AbstractNioChannel>) {
32 | AbstractNioChannel> channel = (AbstractNioChannel>) ch;
33 | ChannelRunnableWrapper wrapper = new ChannelRunnableWrapper(pipeline.getChannel(), task);
34 | channel.worker.executeInIoThread(wrapper);
35 | return wrapper;
36 | }
37 | return super.execute(pipeline, task);
38 | }
39 |
40 | @Override
41 | protected boolean isFireExceptionCaughtLater(ChannelEvent event, Throwable actualCause) {
42 | Channel channel = event.getChannel();
43 | boolean fireLater = false;
44 | if (channel instanceof AbstractNioChannel>) {
45 | fireLater = !AbstractNioWorker.isIoThread((AbstractNioChannel>) channel);
46 | }
47 | return fireLater;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/Boss.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 | /**
19 | * Serves the boss tasks like connecting/accepting
20 | */
21 | public interface Boss extends NioSelector {
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/BossPool.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 | /**
19 | * A Pool that holds {@link Boss} instances
20 | */
21 | public interface BossPool extends NioSelectorPool {
22 | /**
23 | * Return the next {@link Boss} to use
24 | *
25 | */
26 | E nextBoss();
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/NioChannelConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 | import java.nio.ByteBuffer;
19 | import java.nio.channels.WritableByteChannel;
20 |
21 | import org.jboss.netty.channel.core.Channel;
22 | import org.jboss.netty.channel.core.ChannelConfig;
23 |
24 | /**
25 | * Special {@link ChannelConfig} sub-type which offers extra methods which are useful for NIO.
26 | *
27 | */
28 | public interface NioChannelConfig extends ChannelConfig {
29 |
30 | /**
31 | * Returns the high water mark of the write buffer. If the number of bytes
32 | * queued in the write buffer exceeds this value, {@link Channel#isWritable()}
33 | * will start to return {@code false}.
34 | */
35 | int getWriteBufferHighWaterMark();
36 |
37 | /**
38 | * Sets the high water mark of the write buffer. If the number of bytes
39 | * queued in the write buffer exceeds this value, {@link Channel#isWritable()}
40 | * will start to return {@code false}.
41 | */
42 | void setWriteBufferHighWaterMark(int writeBufferHighWaterMark);
43 |
44 | /**
45 | * Returns the low water mark of the write buffer. Once the number of bytes
46 | * queued in the write buffer exceeded the
47 | * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then
48 | * dropped down below this value, {@link Channel#isWritable()} will start to return
49 | * {@code true} again.
50 | */
51 | int getWriteBufferLowWaterMark();
52 |
53 | /**
54 | * Sets the low water mark of the write buffer. Once the number of bytes
55 | * queued in the write buffer exceeded the
56 | * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then
57 | * dropped down below this value, {@link Channel#isWritable()} will start toreturn
58 | * {@code true} again.
59 | */
60 | void setWriteBufferLowWaterMark(int writeBufferLowWaterMark);
61 |
62 | /**
63 | * Returns the maximum loop count for a write operation until
64 | * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value.
65 | * It is similar to what a spin lock is used for in concurrency programming.
66 | * It improves memory utilization and write throughput depending on
67 | * the platform that JVM runs on. The default value is {@code 16}.
68 | */
69 | int getWriteSpinCount();
70 |
71 | /**
72 | * Sets the maximum loop count for a write operation until
73 | * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value.
74 | * It is similar to what a spin lock is used for in concurrency programming.
75 | * It improves memory utilization and write throughput depending on
76 | * the platform that JVM runs on. The default value is {@code 16}.
77 | *
78 | * @throws IllegalArgumentException
79 | * if the specified value is {@code 0} or less than {@code 0}
80 | */
81 | void setWriteSpinCount(int writeSpinCount);
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/NioSelector.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 | import org.jboss.netty.channel.future.ChannelFuture;
20 |
21 | import java.nio.channels.Selector;
22 |
23 |
24 | public interface NioSelector extends Runnable {
25 |
26 | void register(Channel channel, ChannelFuture future);
27 |
28 | /**
29 | * Replaces the current {@link Selector} with a new {@link Selector} to work around the infamous epoll 100% CPU
30 | * bug.
31 | */
32 | void rebuildSelector();
33 |
34 | void shutdown();
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/NioSelectorPool.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 |
19 | import java.nio.channels.Selector;
20 |
21 | public interface NioSelectorPool {
22 |
23 | /**
24 | * Replaces the current {@link Selector}s of the {@link Boss}es with new {@link Selector}s to work around the
25 | * infamous epoll 100% CPU bug.
26 | */
27 | void rebuildSelectors();
28 |
29 | /**
30 | * Shutdown the {@link NioSelectorPool} and all internal created resources
31 | */
32 | void shutdown();
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/NioSocketChannel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 | import org.jboss.netty.channel.core.Channel;
19 | import org.jboss.netty.channel.core.ChannelFactory;
20 | import org.jboss.netty.channel.future.ChannelFuture;
21 | import org.jboss.netty.channel.core.ChannelPipeline;
22 | import org.jboss.netty.channel.core.ChannelSink;
23 |
24 | import java.net.InetSocketAddress;
25 | import java.net.SocketAddress;
26 | import java.nio.channels.SocketChannel;
27 |
28 | public class NioSocketChannel extends AbstractNioChannel
29 | implements org.jboss.netty.channel.socket.SocketChannel {
30 |
31 | private static final int ST_OPEN = 0;
32 | private static final int ST_BOUND = 1;
33 | private static final int ST_CONNECTED = 2;
34 | private static final int ST_CLOSED = -1;
35 | @SuppressWarnings("RedundantFieldInitialization")
36 | volatile int state = ST_OPEN;
37 |
38 | private final NioSocketChannelConfig config;
39 |
40 | public NioSocketChannel(
41 | Channel parent, ChannelFactory factory,
42 | ChannelPipeline pipeline, ChannelSink sink,
43 | SocketChannel socket, NioWorker worker) {
44 | super(parent, factory, pipeline, sink, worker, socket);
45 | config = new DefaultNioSocketChannelConfig(socket.socket());
46 | }
47 |
48 | @Override
49 | public NioWorker getWorker() {
50 | return (NioWorker) super.getWorker();
51 | }
52 |
53 | @Override
54 | public NioSocketChannelConfig getConfig() {
55 | return config;
56 | }
57 |
58 | @Override
59 | public boolean isOpen() {
60 | return state >= ST_OPEN;
61 | }
62 |
63 | public boolean isBound() {
64 | return state >= ST_BOUND;
65 | }
66 |
67 | public boolean isConnected() {
68 | return state == ST_CONNECTED;
69 | }
70 |
71 | public final void setBound() {
72 | assert state == ST_OPEN : "Invalid state: " + state;
73 | state = ST_BOUND;
74 | }
75 |
76 | public final void setConnected() {
77 | if (state != ST_CLOSED) {
78 | state = ST_CONNECTED;
79 | }
80 | }
81 |
82 | @Override
83 | protected boolean setClosed() {
84 | if (super.setClosed()) {
85 | state = ST_CLOSED;
86 | return true;
87 | }
88 | return false;
89 | }
90 |
91 | @Override
92 | InetSocketAddress getLocalSocketAddress() throws Exception {
93 | return (InetSocketAddress) channel.socket().getLocalSocketAddress();
94 | }
95 |
96 | @Override
97 | InetSocketAddress getRemoteSocketAddress() throws Exception {
98 | return (InetSocketAddress) channel.socket().getRemoteSocketAddress();
99 | }
100 |
101 | @Override
102 | public ChannelFuture write(Object message, SocketAddress remoteAddress) {
103 | if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) {
104 | return super.write(message, null);
105 | } else {
106 | return getUnsupportedOperationFuture();
107 | }
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/NioWorkerPool.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 | import org.jboss.netty.util.ThreadNameDeterminer;
19 |
20 | import java.util.concurrent.Executor;
21 |
22 |
23 | /**
24 | * Default implementation which hands of {@link NioWorker}'s
25 | *
26 | *
27 | */
28 | public class NioWorkerPool extends AbstractNioWorkerPool {
29 |
30 | private final ThreadNameDeterminer determiner;
31 |
32 | public NioWorkerPool(Executor workerExecutor, int workerCount) {
33 | this(workerExecutor, workerCount, null);
34 | }
35 |
36 | public NioWorkerPool(Executor workerExecutor, int workerCount, ThreadNameDeterminer determiner) {
37 | super(workerExecutor, workerCount, false);
38 | this.determiner = determiner;
39 | init();
40 | }
41 |
42 | @Override
43 | @Deprecated
44 | protected NioWorker createWorker(Executor executor) {
45 | return new NioWorker(executor, determiner);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/ProtocolFamilyConverter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 | import org.jboss.netty.channel.socket.InternetProtocolFamily;
19 |
20 | import java.net.ProtocolFamily;
21 | import java.net.StandardProtocolFamily;
22 |
23 |
24 | /**
25 | * Helper class which convert the {@link InternetProtocolFamily}.
26 | *
27 | *
28 | */
29 | final class ProtocolFamilyConverter {
30 |
31 | private ProtocolFamilyConverter() {
32 | // Utility class
33 | }
34 |
35 | /**
36 | * Convert the {@link InternetProtocolFamily}. This MUST only be called on jdk version >= 7.
37 | */
38 | public static ProtocolFamily convert(InternetProtocolFamily family) {
39 | switch (family) {
40 | case IPv4:
41 | return StandardProtocolFamily.INET;
42 |
43 | case IPv6:
44 | return StandardProtocolFamily.INET6;
45 | default:
46 | throw new IllegalArgumentException();
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/SelectorUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 | import org.jboss.netty.logging.InternalLogger;
19 | import org.jboss.netty.logging.InternalLoggerFactory;
20 | import org.jboss.netty.util.internal.SystemPropertyUtil;
21 |
22 | import java.io.IOException;
23 | import java.nio.channels.CancelledKeyException;
24 | import java.nio.channels.Selector;
25 | import java.util.concurrent.TimeUnit;
26 |
27 | public final class SelectorUtil {
28 | private static final InternalLogger logger =
29 | InternalLoggerFactory.getInstance(SelectorUtil.class);
30 |
31 | public static final int DEFAULT_IO_THREADS = Runtime.getRuntime().availableProcessors() * 2;
32 | public static final long DEFAULT_SELECT_TIMEOUT = 500;
33 | public static final long SELECT_TIMEOUT =
34 | SystemPropertyUtil.getLong("org.jboss.netty.selectTimeout", DEFAULT_SELECT_TIMEOUT);
35 | public static final long SELECT_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(SELECT_TIMEOUT);
36 | public static final boolean EPOLL_BUG_WORKAROUND =
37 | SystemPropertyUtil.getBoolean("org.jboss.netty.epollBugWorkaround", false);
38 |
39 | // Workaround for JDK NIO bug.
40 | //
41 | // See:
42 | // - http://bugs.sun.com/view_bug.do?bug_id=6427854
43 | // - https://github.com/netty/netty/issues/203
44 | static {
45 | String key = "sun.nio.ch.bugLevel";
46 | try {
47 | String buglevel = System.getProperty(key);
48 | if (buglevel == null) {
49 | System.setProperty(key, "");
50 | }
51 | } catch (SecurityException e) {
52 | if (logger.isDebugEnabled()) {
53 | logger.debug("Unable to get/set System Property '" + key + '\'', e);
54 | }
55 | }
56 | if (logger.isDebugEnabled()) {
57 | logger.debug("Using select timeout of " + SELECT_TIMEOUT);
58 | logger.debug("Epoll-bug workaround enabled = " + EPOLL_BUG_WORKAROUND);
59 | }
60 | }
61 |
62 | public static Selector open() throws IOException {
63 | return Selector.open();
64 | }
65 |
66 | public static int select(Selector selector) throws IOException {
67 | try {
68 | return selector.select(SELECT_TIMEOUT);
69 | } catch (CancelledKeyException e) {
70 | if (logger.isDebugEnabled()) {
71 | logger.debug(
72 | CancelledKeyException.class.getSimpleName() +
73 | " raised by a Selector - JDK bug?", e);
74 | }
75 | // Harmless exception - log anyway
76 | }
77 | return -1;
78 | }
79 |
80 | private SelectorUtil() {
81 | // Unused
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/ShareableWorkerPool.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 | import org.jboss.netty.channel.socket.Worker;
19 | import org.jboss.netty.util.ExternalResourceReleasable;
20 |
21 | /**
22 | * This implementation of a {@link WorkerPool} should be used if you plan to share a
23 | * {@link WorkerPool} between different Factories. You will need to call {@link #destroy()} by your
24 | * own once you want to release any resources of it.
25 | *
26 | *
27 | */
28 | public final class ShareableWorkerPool implements WorkerPool {
29 |
30 | private final WorkerPool wrapped;
31 |
32 | public ShareableWorkerPool(WorkerPool wrapped) {
33 | this.wrapped = wrapped;
34 | }
35 |
36 | public E nextWorker() {
37 | return wrapped.nextWorker();
38 | }
39 |
40 | public void rebuildSelectors() {
41 | wrapped.rebuildSelectors();
42 | }
43 |
44 | /**
45 | * Destroy the {@link ShareableWorkerPool} and release all resources. After this is called its not usable anymore
46 | */
47 | public void destroy() {
48 | wrapped.shutdown();
49 | if (wrapped instanceof ExternalResourceReleasable) {
50 | ((ExternalResourceReleasable) wrapped).releaseExternalResources();
51 | }
52 | }
53 |
54 | public void shutdown() {
55 | // do nothing
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/SocketReceiveBufferAllocator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio;
17 |
18 | import org.jboss.netty.util.ExternalResourceReleasable;
19 | import org.jboss.netty.util.internal.ByteBufferUtil;
20 |
21 | import java.nio.ByteBuffer;
22 |
23 | final class SocketReceiveBufferAllocator implements ExternalResourceReleasable {
24 |
25 | private ByteBuffer buf;
26 | private int exceedCount;
27 | private final int maxExceedCount;
28 | private final int percentual;
29 |
30 | SocketReceiveBufferAllocator() {
31 | this(16, 80);
32 | }
33 |
34 | SocketReceiveBufferAllocator(int maxExceedCount, int percentual) {
35 | this.maxExceedCount = maxExceedCount;
36 | this.percentual = percentual;
37 | }
38 |
39 | ByteBuffer get(int size) {
40 | if (buf == null) {
41 | return newBuffer(size);
42 | }
43 | if (buf.capacity() < size) {
44 | return newBuffer(size);
45 | }
46 | if (buf.capacity() * percentual / 100 > size) {
47 | if (++exceedCount == maxExceedCount) {
48 | return newBuffer(size);
49 | } else {
50 | buf.clear();
51 | }
52 | } else {
53 | exceedCount = 0;
54 | buf.clear();
55 | }
56 | return buf;
57 | }
58 |
59 | private ByteBuffer newBuffer(int size) {
60 | if (buf != null) {
61 | exceedCount = 0;
62 | ByteBufferUtil.destroy(buf);
63 | }
64 | buf = ByteBuffer.allocateDirect(normalizeCapacity(size));
65 | return buf;
66 | }
67 |
68 | private static int normalizeCapacity(int capacity) {
69 | // Normalize to multiple of 1024
70 | int q = capacity >>> 10;
71 | int r = capacity & 1023;
72 | if (r != 0) {
73 | q ++;
74 | }
75 | return q << 10;
76 | }
77 |
78 | public void releaseExternalResources() {
79 | if (buf != null) {
80 | ByteBufferUtil.destroy(buf);
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/WorkerPool.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.jboss.netty.channel.socket.nio;
18 |
19 | import org.jboss.netty.channel.socket.Worker;
20 |
21 | /**
22 | * The {@link WorkerPool} is responsible to hand of {@link Worker}'s on demand
23 | *
24 | */
25 | public interface WorkerPool extends NioSelectorPool {
26 |
27 | /**
28 | * Return the next {@link Worker} to use
29 | *
30 | * @return worker
31 | */
32 | E nextWorker();
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/client/NioClientBossPool.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio.client;
17 |
18 | import org.jboss.netty.channel.socket.nio.AbstractNioBossPool;
19 | import org.jboss.netty.util.HashedWheelTimer;
20 | import org.jboss.netty.util.ThreadNameDeterminer;
21 | import org.jboss.netty.util.Timer;
22 |
23 | import java.util.concurrent.Executor;
24 |
25 | /**
26 | * Holds {@link NioClientBoss} instances to use
27 | */
28 | public class NioClientBossPool extends AbstractNioBossPool {
29 | private final ThreadNameDeterminer determiner;
30 | private final Timer timer;
31 | private boolean stopTimer;
32 |
33 | /**
34 | * Create a new instance
35 | *
36 | * @param bossExecutor the Executor to use for server the {@link NioClientBoss}
37 | * @param bossCount the number of {@link NioClientBoss} instances this {@link NioClientBossPool} will hold
38 | * @param timer the Timer to use for handle connect timeouts
39 | * @param determiner the {@link ThreadNameDeterminer} to use for name the threads. Use {@code null}
40 | * if you not want to set one explicit.
41 | */
42 | public NioClientBossPool(Executor bossExecutor, int bossCount, Timer timer, ThreadNameDeterminer determiner) {
43 | super(bossExecutor, bossCount, false);
44 | this.determiner = determiner;
45 | this.timer = timer;
46 | init();
47 | }
48 |
49 | /**
50 | * Create a new instance using a new {@link HashedWheelTimer} and no {@link ThreadNameDeterminer}
51 | *
52 | * @param bossExecutor the Executor to use for server the {@link NioClientBoss}
53 | * @param bossCount the number of {@link NioClientBoss} instances this {@link NioClientBoss} will hold
54 | */
55 | public NioClientBossPool(Executor bossExecutor, int bossCount) {
56 | this(bossExecutor, bossCount, new HashedWheelTimer(), null);
57 | stopTimer = true;
58 | }
59 |
60 | @Override
61 | protected NioClientBoss newBoss(Executor executor) {
62 | return new NioClientBoss(executor, timer, determiner);
63 | }
64 |
65 | @Override
66 | public void shutdown() {
67 | super.shutdown();
68 | if (stopTimer) {
69 | timer.stop();
70 | }
71 | }
72 |
73 | @Override
74 | public void releaseExternalResources() {
75 | super.releaseExternalResources();
76 | timer.stop();
77 | }
78 | }
79 |
80 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/client/NioClientSocketChannel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio.client;
17 |
18 | import org.jboss.netty.channel.exception.ChannelException;
19 | import org.jboss.netty.channel.core.ChannelFactory;
20 | import org.jboss.netty.channel.future.ChannelFuture;
21 | import org.jboss.netty.channel.core.ChannelPipeline;
22 | import org.jboss.netty.channel.core.ChannelSink;
23 | import org.jboss.netty.channel.socket.nio.NioSocketChannel;
24 | import org.jboss.netty.channel.socket.nio.NioWorker;
25 | import org.jboss.netty.logging.InternalLogger;
26 | import org.jboss.netty.logging.InternalLoggerFactory;
27 | import org.jboss.netty.util.Timeout;
28 |
29 | import java.io.IOException;
30 | import java.net.SocketAddress;
31 | import java.nio.channels.SocketChannel;
32 |
33 | import static org.jboss.netty.channel.core.Channels.*;
34 |
35 | public final class NioClientSocketChannel extends NioSocketChannel {
36 |
37 | private static final InternalLogger logger =
38 | InternalLoggerFactory.getInstance(NioClientSocketChannel.class);
39 |
40 | private static SocketChannel newSocket() {
41 | SocketChannel socket;
42 | try {
43 | socket = SocketChannel.open();
44 | } catch (IOException e) {
45 | throw new ChannelException("Failed to open a socket.", e);
46 | }
47 |
48 | boolean success = false;
49 | try {
50 | socket.configureBlocking(false);
51 | success = true;
52 | } catch (IOException e) {
53 | throw new ChannelException("Failed to enter non-blocking mode.", e);
54 | } finally {
55 | if (!success) {
56 | try {
57 | socket.close();
58 | } catch (IOException e) {
59 | if (logger.isWarnEnabled()) {
60 | logger.warn(
61 | "Failed to close a partially initialized socket.",
62 | e);
63 | }
64 | }
65 | }
66 | }
67 |
68 | return socket;
69 | }
70 |
71 | public volatile ChannelFuture connectFuture;
72 | public volatile boolean boundManually;
73 |
74 | // Does not need to be volatile as it's accessed by only one thread.
75 | public long connectDeadlineNanos;
76 | public volatile SocketAddress requestedRemoteAddress;
77 |
78 | public volatile Timeout timoutTimer;
79 |
80 | NioClientSocketChannel(
81 | ChannelFactory factory, ChannelPipeline pipeline,
82 | ChannelSink sink, NioWorker worker) {
83 |
84 | super(null, factory, pipeline, sink, newSocket(), worker);
85 | fireChannelOpen(this);
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/server/NioAcceptedSocketChannel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio.server;
17 |
18 | import static org.jboss.netty.channel.core.Channels.*;
19 |
20 | import java.nio.channels.SocketChannel;
21 |
22 | import org.jboss.netty.channel.core.Channel;
23 | import org.jboss.netty.channel.core.ChannelFactory;
24 | import org.jboss.netty.channel.core.ChannelPipeline;
25 | import org.jboss.netty.channel.core.ChannelSink;
26 | import org.jboss.netty.channel.socket.nio.NioSocketChannel;
27 | import org.jboss.netty.channel.socket.nio.NioWorker;
28 |
29 | public final class NioAcceptedSocketChannel extends NioSocketChannel {
30 |
31 | final Thread bossThread;
32 |
33 | NioAcceptedSocketChannel(
34 | ChannelFactory factory, ChannelPipeline pipeline,
35 | Channel parent, ChannelSink sink,
36 | SocketChannel socket, NioWorker worker, Thread bossThread) {
37 |
38 | super(parent, factory, pipeline, sink, socket, worker);
39 |
40 | this.bossThread = bossThread;
41 |
42 | setConnected();
43 |
44 | fireChannelOpen(this);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/server/NioServerBossPool.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio.server;
17 |
18 | import org.jboss.netty.channel.socket.nio.AbstractNioBossPool;
19 | import org.jboss.netty.util.ThreadNameDeterminer;
20 |
21 | import java.util.concurrent.Executor;
22 |
23 |
24 | /**
25 | * Holds {@link NioServerBoss} instances to use
26 | */
27 | public class NioServerBossPool extends AbstractNioBossPool {
28 | private final ThreadNameDeterminer determiner;
29 |
30 | /**
31 | * Create a new instance
32 | *
33 | * @param bossExecutor the {@link Executor} to use for server the {@link NioServerBoss}
34 | * @param bossCount the number of {@link NioServerBoss} instances this {@link NioServerBossPool} will hold
35 | * @param determiner the {@link ThreadNameDeterminer} to use for name the threads. Use {@code null}
36 | * if you not want to set one explicit.
37 | */
38 | public NioServerBossPool(Executor bossExecutor, int bossCount, ThreadNameDeterminer determiner) {
39 | super(bossExecutor, bossCount, false);
40 | this.determiner = determiner;
41 | init();
42 | }
43 |
44 | /**
45 | * Create a new instance using no {@link ThreadNameDeterminer}
46 | *
47 | * @param bossExecutor the {@link Executor} to use for server the {@link NioServerBoss}
48 | * @param bossCount the number of {@link NioServerBoss} instances this {@link NioServerBossPool} will hold
49 | */
50 | public NioServerBossPool(Executor bossExecutor, int bossCount) {
51 | this(bossExecutor, bossCount, null);
52 | }
53 |
54 | @Override
55 | protected NioServerBoss newBoss(Executor executor) {
56 | return new NioServerBoss(executor, determiner);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/channel/socket/nio/server/NioServerSocketChannel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.channel.socket.nio.server;
17 |
18 | import static org.jboss.netty.channel.core.Channels.*;
19 |
20 | import java.io.IOException;
21 | import java.net.InetSocketAddress;
22 | import java.nio.channels.ServerSocketChannel;
23 |
24 | import org.jboss.netty.channel.core.impl.AbstractServerChannel;
25 | import org.jboss.netty.channel.exception.ChannelException;
26 | import org.jboss.netty.channel.core.ChannelFactory;
27 | import org.jboss.netty.channel.core.ChannelPipeline;
28 | import org.jboss.netty.channel.core.ChannelSink;
29 | import org.jboss.netty.channel.socket.DefaultServerSocketChannelConfig;
30 | import org.jboss.netty.channel.socket.ServerSocketChannelConfig;
31 | import org.jboss.netty.channel.socket.nio.Boss;
32 | import org.jboss.netty.channel.socket.nio.NioWorker;
33 | import org.jboss.netty.channel.socket.nio.WorkerPool;
34 | import org.jboss.netty.logging.InternalLogger;
35 | import org.jboss.netty.logging.InternalLoggerFactory;
36 |
37 | class NioServerSocketChannel extends AbstractServerChannel
38 | implements org.jboss.netty.channel.socket.ServerSocketChannel {
39 |
40 | private static final InternalLogger logger =
41 | InternalLoggerFactory.getInstance(NioServerSocketChannel.class);
42 |
43 | final ServerSocketChannel socket;
44 | final Boss boss;
45 | final WorkerPool workerPool;
46 |
47 | private final ServerSocketChannelConfig config;
48 |
49 | NioServerSocketChannel(
50 | ChannelFactory factory,
51 | ChannelPipeline pipeline,
52 | ChannelSink sink, Boss boss, WorkerPool workerPool) {
53 |
54 | super(factory, pipeline, sink);
55 | this.boss = boss;
56 | this.workerPool = workerPool;
57 | try {
58 | socket = ServerSocketChannel.open();
59 | } catch (IOException e) {
60 | throw new ChannelException(
61 | "Failed to open a server socket.", e);
62 | }
63 |
64 | try {
65 | socket.configureBlocking(false);
66 | } catch (IOException e) {
67 | try {
68 | socket.close();
69 | } catch (IOException e2) {
70 | if (logger.isWarnEnabled()) {
71 | logger.warn(
72 | "Failed to close a partially initialized socket.", e2);
73 | }
74 | }
75 |
76 | throw new ChannelException("Failed to enter non-blocking mode.", e);
77 | }
78 |
79 | config = new DefaultServerSocketChannelConfig(socket.socket());
80 |
81 | fireChannelOpen(this);
82 | }
83 |
84 | public ServerSocketChannelConfig getConfig() {
85 | return config;
86 | }
87 |
88 | public InetSocketAddress getLocalAddress() {
89 | return (InetSocketAddress) socket.socket().getLocalSocketAddress();
90 | }
91 |
92 | public InetSocketAddress getRemoteAddress() {
93 | return null;
94 | }
95 |
96 | public boolean isBound() {
97 | return isOpen() && socket.socket().isBound();
98 | }
99 |
100 | @Override
101 | protected boolean setClosed() {
102 | return super.setClosed();
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/logging/AbstractInternalLogger.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.logging;
17 |
18 | /**
19 | * A skeletal implementation of {@link InternalLogger}. This class implements
20 | * all methods that have a {@link InternalLogLevel} parameter by default to call
21 | * specific logger methods such as {@link #info(String)} or {@link #isInfoEnabled()}.
22 | */
23 | public abstract class AbstractInternalLogger implements InternalLogger {
24 |
25 | /**
26 | * Creates a new instance.
27 | */
28 | protected AbstractInternalLogger() {
29 | }
30 |
31 | public boolean isEnabled(InternalLogLevel level) {
32 | switch (level) {
33 | case DEBUG:
34 | return isDebugEnabled();
35 | case INFO:
36 | return isInfoEnabled();
37 | case WARN:
38 | return isWarnEnabled();
39 | case ERROR:
40 | return isErrorEnabled();
41 | default:
42 | throw new Error();
43 | }
44 | }
45 |
46 | public void log(InternalLogLevel level, String msg, Throwable cause) {
47 | switch (level) {
48 | case DEBUG:
49 | debug(msg, cause);
50 | break;
51 | case INFO:
52 | info(msg, cause);
53 | break;
54 | case WARN:
55 | warn(msg, cause);
56 | break;
57 | case ERROR:
58 | error(msg, cause);
59 | break;
60 | default:
61 | throw new Error();
62 | }
63 | }
64 |
65 | public void log(InternalLogLevel level, String msg) {
66 | switch (level) {
67 | case DEBUG:
68 | debug(msg);
69 | break;
70 | case INFO:
71 | info(msg);
72 | break;
73 | case WARN:
74 | warn(msg);
75 | break;
76 | case ERROR:
77 | error(msg);
78 | break;
79 | default:
80 | throw new Error();
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/logging/InternalLogLevel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.logging;
17 |
18 | /**
19 | * The log level that {@link InternalLogger} can log at.
20 | */
21 | public enum InternalLogLevel {
22 | /**
23 | * 'DEBUG' log level.
24 | */
25 | DEBUG,
26 | /**
27 | * 'INFO' log level.
28 | */
29 | INFO,
30 | /**
31 | * 'WARN' log level.
32 | */
33 | WARN,
34 | /**
35 | * 'ERROR' log level.
36 | */
37 | ERROR
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/logging/InternalLogger.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.logging;
17 |
18 | /**
19 | * Internal-use-only logger used by Netty. DO NOT
20 | * access this class outside of Netty.
21 | */
22 | public interface InternalLogger {
23 | /**
24 | * Returns {@code true} if a DEBUG level message is logged.
25 | */
26 | boolean isDebugEnabled();
27 |
28 | /**
29 | * Returns {@code true} if an INFO level message is logged.
30 | */
31 | boolean isInfoEnabled();
32 |
33 | /**
34 | * Returns {@code true} if a WARN level message is logged.
35 | */
36 | boolean isWarnEnabled();
37 |
38 | /**
39 | * Returns {@code true} if an ERROR level message is logged.
40 | */
41 | boolean isErrorEnabled();
42 |
43 | /**
44 | * Returns {@code true} if the specified log level message is logged.
45 | */
46 | boolean isEnabled(InternalLogLevel level);
47 |
48 | /**
49 | * Logs a DEBUG level message.
50 | */
51 | void debug(String msg);
52 |
53 | /**
54 | * Logs a DEBUG level message.
55 | */
56 | void debug(String msg, Throwable cause);
57 |
58 | /**
59 | * Logs an INFO level message.
60 | */
61 | void info(String msg);
62 |
63 | /**
64 | * Logs an INFO level message.
65 | */
66 | void info(String msg, Throwable cause);
67 |
68 | /**
69 | * Logs a WARN level message.
70 | */
71 | void warn(String msg);
72 |
73 | /**
74 | * Logs a WARN level message.
75 | */
76 | void warn(String msg, Throwable cause);
77 |
78 | /**
79 | * Logs an ERROR level message.
80 | */
81 | void error(String msg);
82 |
83 | /**
84 | * Logs an ERROR level message.
85 | */
86 | void error(String msg, Throwable cause);
87 |
88 | /**
89 | * Logs a message.
90 | */
91 | void log(InternalLogLevel level, String msg);
92 |
93 | /**
94 | * Logs a message.
95 | */
96 | void log(InternalLogLevel level, String msg, Throwable cause);
97 | }
98 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/logging/InternalLoggerFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.logging;
17 |
18 | /**
19 | * Creates an {@link InternalLogger} or changes the default factory
20 | * implementation. This factory allows you to choose what logging framework
21 | * Netty should use. The default factory is {@link JdkLoggerFactory}.
22 | * You can change it to your preferred logging framework before other Netty
23 | * classes are loaded:
24 | *
25 | * {@link InternalLoggerFactory}.setDefaultFactory(new {@link Log4JLoggerFactory}());
26 | *
27 | * Please note that the new default factory is effective only for the classes
28 | * which were loaded after the default factory is changed. Therefore,
29 | * {@link #setDefaultFactory(InternalLoggerFactory)} should be called as early
30 | * as possible and shouldn't be called more than once.
31 | *
32 | * @apiviz.landmark
33 | * @apiviz.has org.jboss.netty.logging.InternalLogger oneway - - creates
34 | */
35 | public abstract class InternalLoggerFactory {
36 | private static volatile InternalLoggerFactory defaultFactory = new JdkLoggerFactory();
37 |
38 | /**
39 | * Returns the default factory. The initial default factory is
40 | * {@link JdkLoggerFactory}.
41 | */
42 | public static InternalLoggerFactory getDefaultFactory() {
43 | return defaultFactory;
44 | }
45 |
46 | /**
47 | * Changes the default factory.
48 | */
49 | public static void setDefaultFactory(InternalLoggerFactory defaultFactory) {
50 | if (defaultFactory == null) {
51 | throw new NullPointerException("defaultFactory");
52 | }
53 | InternalLoggerFactory.defaultFactory = defaultFactory;
54 | }
55 |
56 | /**
57 | * Creates a new logger instance with the name of the specified class.
58 | */
59 | public static InternalLogger getInstance(Class> clazz) {
60 | return getInstance(clazz.getName());
61 | }
62 |
63 | /**
64 | * Creates a new logger instance with the specified name.
65 | */
66 | public static InternalLogger getInstance(String name) {
67 | return getDefaultFactory().newInstance(name);
68 | }
69 |
70 | /**
71 | * Creates a new logger instance with the specified name.
72 | */
73 | public abstract InternalLogger newInstance(String name);
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/logging/JdkLogger.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.logging;
17 |
18 | import java.util.logging.Level;
19 | import java.util.logging.Logger;
20 |
21 | /**
22 | * java.util.logging
23 | * logger.
24 | */
25 | class JdkLogger extends AbstractInternalLogger {
26 |
27 | private final Logger logger;
28 | private final String loggerName;
29 |
30 | JdkLogger(Logger logger, String loggerName) {
31 | this.logger = logger;
32 | this.loggerName = loggerName;
33 | }
34 |
35 | public void debug(String msg) {
36 | logger.logp(Level.FINE, loggerName, null, msg);
37 | }
38 |
39 | public void debug(String msg, Throwable cause) {
40 | logger.logp(Level.FINE, loggerName, null, msg, cause);
41 | }
42 |
43 | public void error(String msg) {
44 | logger.logp(Level.SEVERE, loggerName, null, msg);
45 | }
46 |
47 | public void error(String msg, Throwable cause) {
48 | logger.logp(Level.SEVERE, loggerName, null, msg, cause);
49 | }
50 |
51 | public void info(String msg) {
52 | logger.logp(Level.INFO, loggerName, null, msg);
53 | }
54 |
55 | public void info(String msg, Throwable cause) {
56 | logger.logp(Level.INFO, loggerName, null, msg, cause);
57 | }
58 |
59 | public boolean isDebugEnabled() {
60 | return logger.isLoggable(Level.FINE);
61 | }
62 |
63 | public boolean isErrorEnabled() {
64 | return logger.isLoggable(Level.SEVERE);
65 | }
66 |
67 | public boolean isInfoEnabled() {
68 | return logger.isLoggable(Level.INFO);
69 | }
70 |
71 | public boolean isWarnEnabled() {
72 | return logger.isLoggable(Level.WARNING);
73 | }
74 |
75 | public void warn(String msg) {
76 | logger.logp(Level.WARNING, loggerName, null, msg);
77 | }
78 |
79 | public void warn(String msg, Throwable cause) {
80 | logger.logp(Level.WARNING, loggerName, null, msg, cause);
81 | }
82 |
83 | @Override
84 | public String toString() {
85 | return loggerName;
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/logging/JdkLoggerFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.logging;
17 |
18 |
19 | import java.util.logging.Logger;
20 |
21 | /**
22 | * Logger factory which creates a
23 | * java.util.logging
24 | * logger.
25 | */
26 | public class JdkLoggerFactory extends InternalLoggerFactory {
27 |
28 | @Override
29 | public InternalLogger newInstance(String name) {
30 | final Logger logger =
31 | Logger.getLogger(name);
32 | return new JdkLogger(logger, name);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/DebugUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util;
17 |
18 | import org.jboss.netty.channel.core.ChannelPipeline;
19 | import org.jboss.netty.channel.core.ChannelSink;
20 | import org.jboss.netty.util.internal.SystemPropertyUtil;
21 |
22 | /**
23 | * Determines if Netty is running in a debug mode or not. Please note that
24 | * this is not a Java debug mode. You can enable Netty debug mode by
25 | * specifying the {@code "org.jboss.netty.debug"} system property (e.g.
26 | * {@code java -Dorg.jboss.netty.debug ...})
27 | *
28 | * If debug mode is disabled (default), the stack trace of the exceptions are
29 | * compressed to help debugging a user application.
30 | *
31 | * If debug mode is enabled, the stack trace of the exceptions raised in
32 | * {@link ChannelPipeline} or {@link ChannelSink} are retained as it is to help
33 | * debugging Netty.
34 | */
35 | public final class DebugUtil {
36 |
37 | private static final boolean DEBUG_ENABLED =
38 | SystemPropertyUtil.getBoolean("org.jboss.netty.debug", false);
39 |
40 | /**
41 | * Returns {@code true} if and only if Netty debug mode is enabled.
42 | */
43 | public static boolean isDebugEnabled() {
44 | return DEBUG_ENABLED;
45 | }
46 |
47 | private DebugUtil() {
48 | // Unused
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/EstimatableObjectWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util;
17 |
18 | /**
19 | * Represents an object which contains another object that needs to be taken
20 | * into account by {@link ObjectSizeEstimator} for more accurate object size
21 | * estimation.
22 | */
23 | public interface EstimatableObjectWrapper {
24 |
25 | /**
26 | * Returns the underlying object that needs to be taken into account
27 | * by {@link ObjectSizeEstimator} for more accurate object size estimation.
28 | */
29 | Object unwrap();
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/ExternalResourceReleasable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util;
17 |
18 | /**
19 | * A common interface for a class which depends on external resources that
20 | * need explicit release or shutdown.
21 | * @apiviz.landmark
22 | */
23 | public interface ExternalResourceReleasable {
24 |
25 | /**
26 | * Releases the external resources that this object depends on. You should
27 | * not call this method if the external resources (e.g. thread pool) are
28 | * in use by other objects.
29 | */
30 | void releaseExternalResources();
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/ExternalResourceUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util;
17 |
18 | /**
19 | * A utility class that provides the convenient shutdown of
20 | * {@link ExternalResourceReleasable}s.
21 | */
22 | public final class ExternalResourceUtil {
23 |
24 | /**
25 | * Releases the specified {@link ExternalResourceReleasable}s.
26 | */
27 | public static void release(ExternalResourceReleasable... releasables) {
28 | ExternalResourceReleasable[] releasablesCopy =
29 | new ExternalResourceReleasable[releasables.length];
30 |
31 | for (int i = 0; i < releasables.length; i ++) {
32 | if (releasables[i] == null) {
33 | throw new NullPointerException("releasables[" + i + ']');
34 | }
35 | releasablesCopy[i] = releasables[i];
36 | }
37 |
38 | for (ExternalResourceReleasable e: releasablesCopy) {
39 | e.releaseExternalResources();
40 | }
41 | }
42 |
43 | private ExternalResourceUtil() {
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/MapBackedSet.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util;
17 |
18 | import java.io.Serializable;
19 | import java.util.AbstractSet;
20 | import java.util.Iterator;
21 | import java.util.Map;
22 | import java.util.Set;
23 |
24 | /**
25 | * A {@link Map}-backed {@link Set}.
26 | */
27 | final class MapBackedSet extends AbstractSet implements Serializable {
28 |
29 | private static final long serialVersionUID = -6761513279741915432L;
30 |
31 | private final Map map;
32 |
33 | /**
34 | * Creates a new instance which wraps the specified {@code map}.
35 | */
36 | MapBackedSet(Map map) {
37 | this.map = map;
38 | }
39 |
40 | @Override
41 | public int size() {
42 | return map.size();
43 | }
44 |
45 | @Override
46 | public boolean contains(Object o) {
47 | return map.containsKey(o);
48 | }
49 |
50 | @Override
51 | public boolean add(E o) {
52 | return map.put(o, Boolean.TRUE) == null;
53 | }
54 |
55 | @Override
56 | public boolean remove(Object o) {
57 | return map.remove(o) != null;
58 | }
59 |
60 | @Override
61 | public void clear() {
62 | map.clear();
63 | }
64 |
65 | @Override
66 | public Iterator iterator() {
67 | return map.keySet().iterator();
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/ObjectSizeEstimator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util;
17 |
18 |
19 | /**
20 | * Estimates the size of an object in bytes.
21 | *
22 | * @apiviz.landmark
23 | * @apiviz.uses org.jboss.netty.util.EstimatableObjectWrapper
24 | */
25 | public interface ObjectSizeEstimator {
26 |
27 | /**
28 | * Returns the estimated size of the specified object in bytes.
29 | *
30 | * @return a positive integer which represents the size of the specified
31 | * object in bytes
32 | */
33 | int estimateSize(Object o);
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/ThreadNameDeterminer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util;
17 |
18 | /**
19 | * Overrides the thread name proposed by {@link ThreadRenamingRunnable}.
20 | */
21 | public interface ThreadNameDeterminer {
22 |
23 | /**
24 | * {@link ThreadNameDeterminer} that accepts the proposed thread name
25 | * as is.
26 | */
27 | ThreadNameDeterminer PROPOSED = new ThreadNameDeterminer() {
28 | public String determineThreadName(String currentThreadName,
29 | String proposedThreadName) throws Exception {
30 | return proposedThreadName;
31 | }
32 | };
33 |
34 | /**
35 | * {@link ThreadNameDeterminer} that rejects the proposed thread name and
36 | * retains the current one.
37 | */
38 | ThreadNameDeterminer CURRENT = new ThreadNameDeterminer() {
39 | public String determineThreadName(String currentThreadName,
40 | String proposedThreadName) throws Exception {
41 | return null;
42 | }
43 | };
44 |
45 | /**
46 | * Overrides the thread name proposed by {@link ThreadRenamingRunnable}.
47 | *
48 | * @param currentThreadName the current thread name
49 | * @param proposedThreadName the proposed new thread name
50 | * @return the actual new thread name.
51 | * If {@code null} is returned, the proposed thread name is
52 | * discarded (i.e. no rename).
53 | */
54 | String determineThreadName(String currentThreadName, String proposedThreadName) throws Exception;
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/Timeout.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util;
17 |
18 | /**
19 | * A handle associated with a {@link TimerTask} that is returned by a
20 | * {@link Timer}.
21 | */
22 | public interface Timeout {
23 |
24 | /**
25 | * Returns the {@link Timer} that created this handle.
26 | */
27 | Timer getTimer();
28 |
29 | /**
30 | * Returns the {@link TimerTask} which is associated with this handle.
31 | */
32 | TimerTask getTask();
33 |
34 | /**
35 | * Returns {@code true} if and only if the {@link TimerTask} associated
36 | * with this handle has been expired.
37 | */
38 | boolean isExpired();
39 |
40 | /**
41 | * Returns {@code true} if and only if the {@link TimerTask} associated
42 | * with this handle has been cancelled.
43 | */
44 | boolean isCancelled();
45 |
46 | /**
47 | * Cancels the {@link TimerTask} associated with this handle. It the
48 | * task has been executed or cancelled already, it will return with no
49 | * side effect.
50 | */
51 | void cancel();
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/Timer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util;
17 |
18 | import java.util.Set;
19 | import java.util.concurrent.TimeUnit;
20 |
21 | /**
22 | * Schedules {@link TimerTask}s for one-time future execution in a background
23 | * thread.
24 | * @apiviz.landmark
25 | * @apiviz.has org.jboss.netty.util.TimerTask oneway - - executes
26 | * @apiviz.has org.jboss.netty.util.Timeout oneway - - creates
27 | */
28 | public interface Timer {
29 |
30 | /**
31 | * Schedules the specified {@link TimerTask} for one-time execution after
32 | * the specified delay.
33 | *
34 | * @return a handle which is associated with the specified task
35 | *
36 | * @throws IllegalStateException if this timer has been
37 | * {@linkplain #stop() stopped} already
38 | */
39 | Timeout newTimeout(TimerTask task, long delay, TimeUnit unit);
40 |
41 | /**
42 | * Releases all resources acquired by this {@link Timer} and cancels all
43 | * tasks which were scheduled but not executed yet.
44 | *
45 | * @return the handles associated with the tasks which were canceled by
46 | * this method
47 | */
48 | Set stop();
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/TimerTask.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util;
17 |
18 | import java.util.concurrent.TimeUnit;
19 |
20 | /**
21 | * A task which is executed after the delay specified with
22 | * {@link Timer#newTimeout(TimerTask, long, TimeUnit)}.
23 | */
24 | public interface TimerTask {
25 |
26 | /**
27 | * Executed after the delay specified with
28 | * {@link Timer#newTimeout(TimerTask, long, TimeUnit)}.
29 | *
30 | * @param timeout a handle which is associated with this task
31 | */
32 | void run(Timeout timeout) throws Exception;
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/Version.java:
--------------------------------------------------------------------------------
1 | // DO NOT MODIFY - WILL BE OVERWRITTEN DURING THE BUILD PROCESS
2 | package org.jboss.netty.util;
3 | /**
4 | * Provides the version information of Netty.
5 | * @apiviz.landmark
6 | */
7 | @SuppressWarnings("all")
8 | public final class Version {
9 | /** The version identifier. */
10 | public static final String ID = "3.9.4.Final-unknown";
11 | /** Prints out the version identifier to stdout. */
12 | public static void main(String[] args) { System.out.println(ID); }
13 | private Version() { }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/AtomicFieldUpdaterUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util.internal;
17 |
18 | import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
19 | import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
20 |
21 | final class AtomicFieldUpdaterUtil {
22 |
23 | private static final boolean AVAILABLE;
24 |
25 | static final class Node {
26 | volatile Node next;
27 | }
28 |
29 | static {
30 | boolean available = false;
31 | try {
32 | AtomicReferenceFieldUpdater tmp =
33 | AtomicReferenceFieldUpdater.newUpdater(
34 | Node.class, Node.class, "next");
35 |
36 | // Test if AtomicReferenceFieldUpdater is really working.
37 | Node testNode = new Node();
38 | tmp.set(testNode, testNode);
39 | if (testNode.next != testNode) {
40 | // Not set as expected - fall back to the safe mode.
41 | throw new Exception();
42 | }
43 | available = true;
44 | } catch (Throwable t) {
45 | // Running in a restricted environment with a security manager.
46 | }
47 | AVAILABLE = available;
48 | }
49 |
50 | static AtomicReferenceFieldUpdater newRefUpdater(Class tclass, Class vclass, String fieldName) {
51 | if (AVAILABLE) {
52 | return AtomicReferenceFieldUpdater.newUpdater(tclass, vclass, fieldName);
53 | } else {
54 | return null;
55 | }
56 | }
57 |
58 | static AtomicIntegerFieldUpdater newIntUpdater(Class tclass, String fieldName) {
59 | if (AVAILABLE) {
60 | return AtomicIntegerFieldUpdater.newUpdater(tclass, fieldName);
61 | } else {
62 | return null;
63 | }
64 | }
65 |
66 | static boolean isAvailable() {
67 | return AVAILABLE;
68 | }
69 |
70 | private AtomicFieldUpdaterUtil() {
71 | // Unused
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/ByteBufferUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util.internal;
17 |
18 | import java.lang.reflect.Method;
19 | import java.nio.ByteBuffer;
20 |
21 | /**
22 | * This is fork of ElasticSearch's ByteBufferAllocator.Cleaner class
23 | */
24 | public final class ByteBufferUtil {
25 | private static final boolean CLEAN_SUPPORTED;
26 | private static final Method directBufferCleaner;
27 | private static final Method directBufferCleanerClean;
28 |
29 | static {
30 | Method directBufferCleanerX = null;
31 | Method directBufferCleanerCleanX = null;
32 | boolean v;
33 | try {
34 | directBufferCleanerX = Class.forName("java.nio.DirectByteBuffer").getMethod("cleaner");
35 | directBufferCleanerX.setAccessible(true);
36 | directBufferCleanerCleanX = Class.forName("sun.misc.Cleaner").getMethod("clean");
37 | directBufferCleanerCleanX.setAccessible(true);
38 | v = true;
39 | } catch (Exception e) {
40 | v = false;
41 | }
42 | CLEAN_SUPPORTED = v;
43 | directBufferCleaner = directBufferCleanerX;
44 | directBufferCleanerClean = directBufferCleanerCleanX;
45 | }
46 |
47 | /**
48 | * Destroy the given {@link ByteBuffer} if possible
49 | */
50 | public static void destroy(ByteBuffer buffer) {
51 | if (CLEAN_SUPPORTED && buffer.isDirect()) {
52 | try {
53 | Object cleaner = directBufferCleaner.invoke(buffer);
54 | directBufferCleanerClean.invoke(cleaner);
55 | } catch (Exception e) {
56 | // silently ignore exception
57 | }
58 | }
59 | }
60 |
61 | private ByteBufferUtil() {
62 | // Utility class
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/CaseIgnoringComparator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util.internal;
17 |
18 | import java.io.Serializable;
19 | import java.util.Comparator;
20 |
21 | public final class CaseIgnoringComparator implements Comparator, Serializable {
22 |
23 | private static final long serialVersionUID = 4582133183775373862L;
24 |
25 | public static final CaseIgnoringComparator INSTANCE = new CaseIgnoringComparator();
26 |
27 | private CaseIgnoringComparator() {
28 | }
29 |
30 | public int compare(String o1, String o2) {
31 | return o1.compareToIgnoreCase(o2);
32 | }
33 |
34 | @SuppressWarnings("MethodMayBeStatic")
35 | private Object readResolve() {
36 | return INSTANCE;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/ConversionUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util.internal;
17 |
18 | import java.util.ArrayList;
19 | import java.util.List;
20 | import java.util.regex.Pattern;
21 |
22 | /**
23 | * Conversion utility class to parse a property represented as a string or
24 | * an object.
25 | */
26 | public final class ConversionUtil {
27 |
28 | /**
29 | * Converts the specified object into an integer.
30 | */
31 | public static int toInt(Object value) {
32 | if (value instanceof Number) {
33 | return ((Number) value).intValue();
34 | } else {
35 | return Integer.parseInt(String.valueOf(value));
36 | }
37 | }
38 |
39 | /**
40 | * Converts the specified object into a boolean.
41 | */
42 | public static boolean toBoolean(Object value) {
43 | if (value instanceof Boolean) {
44 | return ((Boolean) value).booleanValue();
45 | }
46 | if (value instanceof Number) {
47 | return ((Number) value).intValue() != 0;
48 | } else {
49 | String s = String.valueOf(value);
50 | if (s.length() == 0) {
51 | return false;
52 | }
53 |
54 | try {
55 | return Integer.parseInt(s) != 0;
56 | } catch (NumberFormatException e) {
57 | // Proceed
58 | }
59 |
60 | switch (Character.toUpperCase(s.charAt(0))) {
61 | case 'T': case 'Y':
62 | return true;
63 | }
64 | return false;
65 | }
66 | }
67 |
68 | private static final Pattern ARRAY_DELIM = Pattern.compile("[, \\t\\n\\r\\f\\e\\a]");
69 |
70 | /**
71 | * Converts the specified object into an array of strings.
72 | */
73 | public static String[] toStringArray(Object value) {
74 | if (value instanceof String[]) {
75 | return (String[]) value;
76 | }
77 |
78 | if (value instanceof Iterable>) {
79 | List answer = new ArrayList();
80 | for (Object v: (Iterable>) value) {
81 | if (v == null) {
82 | answer.add(null);
83 | } else {
84 | answer.add(String.valueOf(v));
85 | }
86 | }
87 | return answer.toArray(new String[answer.size()]);
88 | }
89 |
90 | return ARRAY_DELIM.split(String.valueOf(value));
91 | }
92 |
93 | private static final String[] INTEGERS = {
94 | "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
95 | "10", "11", "12", "13", "14", "15",
96 | };
97 |
98 | public static String toString(int value) {
99 | if (value >= 0 && value < INTEGERS.length) {
100 | return INTEGERS[value];
101 | } else {
102 | return Integer.toString(value);
103 | }
104 | }
105 |
106 | private ConversionUtil() {
107 | // Unused
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/DeadLockProofWorker.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util.internal;
17 |
18 | import java.util.concurrent.Executor;
19 |
20 | /**
21 | */
22 | public final class DeadLockProofWorker {
23 |
24 | /**
25 | * An internal use only thread-local variable that tells the
26 | * {@link Executor} that this worker acquired a worker thread from.
27 | */
28 | public static final ThreadLocal PARENT = new ThreadLocal();
29 |
30 | public static void start(final Executor parent, final Runnable runnable) {
31 | if (parent == null) {
32 | throw new NullPointerException("parent");
33 | }
34 | if (runnable == null) {
35 | throw new NullPointerException("runnable");
36 | }
37 |
38 | parent.execute(new Runnable() {
39 | public void run() {
40 | PARENT.set(parent);
41 | try {
42 | runnable.run();
43 | } finally {
44 | PARENT.remove();
45 | }
46 | }
47 | });
48 | }
49 |
50 | private DeadLockProofWorker() {
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/EmptyArrays.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 |
17 | package org.jboss.netty.util.internal;
18 |
19 | import java.nio.ByteBuffer;
20 | import java.security.cert.X509Certificate;
21 |
22 | public final class EmptyArrays {
23 |
24 | public static final byte[] EMPTY_BYTES = new byte[0];
25 | public static final boolean[] EMPTY_BOOLEANS = new boolean[0];
26 | public static final double[] EMPTY_DOUBLES = new double[0];
27 | public static final float[] EMPTY_FLOATS = new float[0];
28 | public static final int[] EMPTY_INTS = new int[0];
29 | public static final short[] EMPTY_SHORTS = new short[0];
30 | public static final long[] EMPTY_LONGS = new long[0];
31 | public static final Object[] EMPTY_OBJECTS = new Object[0];
32 | public static final String[] EMPTY_STRINGS = new String[0];
33 | public static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0];
34 | public static final ByteBuffer[] EMPTY_BYTE_BUFFERS = new ByteBuffer[0];
35 | public static final X509Certificate[] EMPTY_X509_CERTIFICATES = new X509Certificate[0];
36 |
37 | private EmptyArrays() { }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/NonReentrantLock.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util.internal;
17 |
18 | import java.util.concurrent.TimeUnit;
19 | import java.util.concurrent.locks.AbstractQueuedSynchronizer;
20 | import java.util.concurrent.locks.Condition;
21 | import java.util.concurrent.locks.Lock;
22 |
23 | public final class NonReentrantLock extends AbstractQueuedSynchronizer
24 | implements Lock {
25 |
26 | private static final long serialVersionUID = -833780837233068610L;
27 |
28 | private Thread owner;
29 |
30 | public void lock() {
31 | acquire(1);
32 | }
33 |
34 | public void lockInterruptibly() throws InterruptedException {
35 | acquireInterruptibly(1);
36 | }
37 |
38 | public boolean tryLock() {
39 | return tryAcquire(1);
40 | }
41 |
42 | public boolean tryLock(long time, TimeUnit unit)
43 | throws InterruptedException {
44 | return tryAcquireNanos(1, unit.toNanos(time));
45 | }
46 |
47 | public void unlock() {
48 | release(1);
49 | }
50 |
51 | public boolean isHeldByCurrentThread() {
52 | return isHeldExclusively();
53 | }
54 |
55 | public Condition newCondition() {
56 | return new ConditionObject();
57 | }
58 |
59 | @Override
60 | protected boolean tryAcquire(int acquires) {
61 | if (compareAndSetState(0, 1)) {
62 | owner = Thread.currentThread();
63 | return true;
64 | }
65 | return false;
66 | }
67 |
68 | @Override
69 | protected boolean tryRelease(int releases) {
70 | if (Thread.currentThread() != owner) {
71 | throw new IllegalMonitorStateException();
72 | }
73 | owner = null;
74 | setState(0);
75 | return true;
76 | }
77 |
78 | @Override
79 | protected boolean isHeldExclusively() {
80 | return getState() != 0 && owner == Thread.currentThread();
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/ReusableIterator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util.internal;
17 |
18 | import java.util.Iterator;
19 |
20 | public interface ReusableIterator extends Iterator {
21 | void rewind();
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/SharedResourceMisuseDetector.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util.internal;
17 |
18 | import java.util.concurrent.atomic.AtomicBoolean;
19 | import java.util.concurrent.atomic.AtomicLong;
20 |
21 | import org.jboss.netty.logging.InternalLogger;
22 | import org.jboss.netty.logging.InternalLoggerFactory;
23 |
24 | /**
25 | * Warn when user creates too many instances to avoid {@link OutOfMemoryError}.
26 | */
27 | public class SharedResourceMisuseDetector {
28 |
29 | private static final int MAX_ACTIVE_INSTANCES = 256;
30 | private static final InternalLogger logger =
31 | InternalLoggerFactory.getInstance(SharedResourceMisuseDetector.class);
32 |
33 | private final Class> type;
34 | private final AtomicLong activeInstances = new AtomicLong();
35 | private final AtomicBoolean logged = new AtomicBoolean();
36 |
37 | public SharedResourceMisuseDetector(Class> type) {
38 | if (type == null) {
39 | throw new NullPointerException("type");
40 | }
41 | this.type = type;
42 | }
43 |
44 | public void increase() {
45 | if (activeInstances.incrementAndGet() > MAX_ACTIVE_INSTANCES) {
46 | if (logger.isWarnEnabled()) {
47 | if (logged.compareAndSet(false, true)) {
48 | logger.warn(
49 | "You are creating too many " + type.getSimpleName() +
50 | " instances. " + type.getSimpleName() +
51 | " is a shared resource that must be reused across the" +
52 | " application, so that only a few instances are created.");
53 | }
54 | }
55 | }
56 | }
57 |
58 | public void decrease() {
59 | activeInstances.decrementAndGet();
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/ThreadLocalBoolean.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util.internal;
17 |
18 | public class ThreadLocalBoolean extends ThreadLocal {
19 |
20 | private final boolean defaultValue;
21 |
22 | public ThreadLocalBoolean() {
23 | this(false);
24 | }
25 |
26 | public ThreadLocalBoolean(boolean defaultValue) {
27 | this.defaultValue = defaultValue;
28 | }
29 |
30 | @Override
31 | protected Boolean initialValue() {
32 | return defaultValue? Boolean.TRUE : Boolean.FALSE;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/org/jboss/netty/util/internal/UnterminatableExecutor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 The Netty Project
3 | *
4 | * The Netty Project licenses this file to you under the Apache License,
5 | * version 2.0 (the "License"); you may not use this file except in compliance
6 | * with the License. You may obtain a copy of the License at:
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations
14 | * under the License.
15 | */
16 | package org.jboss.netty.util.internal;
17 |
18 | import java.util.concurrent.Executor;
19 |
20 | /**
21 | * Disables shutdown of an {@link Executor} by wrapping the {@link Executor}.
22 | */
23 | public class UnterminatableExecutor implements Executor {
24 |
25 | private final Executor executor;
26 |
27 | public UnterminatableExecutor(Executor executor) {
28 | if (executor == null) {
29 | throw new NullPointerException("executor");
30 | }
31 | this.executor = executor;
32 | }
33 |
34 | public void execute(Runnable command) {
35 | executor.execute(command);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/com/nyankosama/test/EchoServer.java:
--------------------------------------------------------------------------------
1 | package com.nyankosama.test;
2 |
3 |
4 | import org.jboss.netty.bootstrap.ServerBootstrap;
5 | import org.jboss.netty.channel.core.ChannelPipeline;
6 | import org.jboss.netty.channel.core.ChannelPipelineFactory;
7 | import org.jboss.netty.channel.core.Channels;
8 | import org.jboss.netty.channel.socket.nio.server.NioServerSocketChannelFactory;
9 | import java.net.InetSocketAddress;
10 | import java.util.concurrent.Executors;
11 |
12 | /**
13 | * Created by hlr@superid.cn on 2014/8/15.
14 | */
15 | public class EchoServer {
16 |
17 | public void run() throws Exception{
18 | // Configure the server.
19 | System.out.println("server start");
20 | ServerBootstrap bootstrap = new ServerBootstrap(
21 | new NioServerSocketChannelFactory(
22 | Executors.newCachedThreadPool(),
23 | Executors.newCachedThreadPool()));
24 |
25 | // Set up the pipeline factory.
26 | bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
27 | public ChannelPipeline getPipeline() throws Exception {
28 | return Channels.pipeline(new EchoServerHandler());
29 | }
30 | });
31 |
32 | // Bind and start to accept incoming connections.
33 | bootstrap.bind(new InetSocketAddress(9123));
34 | }
35 |
36 | public static void main(String args[]) throws Exception {
37 | new EchoServer().run();
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/com/nyankosama/test/EchoServerHandler.java:
--------------------------------------------------------------------------------
1 | package com.nyankosama.test;
2 |
3 | import org.jboss.netty.channel.core.ChannelHandlerContext;
4 | import org.jboss.netty.channel.event.ChannelStateEvent;
5 | import org.jboss.netty.channel.event.MessageEvent;
6 | import org.jboss.netty.channel.core.impl.SimpleChannelUpstreamHandler;
7 |
8 | /**
9 | * Created by hlr@superid.cn on 2014/8/15.
10 | */
11 | public class EchoServerHandler extends SimpleChannelUpstreamHandler {
12 |
13 | @Override
14 | public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
15 | e.getChannel().write(e.getMessage());
16 | }
17 |
18 | @Override
19 | public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
20 | super.channelOpen(ctx, e);
21 | }
22 |
23 | @Override
24 | public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
25 | super.channelConnected(ctx, e);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/nyankosama/test/SimpleClient.java:
--------------------------------------------------------------------------------
1 | package com.nyankosama.test;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.io.PrintWriter;
7 | import java.net.InetSocketAddress;
8 | import java.net.Socket;
9 |
10 | /**
11 | * Created by hlr@superid.cn on 2014/10/28.
12 | */
13 | public class SimpleClient {
14 |
15 | public static void main(String args[]) throws IOException {
16 | new SimpleClient().testClient();
17 | }
18 |
19 | public void testClient() throws IOException {
20 | String ip = "127.0.0.1";
21 | int requestNum = 10000;
22 | Socket socket = new Socket();
23 | socket.connect(new InetSocketAddress(ip, 9123));
24 | PrintWriter writer = new PrintWriter(socket.getOutputStream());
25 | BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
26 |
27 | long begin = System.currentTimeMillis();
28 | int num = requestNum;
29 | for (int i = 0; i < num; i++) {
30 | writer.println("hello world!");
31 | writer.flush();
32 | reader.readLine();
33 | }
34 | socket.close();
35 | long end = System.currentTimeMillis();
36 | System.out.println("cost time:" + (end - begin) + " ms, qps:" + ((double) num / (end - begin) * 1000));
37 | }
38 | }
39 |
--------------------------------------------------------------------------------