├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
└── java
│ └── us
│ └── codecraft
│ └── netty_servlet
│ ├── connector
│ ├── AbstractConnector.java
│ ├── Connector.java
│ └── netty
│ │ ├── ChannelBufferServletInputStream.java
│ │ ├── ChannelBufferServletOutputStream.java
│ │ ├── EnumerationIterableAdaptor.java
│ │ ├── HttpServerHandler.java
│ │ ├── HttpServerPipelineFactory.java
│ │ ├── NettyConnector.java
│ │ ├── NettyHttpServletRequestAdaptor.java
│ │ ├── NettyHttpServletResponseAdaptor.java
│ │ └── NettyToServletCookieConvertor.java
│ └── container
│ └── Dispatcher.java
└── test
└── java
└── us
└── codecraft
└── express
└── connector
└── NettyConnectorTest.java
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | netty-servlet
2 | =============
3 |
4 | A tiny servlet container using netty.
5 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | org.sonatype.oss
6 | oss-parent
7 | 7
8 |
9 | 4.0.0
10 |
11 | us.codecraft
12 | netty-servlet
13 | 0.1.0-SNAPSHOT
14 |
15 |
16 | UTF-8
17 | UTF-8
18 |
19 |
20 |
21 | A tiny servlet container using netty.
22 |
23 | https://github.com/code4craft/netty-servlet
24 |
25 |
26 | code4craft
27 | Yihua huang
28 | code4crafer@gmail.com
29 |
30 |
31 |
32 | scm:git:git@github.com:code4craft/netty-servlet.java.git
33 | scm:git:git@github.com:code4craft/netty-servlet.java.git
34 | git@github.com:code4craft/netty-servlet.java.git
35 | HEAD
36 |
37 |
38 |
39 | Apache License, Version 2.0
40 | http://www.apache.org/licenses/LICENSE-2.0
41 |
42 |
43 |
44 |
45 |
46 | com.google.guava
47 | guava
48 | 15.0
49 |
50 |
51 | javax.servlet
52 | javax.servlet-api
53 | 3.0.1
54 |
55 |
56 | io.netty
57 | netty
58 | 3.9.0.Final
59 |
60 |
61 | junit
62 | junit
63 | 4.11
64 | test
65 |
66 |
67 | org.apache.httpcomponents
68 | fluent-hc
69 | 4.3.2
70 | test
71 |
72 |
73 | org.assertj
74 | assertj-core
75 | 1.5.0
76 | test
77 |
78 |
79 | org.mockito
80 | mockito-all
81 | 1.9.5
82 | test
83 |
84 |
85 |
86 |
87 |
88 |
89 | org.apache.maven.plugins
90 | maven-compiler-plugin
91 | 3.1
92 |
93 | 1.6
94 | 1.6
95 | utf-8
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 | release-sign-artifacts
104 |
105 |
106 | performRelease
107 | true
108 |
109 |
110 |
111 |
112 |
113 | org.apache.maven.plugins
114 | maven-gpg-plugin
115 | 1.1
116 |
117 |
118 | sign-artifacts
119 | verify
120 |
121 | sign
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/AbstractConnector.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.connector;
2 |
3 | import us.codecraft.netty_servlet.container.Dispatcher;
4 |
5 | /**
6 | * @author code4crafter@gmail.com
7 | */
8 | public abstract class AbstractConnector implements Connector {
9 |
10 | private int port;
11 |
12 | private Dispatcher dispatcher;
13 |
14 | @Override
15 | public AbstractConnector port(int port) {
16 | this.port = port;
17 | return this;
18 | }
19 |
20 | protected int getPort() {
21 | return port;
22 | }
23 |
24 | @Override
25 | public Connector dispatcher(Dispatcher dispatcher) {
26 | this.dispatcher = dispatcher;
27 | return this;
28 | }
29 |
30 | public Dispatcher getDispatcher() {
31 | return dispatcher;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/Connector.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.connector;
2 |
3 | import us.codecraft.netty_servlet.container.Dispatcher;
4 |
5 | /**
6 | * @author yihua.huang@dianping.com
7 | */
8 | public interface Connector {
9 |
10 | public Connector port(int port);
11 |
12 | public Connector stop() throws Exception;
13 |
14 | public Connector start() throws Exception;
15 |
16 | public Connector dispatcher(Dispatcher dispatcher);
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/netty/ChannelBufferServletInputStream.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.connector.netty;
2 |
3 | import org.jboss.netty.buffer.ChannelBuffer;
4 |
5 | import javax.servlet.ServletInputStream;
6 | import java.io.DataInput;
7 | import java.io.DataInputStream;
8 | import java.io.EOFException;
9 | import java.io.IOException;
10 |
11 | /**
12 | * @author yihua.huang@dianping.com
13 | */
14 | public class ChannelBufferServletInputStream extends ServletInputStream implements DataInput {
15 |
16 | private final ChannelBuffer buffer;
17 | private final int startIndex;
18 | private final int endIndex;
19 |
20 | /**
21 | * Creates a new stream which reads data from the specified {@code buffer}
22 | * starting at the current {@code readerIndex} and ending at the current
23 | * {@code writerIndex}.
24 | */
25 | public ChannelBufferServletInputStream(ChannelBuffer buffer) {
26 | this(buffer, buffer.readableBytes());
27 | }
28 |
29 | /**
30 | * Creates a new stream which reads data from the specified {@code buffer}
31 | * starting at the current {@code readerIndex} and ending at
32 | * {@code readerIndex + length}.
33 | *
34 | * @throws IndexOutOfBoundsException if {@code readerIndex + length} is greater than
35 | * {@code writerIndex}
36 | */
37 | public ChannelBufferServletInputStream(ChannelBuffer buffer, int length) {
38 | if (buffer == null) {
39 | throw new NullPointerException("buffer");
40 | }
41 | if (length < 0) {
42 | throw new IllegalArgumentException("length: " + length);
43 | }
44 | if (length > buffer.readableBytes()) {
45 | throw new IndexOutOfBoundsException("Too many bytes to be read - Needs "
46 | + length + ", maximum is " + buffer.readableBytes());
47 | }
48 |
49 | this.buffer = buffer;
50 | startIndex = buffer.readerIndex();
51 | endIndex = startIndex + length;
52 | buffer.markReaderIndex();
53 | }
54 |
55 | /**
56 | * Returns the number of read bytes by this stream so far.
57 | */
58 | public int readBytes() {
59 | return buffer.readerIndex() - startIndex;
60 | }
61 |
62 | @Override
63 | public int available() throws IOException {
64 | return endIndex - buffer.readerIndex();
65 | }
66 |
67 | @Override
68 | public void mark(int readlimit) {
69 | buffer.markReaderIndex();
70 | }
71 |
72 | @Override
73 | public boolean markSupported() {
74 | return true;
75 | }
76 |
77 | @Override
78 | public int read() throws IOException {
79 | if (!buffer.readable()) {
80 | return -1;
81 | }
82 | return buffer.readByte() & 0xff;
83 | }
84 |
85 | @Override
86 | public int read(byte[] b, int off, int len) throws IOException {
87 | int available = available();
88 | if (available == 0) {
89 | return -1;
90 | }
91 |
92 | len = Math.min(available, len);
93 | buffer.readBytes(b, off, len);
94 | return len;
95 | }
96 |
97 | @Override
98 | public void reset() throws IOException {
99 | buffer.resetReaderIndex();
100 | }
101 |
102 | @Override
103 | public long skip(long n) throws IOException {
104 | if (n > Integer.MAX_VALUE) {
105 | return skipBytes(Integer.MAX_VALUE);
106 | } else {
107 | return skipBytes((int) n);
108 | }
109 | }
110 |
111 | public boolean readBoolean() throws IOException {
112 | checkAvailable(1);
113 | return read() != 0;
114 | }
115 |
116 | public byte readByte() throws IOException {
117 | if (!buffer.readable()) {
118 | throw new EOFException();
119 | }
120 | return buffer.readByte();
121 | }
122 |
123 | public char readChar() throws IOException {
124 | return (char) readShort();
125 | }
126 |
127 | public double readDouble() throws IOException {
128 | return Double.longBitsToDouble(readLong());
129 | }
130 |
131 | public float readFloat() throws IOException {
132 | return Float.intBitsToFloat(readInt());
133 | }
134 |
135 | public void readFully(byte[] b) throws IOException {
136 | readFully(b, 0, b.length);
137 | }
138 |
139 | public void readFully(byte[] b, int off, int len) throws IOException {
140 | checkAvailable(len);
141 | buffer.readBytes(b, off, len);
142 | }
143 |
144 | public int readInt() throws IOException {
145 | checkAvailable(4);
146 | return buffer.readInt();
147 | }
148 |
149 | private final StringBuilder lineBuf = new StringBuilder();
150 |
151 | public String readLine() throws IOException {
152 | lineBuf.setLength(0);
153 | for (; ; ) {
154 | int b = read();
155 | if (b < 0 || b == '\n') {
156 | break;
157 | }
158 |
159 | lineBuf.append((char) b);
160 | }
161 |
162 | if (lineBuf.length() > 0) {
163 | while (lineBuf.charAt(lineBuf.length() - 1) == '\r') {
164 | lineBuf.setLength(lineBuf.length() - 1);
165 | }
166 | }
167 |
168 | return lineBuf.toString();
169 | }
170 |
171 | public long readLong() throws IOException {
172 | checkAvailable(8);
173 | return buffer.readLong();
174 | }
175 |
176 | public short readShort() throws IOException {
177 | checkAvailable(2);
178 | return buffer.readShort();
179 | }
180 |
181 | public String readUTF() throws IOException {
182 | return DataInputStream.readUTF(this);
183 | }
184 |
185 | public int readUnsignedByte() throws IOException {
186 | return readByte() & 0xff;
187 | }
188 |
189 | public int readUnsignedShort() throws IOException {
190 | return readShort() & 0xffff;
191 | }
192 |
193 | public int skipBytes(int n) throws IOException {
194 | int nBytes = Math.min(available(), n);
195 | buffer.skipBytes(nBytes);
196 | return nBytes;
197 | }
198 |
199 | private void checkAvailable(int fieldSize) throws IOException {
200 | if (fieldSize < 0) {
201 | throw new IndexOutOfBoundsException("fieldSize cannot be a negative number");
202 | }
203 | if (fieldSize > available()) {
204 | throw new EOFException("fieldSize is too long! Length is " + fieldSize
205 | + ", but maximum is " + available());
206 | }
207 | }
208 |
209 | }
210 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/netty/ChannelBufferServletOutputStream.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.connector.netty;
2 |
3 | import org.jboss.netty.buffer.ChannelBuffer;
4 |
5 | import javax.servlet.ServletOutputStream;
6 | import java.io.DataOutput;
7 | import java.io.DataOutputStream;
8 | import java.io.IOException;
9 |
10 | /**
11 | * @author yihua.huang@dianping.com
12 | */
13 | public class ChannelBufferServletOutputStream extends ServletOutputStream implements DataOutput {
14 |
15 | private final ChannelBuffer buffer;
16 | private final int startIndex;
17 | private final DataOutputStream utf8out = new DataOutputStream(this);
18 |
19 | /**
20 | * Creates a new stream which writes data to the specified {@code buffer}.
21 | */
22 | public ChannelBufferServletOutputStream(ChannelBuffer buffer) {
23 | if (buffer == null) {
24 | throw new NullPointerException("buffer");
25 | }
26 | this.buffer = buffer;
27 | startIndex = buffer.writerIndex();
28 | }
29 |
30 | /**
31 | * Returns the number of written bytes by this stream so far.
32 | */
33 | public int writtenBytes() {
34 | return buffer.writerIndex() - startIndex;
35 | }
36 |
37 | @Override
38 | public void write(byte[] b, int off, int len) throws IOException {
39 | if (len == 0) {
40 | return;
41 | }
42 |
43 | buffer.writeBytes(b, off, len);
44 | }
45 |
46 | @Override
47 | public void write(byte[] b) throws IOException {
48 | buffer.writeBytes(b);
49 | }
50 |
51 | @Override
52 | public void write(int b) throws IOException {
53 | buffer.writeByte((byte) b);
54 | }
55 |
56 | public void writeBoolean(boolean v) throws IOException {
57 | write(v ? (byte) 1 : (byte) 0);
58 | }
59 |
60 | public void writeByte(int v) throws IOException {
61 | write(v);
62 | }
63 |
64 | public void writeBytes(String s) throws IOException {
65 | int len = s.length();
66 | for (int i = 0; i < len; i++) {
67 | write((byte) s.charAt(i));
68 | }
69 | }
70 |
71 | public void writeChar(int v) throws IOException {
72 | writeShort((short) v);
73 | }
74 |
75 | public void writeChars(String s) throws IOException {
76 | int len = s.length();
77 | for (int i = 0; i < len; i++) {
78 | writeChar(s.charAt(i));
79 | }
80 | }
81 |
82 | public void writeDouble(double v) throws IOException {
83 | writeLong(Double.doubleToLongBits(v));
84 | }
85 |
86 | public void writeFloat(float v) throws IOException {
87 | writeInt(Float.floatToIntBits(v));
88 | }
89 |
90 | public void writeInt(int v) throws IOException {
91 | buffer.writeInt(v);
92 | }
93 |
94 | public void writeLong(long v) throws IOException {
95 | buffer.writeLong(v);
96 | }
97 |
98 | public void writeShort(int v) throws IOException {
99 | buffer.writeShort((short) v);
100 | }
101 |
102 | public void writeUTF(String s) throws IOException {
103 | utf8out.writeUTF(s);
104 | }
105 |
106 | /**
107 | * Returns the buffer where this stream is writing data.
108 | */
109 | public ChannelBuffer buffer() {
110 | return buffer;
111 | }
112 |
113 | }
114 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/netty/EnumerationIterableAdaptor.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.connector.netty;
2 |
3 | import java.util.Enumeration;
4 | import java.util.Iterator;
5 |
6 | /**
7 | * @author code4crafter@gmail.com
8 | */
9 | public class EnumerationIterableAdaptor implements Enumeration {
10 |
11 | private Iterable wrapped;
12 |
13 | private Iterator wrappedIterator;
14 |
15 | public EnumerationIterableAdaptor(Iterable wrapped) {
16 | this.wrapped = wrapped;
17 | this.wrappedIterator = wrapped.iterator();
18 | }
19 |
20 | @Override
21 | public boolean hasMoreElements() {
22 | return wrappedIterator.hasNext();
23 | }
24 |
25 | @Override
26 | public T nextElement() {
27 | return wrappedIterator.next();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/netty/HttpServerHandler.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.connector.netty;
2 |
3 | import org.jboss.netty.buffer.DynamicChannelBuffer;
4 | import org.jboss.netty.channel.*;
5 | import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
6 | import org.jboss.netty.handler.codec.http.HttpHeaders;
7 | import org.jboss.netty.handler.codec.http.HttpRequest;
8 | import org.jboss.netty.handler.codec.http.HttpResponse;
9 | import us.codecraft.netty_servlet.container.Dispatcher;
10 |
11 | import javax.servlet.http.HttpServletRequest;
12 | import javax.servlet.http.HttpServletResponse;
13 |
14 | import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
15 | import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;
16 |
17 | /**
18 | * @author yihua.huang@dianping.com
19 | */
20 | public class HttpServerHandler extends SimpleChannelUpstreamHandler {
21 |
22 | private Dispatcher dispatcher;
23 |
24 | public HttpServerHandler(Dispatcher dispatcher) {
25 | this.dispatcher = dispatcher;
26 | }
27 |
28 | @Override
29 | public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
30 | super.channelClosed(ctx, e);
31 | }
32 |
33 | @Override
34 | public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
35 | if (event.getMessage() instanceof HttpRequest) {
36 | try {
37 | HttpServletRequest httpServletRequest = new NettyHttpServletRequestAdaptor((HttpRequest) event.getMessage(), ctx.getChannel());
38 | HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
39 | response.setContent(new DynamicChannelBuffer(200));
40 | HttpServletResponse httpServletResponse = new NettyHttpServletResponseAdaptor(response, ctx.getChannel());
41 | dispatcher.dispatch(httpServletRequest,httpServletResponse);
42 | response.headers().set(HttpHeaders.Names.CONTENT_LENGTH,response.getContent().writerIndex());
43 | ChannelFuture future = ctx.getChannel().write(response);
44 | future.addListener(ChannelFutureListener.CLOSE);
45 | } catch (Exception e) {
46 | e.printStackTrace();
47 | }
48 | }
49 | }
50 |
51 | @Override
52 | public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
53 | //DO NOTHING ha ha!
54 | super.exceptionCaught(ctx, e);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/netty/HttpServerPipelineFactory.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 us.codecraft.netty_servlet.connector.netty;
17 |
18 | import org.jboss.netty.channel.ChannelPipeline;
19 | import org.jboss.netty.channel.ChannelPipelineFactory;
20 | import org.jboss.netty.handler.codec.http.HttpContentCompressor;
21 | import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
22 | import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
23 | import org.jboss.netty.handler.execution.ExecutionHandler;
24 | import org.jboss.netty.handler.execution.MemoryAwareThreadPoolExecutor;
25 | import us.codecraft.netty_servlet.container.Dispatcher;
26 |
27 | import static org.jboss.netty.channel.Channels.pipeline;
28 |
29 | public class HttpServerPipelineFactory implements ChannelPipelineFactory {
30 |
31 | private Dispatcher dispatcher;
32 |
33 | private ExecutionHandler executionHandler = new ExecutionHandler(new MemoryAwareThreadPoolExecutor(10,0,0));
34 |
35 | public HttpServerPipelineFactory(Dispatcher dispatcher) {
36 | this.dispatcher = dispatcher;
37 | }
38 |
39 | public ChannelPipeline getPipeline() throws Exception {
40 | // Create a default pipeline implementation.
41 | ChannelPipeline pipeline = pipeline();
42 |
43 | pipeline.addLast("decoder", new HttpRequestDecoder());
44 |
45 | pipeline.addLast("encoder", new HttpResponseEncoder());
46 |
47 | // Remove the following line if you don't want automatic content compression.
48 | pipeline.addLast("deflater", new HttpContentCompressor());
49 |
50 | pipeline.addLast("excution", executionHandler);
51 |
52 | pipeline.addLast("handler", new HttpServerHandler(dispatcher));
53 | return pipeline;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/netty/NettyConnector.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.connector.netty;
2 |
3 | import org.jboss.netty.bootstrap.ServerBootstrap;
4 | import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
5 | import us.codecraft.netty_servlet.connector.AbstractConnector;
6 |
7 | import java.net.InetSocketAddress;
8 | import java.util.concurrent.Executors;
9 |
10 | /**
11 | * @author code4crafter@gmail.com
12 | */
13 | public class NettyConnector extends AbstractConnector {
14 |
15 | private ServerBootstrap bootstrap;
16 |
17 | @Override
18 | public NettyConnector stop() throws Exception {
19 | bootstrap.shutdown();
20 | return this;
21 | }
22 |
23 | @Override
24 | public NettyConnector start() throws Exception {
25 | bootstrap = new ServerBootstrap(
26 | new NioServerSocketChannelFactory(
27 | Executors.newCachedThreadPool(),
28 | Executors.newCachedThreadPool()));
29 |
30 | // Set up the event pipeline factory.
31 | bootstrap.setPipelineFactory(new HttpServerPipelineFactory(getDispatcher()));
32 |
33 | bootstrap.setOption("child.tcpNoDelay", true);
34 |
35 | // Bind and start to accept incoming connections.
36 | bootstrap.bind(new InetSocketAddress(getPort()));
37 | return this;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/netty/NettyHttpServletRequestAdaptor.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.connector.netty;
2 |
3 | import org.jboss.netty.channel.Channel;
4 | import org.jboss.netty.handler.codec.http.*;
5 |
6 | import javax.servlet.*;
7 | import javax.servlet.http.*;
8 | import javax.servlet.http.Cookie;
9 | import java.io.BufferedReader;
10 | import java.io.IOException;
11 | import java.io.InputStreamReader;
12 | import java.io.UnsupportedEncodingException;
13 | import java.net.InetSocketAddress;
14 | import java.security.Principal;
15 | import java.util.*;
16 |
17 | /**
18 | * @author code4crafter@gmail.com
19 | */
20 | public class NettyHttpServletRequestAdaptor implements HttpServletRequest {
21 |
22 | private HttpRequest httpRequest;
23 |
24 | private Channel channel;
25 |
26 | private Cookie[] cookieCache;
27 |
28 | private QueryStringDecoder queryStringDecoder;
29 |
30 | private Map parameterMap;
31 |
32 | private String characterEncoding;
33 |
34 | private Map attributes;
35 |
36 | public NettyHttpServletRequestAdaptor(HttpRequest httpRequest, Channel channel) {
37 | this.httpRequest = httpRequest;
38 | this.channel = channel;
39 | this.attributes = new HashMap();
40 | }
41 |
42 | public QueryStringDecoder getQueryStringDecoder() {
43 | if (queryStringDecoder == null) {
44 | queryStringDecoder = new QueryStringDecoder(httpRequest.getUri());
45 | }
46 | return queryStringDecoder;
47 | }
48 |
49 | @Override
50 | public String getAuthType() {
51 | throw new UnsupportedOperationException();
52 | }
53 |
54 | @Override
55 | public Cookie[] getCookies() {
56 | if (cookieCache == null) {
57 | Set cookies = new CookieDecoder().decode(HttpHeaders.Names.COOKIE);
58 | cookieCache = new Cookie[cookies.size()];
59 | NettyToServletCookieConvertor.convert(cookies).toArray(cookieCache);
60 | }
61 | return cookieCache;
62 | }
63 |
64 | @Override
65 | public long getDateHeader(String name) {
66 | throw new UnsupportedOperationException();
67 | }
68 |
69 | @Override
70 | public String getHeader(String name) {
71 | return httpRequest.headers().get(name);
72 | }
73 |
74 | @Override
75 | public Enumeration getHeaders(String name) {
76 | return new EnumerationIterableAdaptor(httpRequest.headers().getAll(name));
77 | }
78 |
79 | @Override
80 | public Enumeration getHeaderNames() {
81 | return new EnumerationIterableAdaptor(httpRequest.headers().names());
82 | }
83 |
84 | @Override
85 | public int getIntHeader(String name) {
86 | return Integer.parseInt(httpRequest.headers().get(name));
87 | }
88 |
89 | @Override
90 | public String getMethod() {
91 | return httpRequest.getMethod().getName();
92 | }
93 |
94 | @Override
95 | public String getPathInfo() {
96 | throw new UnsupportedOperationException();
97 | }
98 |
99 | @Override
100 | public String getPathTranslated() {
101 | throw new UnsupportedOperationException();
102 | }
103 |
104 | @Override
105 | public String getContextPath() {
106 | throw new UnsupportedOperationException();
107 | }
108 |
109 | @Override
110 | public String getQueryString() {
111 | throw new UnsupportedOperationException();
112 | }
113 |
114 | @Override
115 | public String getRemoteUser() {
116 | throw new UnsupportedOperationException();
117 | }
118 |
119 | @Override
120 | public boolean isUserInRole(String role) {
121 | return false;
122 | }
123 |
124 | @Override
125 | public Principal getUserPrincipal() {
126 | throw new UnsupportedOperationException();
127 | }
128 |
129 | @Override
130 | public String getRequestedSessionId() {
131 | throw new UnsupportedOperationException();
132 | }
133 |
134 | @Override
135 | public String getRequestURI() {
136 | return httpRequest.getUri();
137 | }
138 |
139 | @Override
140 | public StringBuffer getRequestURL() {
141 | throw new UnsupportedOperationException();
142 | }
143 |
144 | @Override
145 | public String getServletPath() {
146 | throw new UnsupportedOperationException();
147 | }
148 |
149 | @Override
150 | public HttpSession getSession(boolean create) {
151 | throw new UnsupportedOperationException();
152 | }
153 |
154 | @Override
155 | public HttpSession getSession() {
156 | throw new UnsupportedOperationException();
157 | }
158 |
159 | @Override
160 | public boolean isRequestedSessionIdValid() {
161 | return false;
162 | }
163 |
164 | @Override
165 | public boolean isRequestedSessionIdFromCookie() {
166 | return false;
167 | }
168 |
169 | @Override
170 | public boolean isRequestedSessionIdFromURL() {
171 | return false;
172 | }
173 |
174 | @Override
175 | public boolean isRequestedSessionIdFromUrl() {
176 | return false;
177 | }
178 |
179 | @Override
180 | public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
181 | return false;
182 | }
183 |
184 | @Override
185 | public void login(String username, String password) throws ServletException {
186 | throw new UnsupportedOperationException();
187 | }
188 |
189 | @Override
190 | public void logout() throws ServletException {
191 | throw new UnsupportedOperationException();
192 | }
193 |
194 | @Override
195 | public Collection getParts() throws IOException, ServletException {
196 | throw new UnsupportedOperationException();
197 | }
198 |
199 | @Override
200 | public Part getPart(String name) throws IOException, ServletException {
201 | throw new UnsupportedOperationException();
202 | }
203 |
204 | @Override
205 | public Object getAttribute(String name) {
206 | return attributes.get(name);
207 | }
208 |
209 | @Override
210 | public Enumeration getAttributeNames() {
211 | return new EnumerationIterableAdaptor(attributes.keySet());
212 | }
213 |
214 | @Override
215 | public String getCharacterEncoding() {
216 | return characterEncoding;
217 | }
218 |
219 | @Override
220 | public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
221 | this.characterEncoding = env;
222 | }
223 |
224 | @Override
225 | public int getContentLength() {
226 | return getIntHeader(HttpHeaders.Names.CONTENT_LENGTH);
227 | }
228 |
229 | @Override
230 | public String getContentType() {
231 | return getHeader(HttpHeaders.Names.CONTENT_TYPE);
232 | }
233 |
234 | @Override
235 | public ServletInputStream getInputStream() throws IOException {
236 | return new ChannelBufferServletInputStream(httpRequest.getContent());
237 | }
238 |
239 | @Override
240 | public String getParameter(String name) {
241 | if (getParameterMap().get(name) != null && getParameterMap().get(name).length > 0) {
242 | return getParameterMap().get(name)[0];
243 | }
244 | return null;
245 | }
246 |
247 | @Override
248 | public Enumeration getParameterNames() {
249 | return new EnumerationIterableAdaptor(getParameterMap().keySet());
250 | }
251 |
252 | @Override
253 | public String[] getParameterValues(String name) {
254 | return getParameterMap().get(name);
255 | }
256 |
257 | @Override
258 | public Map getParameterMap() {
259 | if (parameterMap == null) {
260 | parameterMap = new HashMap(getQueryStringDecoder().getParameters().size());
261 | for (Map.Entry> stringListEntry : getQueryStringDecoder().getParameters().entrySet()) {
262 | String[] strings = new String[stringListEntry.getValue().size()];
263 | parameterMap.put(stringListEntry.getKey(), stringListEntry.getValue().toArray(strings));
264 | }
265 | }
266 | return parameterMap;
267 | }
268 |
269 | @Override
270 | public String getProtocol() {
271 | return httpRequest.getProtocolVersion().getText();
272 | }
273 |
274 | @Override
275 | public String getScheme() {
276 | return httpRequest.getProtocolVersion().getProtocolName();
277 | }
278 |
279 | @Override
280 | public BufferedReader getReader() throws IOException {
281 | return new BufferedReader(new InputStreamReader(getInputStream()));
282 | }
283 |
284 | @Override
285 | public void setAttribute(String name, Object o) {
286 | this.attributes.put(name,o);
287 | }
288 |
289 | @Override
290 | public void removeAttribute(String name) {
291 | this.attributes.remove(name);
292 | }
293 |
294 | @Override
295 | public Locale getLocale() {
296 | throw new UnsupportedOperationException();
297 | }
298 |
299 | @Override
300 | public Enumeration getLocales() {
301 | throw new UnsupportedOperationException();
302 | }
303 |
304 | @Override
305 | public boolean isSecure() {
306 | return false;
307 | }
308 |
309 | @Override
310 | public String getRemoteAddr() {
311 | return ((InetSocketAddress)channel.getRemoteAddress()).getAddress().getHostAddress();
312 | }
313 |
314 | @Override
315 | public String getRemoteHost() {
316 | return ((InetSocketAddress)channel.getRemoteAddress()).getHostName();
317 | }
318 |
319 | @Override
320 | public int getRemotePort() {
321 | return ((InetSocketAddress)channel.getRemoteAddress()).getPort();
322 | }
323 |
324 | @Override
325 | public String getLocalName() {
326 | return ((InetSocketAddress)channel.getLocalAddress()).getHostName();
327 | }
328 |
329 | @Override
330 | public String getLocalAddr() {
331 | return ((InetSocketAddress)channel.getLocalAddress()).getAddress().getHostAddress();
332 | }
333 |
334 | @Override
335 | public int getLocalPort() {
336 | return ((InetSocketAddress)channel.getLocalAddress()).getPort();
337 | }
338 |
339 | @Override
340 | public String getServerName() {
341 | return getLocalName();
342 | }
343 |
344 | @Override
345 | public int getServerPort() {
346 | return getLocalPort();
347 | }
348 |
349 | @Override
350 | public ServletContext getServletContext() {
351 | throw new UnsupportedOperationException();
352 | }
353 |
354 | @Override
355 | public AsyncContext startAsync() throws IllegalStateException {
356 | throw new UnsupportedOperationException();
357 | }
358 |
359 | @Override
360 | public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
361 | throw new UnsupportedOperationException();
362 | }
363 |
364 | @Override
365 | public boolean isAsyncStarted() {
366 | throw new UnsupportedOperationException();
367 | }
368 |
369 | @Override
370 | public boolean isAsyncSupported() {
371 | return false;
372 | }
373 |
374 | @Override
375 | public AsyncContext getAsyncContext() {
376 | throw new UnsupportedOperationException();
377 | }
378 |
379 | @Override
380 | public DispatcherType getDispatcherType() {
381 | throw new UnsupportedOperationException();
382 | }
383 |
384 | @Override
385 | public RequestDispatcher getRequestDispatcher(String path) {
386 | throw new UnsupportedOperationException();
387 | }
388 |
389 | @Override
390 | public String getRealPath(String path) {
391 | throw new UnsupportedOperationException();
392 | }
393 | }
394 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/netty/NettyHttpServletResponseAdaptor.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.connector.netty;
2 |
3 | import org.jboss.netty.channel.Channel;
4 | import org.jboss.netty.handler.codec.http.HttpResponse;
5 |
6 | import javax.servlet.ServletOutputStream;
7 | import javax.servlet.http.Cookie;
8 | import javax.servlet.http.HttpServletResponse;
9 | import java.io.IOException;
10 | import java.io.OutputStreamWriter;
11 | import java.io.PrintWriter;
12 | import java.util.Collection;
13 | import java.util.Locale;
14 |
15 | /**
16 | * @author code4crafter@gmail.com
17 | */
18 | public class NettyHttpServletResponseAdaptor implements HttpServletResponse {
19 |
20 | private HttpResponse httpResponse;
21 |
22 | private Channel channel;
23 |
24 | public NettyHttpServletResponseAdaptor(HttpResponse httpResponse, Channel channel) {
25 | this.httpResponse = httpResponse;
26 | this.channel = channel;
27 | }
28 |
29 | @Override
30 | public void addCookie(Cookie cookie) {
31 | }
32 |
33 | @Override
34 | public boolean containsHeader(String name) {
35 | return httpResponse.headers().contains(name);
36 | }
37 |
38 | @Override
39 | public String encodeURL(String url) {
40 | return null;
41 | }
42 |
43 | @Override
44 | public String encodeRedirectURL(String url) {
45 | return null;
46 | }
47 |
48 | @Override
49 | public String encodeUrl(String url) {
50 | return null;
51 | }
52 |
53 | @Override
54 | public String encodeRedirectUrl(String url) {
55 | return null;
56 | }
57 |
58 | @Override
59 | public void sendError(int sc, String msg) throws IOException {
60 |
61 | }
62 |
63 | @Override
64 | public void sendError(int sc) throws IOException {
65 |
66 | }
67 |
68 | @Override
69 | public void sendRedirect(String location) throws IOException {
70 |
71 | }
72 |
73 | @Override
74 | public void setDateHeader(String name, long date) {
75 |
76 | }
77 |
78 | @Override
79 | public void addDateHeader(String name, long date) {
80 |
81 | }
82 |
83 | @Override
84 | public void setHeader(String name, String value) {
85 |
86 | }
87 |
88 | @Override
89 | public void addHeader(String name, String value) {
90 |
91 | }
92 |
93 | @Override
94 | public void setIntHeader(String name, int value) {
95 |
96 | }
97 |
98 | @Override
99 | public void addIntHeader(String name, int value) {
100 |
101 | }
102 |
103 | @Override
104 | public void setStatus(int sc) {
105 |
106 | }
107 |
108 | @Override
109 | public void setStatus(int sc, String sm) {
110 |
111 | }
112 |
113 | @Override
114 | public int getStatus() {
115 | return 0;
116 | }
117 |
118 | @Override
119 | public String getHeader(String name) {
120 | return null;
121 | }
122 |
123 | @Override
124 | public Collection getHeaders(String name) {
125 | return null;
126 | }
127 |
128 | @Override
129 | public Collection getHeaderNames() {
130 | return null;
131 | }
132 |
133 | @Override
134 | public String getCharacterEncoding() {
135 | return null;
136 | }
137 |
138 | @Override
139 | public String getContentType() {
140 | return null;
141 | }
142 |
143 | @Override
144 | public ServletOutputStream getOutputStream() throws IOException {
145 | return new ChannelBufferServletOutputStream(httpResponse.getContent());
146 | }
147 |
148 | @Override
149 | public PrintWriter getWriter() throws IOException {
150 | return new PrintWriter(new OutputStreamWriter(getOutputStream()));
151 | }
152 |
153 | @Override
154 | public void setCharacterEncoding(String charset) {
155 |
156 | }
157 |
158 | @Override
159 | public void setContentLength(int len) {
160 |
161 | }
162 |
163 | @Override
164 | public void setContentType(String type) {
165 |
166 | }
167 |
168 | @Override
169 | public void setBufferSize(int size) {
170 |
171 | }
172 |
173 | @Override
174 | public int getBufferSize() {
175 | return 0;
176 | }
177 |
178 | @Override
179 | public void flushBuffer() throws IOException {
180 | }
181 |
182 | @Override
183 | public void resetBuffer() {
184 |
185 | }
186 |
187 | @Override
188 | public boolean isCommitted() {
189 | return false;
190 | }
191 |
192 | @Override
193 | public void reset() {
194 |
195 | }
196 |
197 | @Override
198 | public void setLocale(Locale loc) {
199 |
200 | }
201 |
202 | @Override
203 | public Locale getLocale() {
204 | return null;
205 | }
206 | }
207 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/connector/netty/NettyToServletCookieConvertor.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.connector.netty;
2 |
3 | import javax.servlet.http.Cookie;
4 | import java.util.ArrayList;
5 | import java.util.Collection;
6 | import java.util.List;
7 |
8 | /**
9 | * @author yihua.huang@dianping.com
10 | */
11 | public abstract class NettyToServletCookieConvertor {
12 |
13 | public static Cookie convert(org.jboss.netty.handler.codec.http.Cookie nettyCookie){
14 | Cookie servletCookie = new Cookie(nettyCookie.getName(),nettyCookie.getValue());
15 | servletCookie.setDomain(nettyCookie.getDomain());
16 | servletCookie.setMaxAge(nettyCookie.getMaxAge());
17 | servletCookie.setHttpOnly(nettyCookie.isHttpOnly());
18 | servletCookie.setPath(nettyCookie.getPath());
19 | servletCookie.setSecure(nettyCookie.isSecure());
20 | servletCookie.setVersion(nettyCookie.getVersion());
21 | servletCookie.setComment(nettyCookie.getComment());
22 | return servletCookie;
23 | }
24 |
25 | public static List convert(Collection nettyCookies){
26 | List servletCookies = new ArrayList(nettyCookies.size());
27 | for (org.jboss.netty.handler.codec.http.Cookie nettyCookie : nettyCookies) {
28 | servletCookies.add(convert(nettyCookie));
29 | }
30 | return servletCookies;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/us/codecraft/netty_servlet/container/Dispatcher.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.netty_servlet.container;
2 |
3 | import javax.servlet.http.HttpServletRequest;
4 | import javax.servlet.http.HttpServletResponse;
5 | import java.io.IOException;
6 |
7 | /**
8 | * @author yihua.huang@dianping.com
9 | */
10 | public interface Dispatcher {
11 |
12 | public void dispatch(HttpServletRequest request,HttpServletResponse response) throws IOException;
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/us/codecraft/express/connector/NettyConnectorTest.java:
--------------------------------------------------------------------------------
1 | package us.codecraft.express.connector;
2 |
3 | import org.apache.http.client.fluent.Request;
4 | import org.junit.Test;
5 | import us.codecraft.netty_servlet.connector.Connector;
6 | import us.codecraft.netty_servlet.connector.netty.NettyConnector;
7 | import us.codecraft.netty_servlet.container.Dispatcher;
8 |
9 | import javax.servlet.http.HttpServletRequest;
10 | import javax.servlet.http.HttpServletResponse;
11 | import java.io.IOException;
12 |
13 | import static org.assertj.core.api.Assertions.assertThat;
14 |
15 | /**
16 | * @author yihua.huang@dianping.com
17 | */
18 | public class NettyConnectorTest {
19 |
20 | public static final String HELLO_WORLD = "hello_world";
21 | public static final String TEST_HEADER = "test";
22 |
23 | @Test
24 | public void should_mock_dispatcher_return_assumed_body() throws Exception {
25 | Connector connector = new NettyConnector();
26 | connector.port(8080).dispatcher(mockDispatcher()).start();
27 | String returnString = Request.Get("http://127.0.0.1:8080/").connectTimeout(1000).socketTimeout(1000).execute()
28 | .returnContent().asString();
29 | assertThat(returnString).isEqualTo(HELLO_WORLD);
30 | connector.stop();
31 | }
32 |
33 | private Dispatcher mockDispatcher() {
34 | return new Dispatcher() {
35 | @Override
36 | public void dispatch(HttpServletRequest request, HttpServletResponse response) throws IOException {
37 | response.getOutputStream().print(HELLO_WORLD);
38 | }
39 | };
40 | }
41 |
42 | @Test
43 | public void should_dispatcher_get_assumed_param() throws Exception {
44 | Connector connector = new NettyConnector();
45 | connector.port(8080).dispatcher(new Dispatcher() {
46 | @Override
47 | public void dispatch(HttpServletRequest request, HttpServletResponse response) throws IOException {
48 | assertThat(request.getHeader(TEST_HEADER)).isEqualTo(HELLO_WORLD);
49 | assertThat(request.getRequestURI()).isEqualTo("/"+HELLO_WORLD);
50 | response.getOutputStream().print(HELLO_WORLD);
51 | }
52 | }).start();
53 | Request.Get("http://127.0.0.1:8080/" + HELLO_WORLD).connectTimeout(1000)
54 | .socketTimeout(1000).addHeader(TEST_HEADER, HELLO_WORLD).execute().returnContent().asString();
55 | connector.stop();
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------