├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── NOTICE.txt ├── README.md ├── build.gradle ├── gradle ├── benchmark.gradle ├── dependencies.gradle ├── idea-codestyle.xml ├── idea-copyright.xml ├── idea-entrypoints.xml ├── idea-inspections.xml ├── idea.gradle ├── integTest.gradle ├── maven.gradle ├── test.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── integTest ├── groovy │ └── org │ │ └── springframework │ │ └── boot │ │ └── context │ │ └── embedded │ │ └── netty │ │ └── NettyEmbeddedServletContainerAutoConfigurationIntegrationTest.groovy ├── java │ └── org │ │ └── springframework │ │ └── boot │ │ └── context │ │ └── embedded │ │ └── netty │ │ ├── HttpContentInputStreamBenchmark.java │ │ ├── HttpResponseOutputStreamBenchmark.java │ │ ├── NettyHttpServletResponseBenchmark.java │ │ ├── StubChannelHandlerContext.java │ │ └── TestApplication.java └── resources │ └── logback.xml ├── main └── java │ └── org │ └── springframework │ └── boot │ └── context │ └── embedded │ └── netty │ ├── AbstractNettyRegistration.java │ ├── HttpContentInputStream.java │ ├── HttpResponseOutputStream.java │ ├── NettyAsyncContext.java │ ├── NettyEmbeddedContext.java │ ├── NettyEmbeddedServletContainer.java │ ├── NettyEmbeddedServletContainerAutoConfiguration.java │ ├── NettyEmbeddedServletContainerFactory.java │ ├── NettyEmbeddedServletInitializer.java │ ├── NettyFilterRegistration.java │ ├── NettyHttpServletRequest.java │ ├── NettyHttpServletResponse.java │ ├── NettyRequestDispatcher.java │ ├── NettyServletRegistration.java │ ├── RequestDispatcherHandler.java │ ├── ServletContentHandler.java │ ├── SimpleFilterChain.java │ └── package-info.java └── test └── groovy └── org └── springframework └── boot └── context └── embedded └── netty ├── HttpContentInputStreamTest.groovy └── PackageSanityTest.groovy /.gitignore: -------------------------------------------------------------------------------- 1 | ### Gradle ### 2 | .gradle 3 | build/ 4 | 5 | ### Intellij ### 6 | 7 | ## Directory-based project format 8 | .idea/ 9 | 10 | ## File-based project format 11 | *.ipr 12 | *.iml 13 | *.iws 14 | 15 | ## Additional for IntelliJ 16 | out/ 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DanielThomas/spring-boot-starter-netty/d1485e7d4c8fe047e46b43f105d18b1f2b521eeb/NOTICE.txt -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | A prototype Netty embedded servlet bridge for Spring Boot. 2 | 3 | Includes basic filter and servlet support. I'm fairly new to Spring Boot, but this approach seems to fit it's opinionated view of the servlet container. Async servlet support isn't yet completed. 4 | 5 | [![Build Status](https://travis-ci.org/DanielThomas/spring-boot-starter-netty.svg?branch=master)](https://travis-ci.org/DanielThomas/spring-boot-starter-netty) 6 | 7 | Performance 8 | ============= 9 | 10 | Use the `runTestApp` Gradle task to start the server with the same configuration used here. Tests run with `wrk` with the following arguments: 11 | 12 | wrk -H 'Host: localhost' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Connection: keep-alive' -d 120 -c 32 -t 2 http://localhost:8080/plaintext 13 | 14 | Tomcat 7.0.55 15 | ------------- 16 | 17 | Running 2m test @ http://localhost:8080/plaintext 18 | 2 threads and 32 connections 19 | Thread Stats Avg Stdev Max +/- Stdev 20 | Latency 22.96ms 115.34ms 628.47ms 96.50% 21 | Req/Sec 16.33k 4.74k 34.44k 83.57% 22 | 3691775 requests in 2.00m, 497.09MB read 23 | Requests/sec: 30764.62 24 | Transfer/sec: 4.14MB 25 | 26 | Tomcat 8.0.9 27 | ------------- 28 | 29 | Running 2m test @ http://localhost:8080/plaintext 30 | 2 threads and 32 connections 31 | Thread Stats Avg Stdev Max +/- Stdev 32 | Latency 114.10ms 745.91ms 5.04s 97.75% 33 | Req/Sec 15.67k 2.99k 27.56k 91.68% 34 | 3553322 requests in 2.00m, 478.45MB read 35 | Socket errors: connect 0, read 0, write 0, timeout 3 36 | Requests/sec: 29611.00 37 | Transfer/sec: 3.99MB 38 | 39 | Prototype Netty 4.0 Bridge 40 | ------------- 41 | 42 | Running 2m test @ http://localhost:8080/plaintext 43 | 2 threads and 32 connections 44 | Thread Stats Avg Stdev Max +/- Stdev 45 | Latency 1.14ms 6.64ms 128.33ms 99.33% 46 | Req/Sec 19.64k 4.16k 45.22k 83.96% 47 | 4459068 requests in 2.00m, 331.69MB read 48 | Requests/sec: 37158.91 49 | Transfer/sec: 2.76MB 50 | 51 | Note: Difference in transfer/sec is due to Server and Date headers returned by Tomcat 52 | 53 | Prototype Netty 4.1 Beta 1 Bridge 54 | ------------- 55 | 56 | Running 2m test @ http://localhost:8080/plaintext 57 | 2 threads and 32 connections 58 | Thread Stats Avg Stdev Max +/- Stdev 59 | Latency 1.09ms 7.58ms 200.99ms 99.80% 60 | Req/Sec 19.14k 2.19k 39.89k 84.44% 61 | 4366902 requests in 2.00m, 408.12MB read 62 | Requests/sec: 36390.84 63 | Transfer/sec: 3.40MB 64 | 65 | When compared to a null servlet: 66 | 67 | Running 2m test @ http://localhost:8080/null 68 | 2 threads and 32 connections 69 | Thread Stats Avg Stdev Max +/- Stdev 70 | Latency 820.84us 3.47ms 66.04ms 99.70% 71 | Req/Sec 26.03k 4.27k 45.44k 69.68% 72 | 5894335 requests in 2.00m, 505.91MB read 73 | Requests/sec: 49119.58 74 | 75 | And to serving the response directly from Netty: 76 | 77 | Running 2m test @ http://localhost:8080/nullnetty 78 | 2 threads and 32 connections 79 | Thread Stats Avg Stdev Max +/- Stdev 80 | Latency 2.01ms 23.54ms 400.01ms 99.65% 81 | Req/Sec 27.21k 4.26k 41.44k 66.08% 82 | 6164886 requests in 2.00m, 223.41MB read 83 | Requests/sec: 51374.16 84 | 85 | Prototype Netty 4.1 Beta 3 Bridge (Commit eb531c6) 86 | ------------- 87 | 88 | Running 2m test @ http://localhost:8080/plaintext 89 | 2 threads and 32 connections 90 | Thread Stats Avg Stdev Max +/- Stdev 91 | Latency 1.95ms 18.62ms 289.53ms 99.57% 92 | Req/Sec 20.48k 2.55k 37.78k 86.51% 93 | 4637061 requests in 2.00m, 698.71MB read 94 | Requests/sec: 38642.24 95 | Transfer/sec: 5.82MB 96 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | plugins { 19 | id 'java' 20 | id 'groovy' 21 | id 'com.github.ben-manes.versions' version '0.11.3' 22 | } 23 | 24 | version '1.0-SNAPSHOT' 25 | description 'Spring Boot Netty Starter' 26 | 27 | apply from: 'gradle/dependencies.gradle' 28 | apply from: 'gradle/idea.gradle' 29 | apply from: 'gradle/maven.gradle' 30 | apply from: 'gradle/test.gradle' 31 | 32 | dependencies { 33 | compile libraries.guava 34 | compile libraries.netty 35 | compile libraries.servletapi 36 | compile libraries.springboot 37 | 38 | testCompile libraries.testlibs 39 | } 40 | 41 | jar { 42 | manifest { 43 | attributes('Implementation-Title': description, 'Implementation-Version': version) 44 | } 45 | } 46 | 47 | task wrapper(type: Wrapper) { gradleVersion = '2.8' } 48 | 49 | repositories { 50 | jcenter() 51 | } 52 | -------------------------------------------------------------------------------- /gradle/benchmark.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | dependencies { 19 | testCompile 'org.openjdk.jmh:jmh-generator-annprocess:1.11.2' 20 | } 21 | 22 | task(benchmark, type: JavaExec) { 23 | classpath sourceSets.test.runtimeClasspath 24 | main = 'org.openjdk.jmh.Main' 25 | } 26 | 27 | task(integBenchmark, type: JavaExec) { 28 | classpath sourceSets.integTest.runtimeClasspath 29 | main = 'org.openjdk.jmh.Main' 30 | } 31 | -------------------------------------------------------------------------------- /gradle/dependencies.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | ext { 19 | libraries = [:] 20 | versions = [:] 21 | } 22 | 23 | versions.guava = '18.0' 24 | versions.spock = '1.0-groovy-2.4' 25 | versions.springboot = '1.2.7.RELEASE' 26 | 27 | configurations.all { 28 | resolutionStrategy { 29 | eachDependency { details -> 30 | switch (details.requested.name) { 31 | case 'junit': 32 | case 'junit-dep': 33 | details.useTarget 'junit:junit:4.11' 34 | break 35 | } 36 | if (details.requested.group == 'org.apache.tomcat.embed') { 37 | details.useVersion '8.0.9' 38 | } 39 | } 40 | def isCiServer = System.getenv().containsKey('HUDSON_HOME') 41 | if (isCiServer) { 42 | cacheChangingModulesFor 0, 'seconds' 43 | } 44 | } 45 | } 46 | 47 | 48 | libraries.guava = [ 49 | "com.google.guava:guava:$versions.guava", 50 | 'com.google.code.findbugs:jsr305:3.0.1' 51 | ] 52 | libraries.netty = [ 53 | 'io.netty:netty-all:4.1.0.Beta7', 54 | 'org.javassist:javassist:3.20.0-GA', 55 | 'com.jcraft:jzlib:1.1.3', 56 | 'javax.el:javax.el-api:2.2.5' 57 | ] 58 | libraries.servletapi = 'javax.servlet:javax.servlet-api:3.1.0' 59 | 60 | libraries.springboot = [ 61 | dependencies.create("org.springframework.boot:spring-boot-starter-web:$versions.springboot") { 62 | exclude module: 'spring-boot-starter-tomcat' 63 | } 64 | ] 65 | 66 | libraries.guavatest = "com.google.guava:guava-testlib:$versions.guava" 67 | libraries.spock = [ 68 | "org.spockframework:spock-core:$versions.spock", 69 | 'cglib:cglib-nodep:3.2.0', 70 | 'org.objenesis:objenesis:2.2' 71 | ] 72 | 73 | libraries.testlibs = [ 74 | libraries.guavatest, 75 | libraries.spock 76 | ] 77 | -------------------------------------------------------------------------------- /gradle/idea-codestyle.xml: -------------------------------------------------------------------------------- 1 | 17 | 18 | 19 | 268 | 270 | -------------------------------------------------------------------------------- /gradle/idea-copyright.xml: -------------------------------------------------------------------------------- 1 | 17 | 18 | 19 | 20 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /gradle/idea-entrypoints.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /gradle/idea-inspections.xml: -------------------------------------------------------------------------------- 1 | 17 | 18 | 19 | 20 | 21 | 32 | 33 | 37 | -------------------------------------------------------------------------------- /gradle/idea.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | apply plugin: 'idea' 19 | 20 | idea { 21 | project { 22 | jdkName = targetCompatibility 23 | languageLevel = targetCompatibility 24 | wildcards += 'logback.groovy' 25 | 26 | ipr { 27 | withXml { provider -> 28 | def node = provider.asNode() 29 | 30 | def codestyle = new XmlParser().parse(file('gradle/idea-codestyle.xml')) 31 | node.append(codestyle) 32 | 33 | def inspections = new XmlParser().parse(file('gradle/idea-inspections.xml')) 34 | node.append(inspections) 35 | 36 | def entrypoints = new XmlParser().parse(file('gradle/idea-entrypoints.xml')) 37 | node.append(entrypoints) 38 | 39 | def compilerConfig = node.component.find { it.'@name' == 'CompilerConfiguration' } 40 | compilerConfig.getByName('annotationProcessing').each { compilerConfig.remove(it) } 41 | def annotationProcessing = compilerConfig.appendNode('annotationProcessing') 42 | annotationProcessing.appendNode('profile', ['default': true, 'name': 'Default', 'enabled': true]).appendNode('processorPath', ['useClasspath': true]) 43 | 44 | def copyrightManager = node.component.find { it.'@name' == 'CopyrightManager' } 45 | node.remove(copyrightManager) 46 | def copyright = new XmlParser().parse(file('gradle/idea-copyright.xml')) 47 | node.append(copyright) 48 | 49 | def vcsDirectoryMappings = node.component.find { it.'@name' == 'VcsDirectoryMappings' } 50 | def mappings = vcsDirectoryMappings.iterator() 51 | while (mappings.hasNext()) { 52 | mappings.next() 53 | mappings.remove() 54 | } 55 | 56 | def gitRoot = file('.git') 57 | if (gitRoot.exists()) { 58 | vcsDirectoryMappings.appendNode('mapping', ['directory': gitRoot.parentFile, 'vcs': 'Git']) 59 | } 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /gradle/integTest.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | sourceSets { 19 | integTest { 20 | compileClasspath += main.output + test.output 21 | runtimeClasspath += main.output + test.output 22 | } 23 | } 24 | 25 | configurations { 26 | integTestCompile.extendsFrom testCompile 27 | integTestRuntime.extendsFrom testRuntime 28 | } 29 | 30 | task integTest(type: Test) { 31 | testClassesDir = sourceSets.integTest.output.classesDir 32 | classpath = sourceSets.integTest.runtimeClasspath 33 | testSrcDirs = [] 34 | } 35 | 36 | check.dependsOn(integTest) 37 | 38 | plugins.withType(org.gradle.plugins.ide.idea.IdeaPlugin) { 39 | idea { 40 | module { 41 | testSourceDirs += sourceSets.integTest.java.srcDirs 42 | testSourceDirs += sourceSets.integTest.groovy.srcDirs 43 | testSourceDirs += sourceSets.integTest.resources.srcDirs 44 | scopes.TEST.plus.add(configurations.integTestCompile) 45 | scopes.TEST.plus.add(configurations.integTestRuntime) 46 | } 47 | } 48 | } 49 | 50 | plugins.withType(org.gradle.plugins.ide.eclipse.EclipsePlugin) { 51 | eclipse { 52 | classpath { 53 | plusConfigurations.add(configurations.integTestCompile) 54 | plusConfigurations.add(configurations.integTestRuntime) 55 | } 56 | } 57 | } 58 | 59 | task(runTestApp, type: JavaExec) { 60 | classpath sourceSets.integTest.runtimeClasspath 61 | main = 'org.springframework.boot.context.embedded.netty.TestApplication' 62 | } 63 | -------------------------------------------------------------------------------- /gradle/maven.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | apply plugin: 'maven' 19 | 20 | repositories { 21 | mavenCentral() 22 | } 23 | -------------------------------------------------------------------------------- /gradle/test.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | apply plugin: 'jacoco' 19 | 20 | apply from: 'gradle/integTest.gradle' 21 | apply from: 'gradle/benchmark.gradle' 22 | 23 | task('checkSourceFiles') << { 24 | def sourceSet = sourceSets.main.java 25 | for (File srcDir : sourceSet.srcDirs) { 26 | def tree = fileTree(srcDir).matching(sourceSet.filter) 27 | def packageDirs = new TreeSet() 28 | tree.visit { details -> 29 | if (!details.isDirectory()) { 30 | packageDirs.add(details.getFile().getParentFile()) 31 | } 32 | } 33 | for (File packageDir : packageDirs) { 34 | def packageInfoFile = new File(packageDir, 'package-info.java') 35 | assert packageInfoFile.exists(): packageInfoFile.absolutePath + ' is missing. All packages must have a package-info file' 36 | 37 | def sanityTestFile = new File(packageDir.absolutePath.replace('\\', '/').replace('src/main/java', 'src/test/groovy'), 'PackageSanityTest.groovy') 38 | assert sanityTestFile.exists(): sanityTestFile.absolutePath + ' is missing. All packages must have a Guava package sanity check' 39 | } 40 | } 41 | } 42 | compileJava.dependsOn checkSourceFiles 43 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DanielThomas/spring-boot-starter-netty/d1485e7d4c8fe047e46b43f105d18b1f2b521eeb/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Nov 24 15:05:30 GMT 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.2-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | /* 19 | * This settings file was auto generated by the Gradle buildInit task 20 | * by 'dthomas' at '07/08/14 18:11' with Gradle 2.0 21 | * 22 | * The settings file is used to specify which projects to include in your build. 23 | * In a single project build this file can be empty or even removed. 24 | * 25 | * Detailed information about configuring a multi-project build in Gradle can be found 26 | * in the user guide at http://gradle.org/docs/2.0/userguide/multi_project_builds.html 27 | */ 28 | 29 | /* 30 | // To declare projects as part of a multi-project build use the 'include' method 31 | include 'shared' 32 | include 'api' 33 | include 'services:webservice' 34 | */ 35 | 36 | rootProject.name = 'spring-boot-starter-netty' 37 | -------------------------------------------------------------------------------- /src/integTest/groovy/org/springframework/boot/context/embedded/netty/NettyEmbeddedServletContainerAutoConfigurationIntegrationTest.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty 19 | 20 | import org.springframework.boot.SpringApplication 21 | import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory 22 | import org.springframework.context.ConfigurableApplicationContext 23 | import spock.lang.Specification 24 | 25 | class NettyEmbeddedServletContainerAutoConfigurationIntegrationTest extends Specification { 26 | def 'application autoconfigures netty factory'() { 27 | given: 28 | def String[] args = [] 29 | ConfigurableApplicationContext context = SpringApplication.run(TestApplication, args) 30 | 31 | expect: 32 | context.getBean(EmbeddedServletContainerFactory) instanceof NettyEmbeddedServletContainerFactory 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/integTest/java/org/springframework/boot/context/embedded/netty/HttpContentInputStreamBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.buffer.Unpooled; 21 | import io.netty.channel.embedded.EmbeddedChannel; 22 | import io.netty.handler.codec.http.DefaultHttpContent; 23 | import org.openjdk.jmh.annotations.*; 24 | import org.openjdk.jmh.runner.Runner; 25 | import org.openjdk.jmh.runner.RunnerException; 26 | import org.openjdk.jmh.runner.options.Options; 27 | import org.openjdk.jmh.runner.options.OptionsBuilder; 28 | 29 | import java.io.IOException; 30 | import java.util.concurrent.TimeUnit; 31 | 32 | /** 33 | * Benchmarks for {@link HttpContentInputStream}. 34 | */ 35 | @State(Scope.Group) 36 | @OutputTimeUnit(TimeUnit.MILLISECONDS) 37 | public class HttpContentInputStreamBenchmark { 38 | private HttpContentInputStream stream; 39 | private byte[] b; 40 | 41 | @Param("8192") 42 | private int size; 43 | 44 | @Setup 45 | public void setup() { 46 | stream = new HttpContentInputStream(new EmbeddedChannel()); 47 | b = new byte[size]; 48 | } 49 | 50 | @Benchmark 51 | @Group("handler") 52 | public void addContent() { 53 | stream.addContent(new DefaultHttpContent(Unpooled.buffer(size))); 54 | } 55 | 56 | @Benchmark 57 | @Group("handler") 58 | public int read() throws IOException { 59 | return stream.read(b); 60 | } 61 | 62 | public static void main(String[] args) throws RunnerException { 63 | Options opt = new OptionsBuilder() 64 | .include(".*" + HttpContentInputStream.class.getSimpleName() + ".*") 65 | .warmupIterations(5) 66 | .measurementIterations(5) 67 | .forks(0) 68 | .build(); 69 | 70 | new Runner(opt).run(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/integTest/java/org/springframework/boot/context/embedded/netty/HttpResponseOutputStreamBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.handler.codec.http.DefaultHttpResponse; 22 | import io.netty.handler.codec.http.HttpResponse; 23 | import io.netty.handler.codec.http.HttpResponseStatus; 24 | import io.netty.handler.codec.http.HttpVersion; 25 | import org.openjdk.jmh.annotations.*; 26 | import org.openjdk.jmh.runner.Runner; 27 | import org.openjdk.jmh.runner.RunnerException; 28 | import org.openjdk.jmh.runner.options.Options; 29 | import org.openjdk.jmh.runner.options.OptionsBuilder; 30 | 31 | import java.io.IOException; 32 | import java.util.concurrent.TimeUnit; 33 | 34 | /** 35 | * Benchmarks for {@link HttpResponseOutputStream}. 36 | */ 37 | @State(Scope.Benchmark) 38 | @OutputTimeUnit(TimeUnit.NANOSECONDS) 39 | @BenchmarkMode(Mode.AverageTime) 40 | public class HttpResponseOutputStreamBenchmark { 41 | private HttpResponseOutputStream stream; 42 | private byte[] input; 43 | 44 | @Param({"1024", "2048", "4096", "8192", "16384", "32768"}) 45 | public int size; 46 | 47 | @Setup 48 | public void setup() { 49 | HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, false); 50 | ChannelHandlerContext ctx = new StubChannelHandlerContext(); 51 | NettyEmbeddedContext context = new NettyEmbeddedContext("/", Thread.currentThread().getContextClassLoader(), "Server"); 52 | NettyHttpServletResponse servletResponse = new NettyHttpServletResponse(ctx, context, httpResponse); 53 | stream = new HttpResponseOutputStream(ctx, servletResponse); 54 | input = new byte[size]; 55 | } 56 | 57 | @Benchmark 58 | public void writeByte() throws IOException { 59 | for (int i = 0; i < size; i++) { 60 | stream.write(0); 61 | } 62 | } 63 | 64 | @Benchmark 65 | public void writeBytes() throws IOException { 66 | stream.write(input); 67 | } 68 | 69 | public static void main(String[] args) throws RunnerException { 70 | Options opt = new OptionsBuilder() 71 | .include(".*" + HttpResponseOutputStreamBenchmark.class.getSimpleName() + ".*") 72 | .warmupIterations(5) 73 | .measurementIterations(5) 74 | .forks(1) 75 | .build(); 76 | 77 | new Runner(opt).run(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/integTest/java/org/springframework/boot/context/embedded/netty/NettyHttpServletResponseBenchmark.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.handler.codec.http.*; 21 | import org.openjdk.jmh.annotations.*; 22 | import org.openjdk.jmh.runner.Runner; 23 | import org.openjdk.jmh.runner.RunnerException; 24 | import org.openjdk.jmh.runner.options.Options; 25 | import org.openjdk.jmh.runner.options.OptionsBuilder; 26 | 27 | import java.util.concurrent.TimeUnit; 28 | 29 | /** 30 | * Sample benchmark to check that the Gradle configuration is working. 31 | */ 32 | @State(Scope.Benchmark) 33 | @BenchmarkMode(Mode.AverageTime) 34 | @OutputTimeUnit(TimeUnit.NANOSECONDS) 35 | public class NettyHttpServletResponseBenchmark { 36 | private NettyHttpServletResponse response; 37 | 38 | @Setup 39 | public void setup() { 40 | StubChannelHandlerContext cxt = new StubChannelHandlerContext(); 41 | HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, false); 42 | NettyEmbeddedContext context = new NettyEmbeddedContext("/", Thread.currentThread().getContextClassLoader(), "Server"); 43 | response = new NettyHttpServletResponse(cxt, context, httpResponse); 44 | } 45 | 46 | @Benchmark 47 | public void setContentType() { 48 | response.setContentType("text/html"); 49 | } 50 | 51 | @Benchmark 52 | public void setContentTypeHeader() { 53 | response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html"); 54 | } 55 | 56 | @Benchmark 57 | public CharSequence getFormattedDate() { 58 | return response.getFormattedDate(); 59 | } 60 | 61 | public static void main(String[] args) throws RunnerException { 62 | Options opt = new OptionsBuilder() 63 | .include(".*" + NettyHttpServletResponseBenchmark.class.getSimpleName() + ".*") 64 | .warmupIterations(5) 65 | .measurementIterations(5) 66 | .forks(1) 67 | .build(); 68 | 69 | new Runner(opt).run(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/integTest/java/org/springframework/boot/context/embedded/netty/StubChannelHandlerContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.buffer.ByteBufAllocator; 21 | import io.netty.channel.*; 22 | import io.netty.channel.embedded.EmbeddedChannel; 23 | import io.netty.util.Attribute; 24 | import io.netty.util.AttributeKey; 25 | import io.netty.util.ReferenceCounted; 26 | import io.netty.util.concurrent.EventExecutor; 27 | 28 | import java.net.SocketAddress; 29 | 30 | /** 31 | * A stub {@link ChannelHandlerContext} for benchmarks, as dynamic mocks introduce far too many side effects. 32 | */ 33 | public class StubChannelHandlerContext implements ChannelHandlerContext { 34 | private final Channel channel = new EmbeddedChannel(); 35 | 36 | @Override 37 | public ByteBufAllocator alloc() { 38 | return channel.alloc(); 39 | } 40 | 41 | @Override 42 | public ChannelFuture write(Object msg) { 43 | write(msg, null); 44 | return null; 45 | } 46 | 47 | @Override 48 | public ChannelFuture write(Object msg, ChannelPromise promise) { 49 | if (msg instanceof ReferenceCounted) { 50 | ((ReferenceCounted) msg).release(); 51 | } 52 | return null; 53 | } 54 | 55 | // Default implementations follow 56 | 57 | @Override 58 | public Channel channel() { 59 | return null; 60 | } 61 | 62 | @Override 63 | public EventExecutor executor() { 64 | return null; 65 | } 66 | 67 | @Override 68 | public String name() { 69 | return null; 70 | } 71 | 72 | @Override 73 | public ChannelHandler handler() { 74 | return null; 75 | } 76 | 77 | @Override 78 | public boolean isRemoved() { 79 | return false; 80 | } 81 | 82 | @Override 83 | public ChannelHandlerContext fireChannelRegistered() { 84 | return null; 85 | } 86 | 87 | @Override 88 | public ChannelHandlerContext fireChannelUnregistered() { 89 | return null; 90 | } 91 | 92 | @Override 93 | public ChannelHandlerContext fireChannelActive() { 94 | return null; 95 | } 96 | 97 | @Override 98 | public ChannelHandlerContext fireChannelInactive() { 99 | return null; 100 | } 101 | 102 | @Override 103 | public ChannelHandlerContext fireExceptionCaught(Throwable cause) { 104 | return null; 105 | } 106 | 107 | @Override 108 | public ChannelHandlerContext fireUserEventTriggered(Object event) { 109 | return null; 110 | } 111 | 112 | @Override 113 | public ChannelHandlerContext fireChannelRead(Object msg) { 114 | return null; 115 | } 116 | 117 | @Override 118 | public ChannelHandlerContext fireChannelReadComplete() { 119 | return null; 120 | } 121 | 122 | @Override 123 | public ChannelHandlerContext fireChannelWritabilityChanged() { 124 | return null; 125 | } 126 | 127 | @Override 128 | public ChannelFuture bind(SocketAddress localAddress) { 129 | return null; 130 | } 131 | 132 | @Override 133 | public ChannelFuture connect(SocketAddress remoteAddress) { 134 | return null; 135 | } 136 | 137 | @Override 138 | public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { 139 | return null; 140 | } 141 | 142 | @Override 143 | public ChannelFuture disconnect() { 144 | return null; 145 | } 146 | 147 | @Override 148 | public ChannelFuture close() { 149 | return null; 150 | } 151 | 152 | @Override 153 | public ChannelFuture deregister() { 154 | return null; 155 | } 156 | 157 | @Override 158 | public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { 159 | return null; 160 | } 161 | 162 | @Override 163 | public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { 164 | return null; 165 | } 166 | 167 | @Override 168 | public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { 169 | return null; 170 | } 171 | 172 | @Override 173 | public ChannelFuture disconnect(ChannelPromise promise) { 174 | return null; 175 | } 176 | 177 | @Override 178 | public ChannelFuture close(ChannelPromise promise) { 179 | return null; 180 | } 181 | 182 | @Override 183 | public ChannelFuture deregister(ChannelPromise promise) { 184 | return null; 185 | } 186 | 187 | @Override 188 | public ChannelHandlerContext read() { 189 | return null; 190 | } 191 | 192 | @Override 193 | public ChannelHandlerContext flush() { 194 | return null; 195 | } 196 | 197 | @Override 198 | public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { 199 | return null; 200 | } 201 | 202 | @Override 203 | public ChannelFuture writeAndFlush(Object msg) { 204 | return null; 205 | } 206 | 207 | @Override 208 | public ChannelPipeline pipeline() { 209 | return null; 210 | } 211 | 212 | @Override 213 | public ChannelPromise newPromise() { 214 | return null; 215 | } 216 | 217 | @Override 218 | public ChannelProgressivePromise newProgressivePromise() { 219 | return null; 220 | } 221 | 222 | @Override 223 | public ChannelFuture newSucceededFuture() { 224 | return null; 225 | } 226 | 227 | @Override 228 | public ChannelFuture newFailedFuture(Throwable cause) { 229 | return null; 230 | } 231 | 232 | @Override 233 | public ChannelPromise voidPromise() { 234 | return null; 235 | } 236 | 237 | @Override 238 | public Attribute attr(AttributeKey key) { 239 | return null; 240 | } 241 | 242 | @Override 243 | public boolean hasAttr(AttributeKey key) { 244 | return false; 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /src/integTest/java/org/springframework/boot/context/embedded/netty/TestApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import org.springframework.boot.SpringApplication; 21 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 22 | import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; 23 | import org.springframework.boot.context.embedded.ServletRegistrationBean; 24 | import org.springframework.context.annotation.Bean; 25 | import org.springframework.context.annotation.ComponentScan; 26 | import org.springframework.stereotype.Controller; 27 | import org.springframework.web.bind.annotation.RequestMapping; 28 | import org.springframework.web.bind.annotation.RequestMethod; 29 | import org.springframework.web.bind.annotation.ResponseBody; 30 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 31 | 32 | import javax.servlet.ServletException; 33 | import javax.servlet.ServletInputStream; 34 | import javax.servlet.http.HttpServlet; 35 | import javax.servlet.http.HttpServletRequest; 36 | import javax.servlet.http.HttpServletResponse; 37 | import java.io.IOException; 38 | import java.util.concurrent.Callable; 39 | 40 | /** 41 | * A {@link org.springframework.boot.SpringApplication} harness for integration tests. 42 | *

43 | * Implemented in Java to avoid currency issues caused by repeated annotation scanning of Groovy controllers. 44 | */ 45 | @Controller 46 | @EnableAutoConfiguration(exclude = WebMvcAutoConfiguration.class) 47 | @ComponentScan 48 | @EnableWebMvc 49 | class TestApplication { 50 | private static final String MESSAGE = "Hello, World!"; 51 | private static final Callable MESSAGE_CALLABLE = new Callable() { 52 | @Override 53 | public String call() throws Exception { 54 | return MESSAGE; 55 | } 56 | }; 57 | 58 | @RequestMapping(value = "/plaintext", produces = "text/plain") 59 | @ResponseBody 60 | public String plaintext() { 61 | return MESSAGE; 62 | } 63 | 64 | @RequestMapping(value = "/async", produces = "text/plain") 65 | @ResponseBody 66 | public Callable async() { 67 | return MESSAGE_CALLABLE; 68 | } 69 | 70 | @RequestMapping(value = "/json", produces = "application/json") 71 | @ResponseBody 72 | public Message json() { 73 | return new Message(MESSAGE); 74 | } 75 | 76 | @RequestMapping(value = "/upload", method = RequestMethod.POST) 77 | @ResponseBody 78 | public String upload(HttpServletRequest request) throws IOException { 79 | ServletInputStream inputStream = request.getInputStream(); 80 | int total = 0; 81 | while (true) { 82 | byte[] bytes = new byte[8192]; 83 | int read = inputStream.read(bytes); 84 | if (read == -1) { 85 | break; 86 | } 87 | total += read; 88 | } 89 | return "Total bytes received: " + total; 90 | } 91 | 92 | @RequestMapping("/sleepy") 93 | @ResponseBody 94 | public String sleepy() throws InterruptedException { 95 | int millis = 500; 96 | Thread.sleep(millis); 97 | return "Yawn! I slept for " + millis + "ms"; 98 | } 99 | 100 | @Bean 101 | public ServletRegistrationBean nullServletRegistration() { 102 | return new ServletRegistrationBean(new NullHttpServlet(), "/null"); 103 | } 104 | 105 | public static void main(String[] args) { 106 | SpringApplication.run(TestApplication.class, args); 107 | } 108 | 109 | private static class Message { 110 | private final String message; 111 | 112 | public Message(String message) { 113 | this.message = message; 114 | } 115 | 116 | public String getMessage() { 117 | return message; 118 | } 119 | } 120 | 121 | private class NullHttpServlet extends HttpServlet { 122 | @Override 123 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/integTest/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/AbstractNettyRegistration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import javax.servlet.FilterConfig; 21 | import javax.servlet.Registration; 22 | import javax.servlet.ServletConfig; 23 | import javax.servlet.ServletContext; 24 | import java.util.Collections; 25 | import java.util.Enumeration; 26 | import java.util.Map; 27 | import java.util.Set; 28 | 29 | import static com.google.common.base.Preconditions.checkArgument; 30 | import static com.google.common.base.Preconditions.checkNotNull; 31 | 32 | /** 33 | * Abstract class for those classes implementing {@link javax.servlet.Registration} classes and 34 | * {@link ServletConfig}/{@link FilterConfig}. 35 | * 36 | * @author Danny Thomas 37 | */ 38 | class AbstractNettyRegistration implements Registration, Registration.Dynamic, ServletConfig, FilterConfig { 39 | private final String name; 40 | private final String className; 41 | private final NettyEmbeddedContext context; 42 | protected boolean asyncSupported; 43 | 44 | protected AbstractNettyRegistration(String name, String className, NettyEmbeddedContext context) { 45 | this.name = checkNotNull(name); 46 | this.className = checkNotNull(className); 47 | this.context = checkNotNull(context); 48 | } 49 | 50 | @Override 51 | public void setAsyncSupported(boolean isAsyncSupported) { 52 | asyncSupported = isAsyncSupported; 53 | } 54 | 55 | @Override 56 | public String getName() { 57 | return name; 58 | } 59 | 60 | @Override 61 | public String getClassName() { 62 | return className; 63 | } 64 | 65 | @Override 66 | public boolean setInitParameter(String name, String value) { 67 | checkArgument(name != null, "name may not be null"); 68 | checkArgument(value != null, "value may not be null"); 69 | return false; 70 | } 71 | 72 | @Override 73 | public String getFilterName() { 74 | return name; 75 | } 76 | 77 | @Override 78 | public String getServletName() { 79 | return name; 80 | } 81 | 82 | @Override 83 | public ServletContext getServletContext() { 84 | return context; 85 | } 86 | 87 | protected NettyEmbeddedContext getNettyContext() { 88 | return context; 89 | } 90 | 91 | @Override 92 | public String getInitParameter(String name) { 93 | return null; 94 | } 95 | 96 | @Override 97 | public Enumeration getInitParameterNames() { 98 | return Collections.emptyEnumeration(); 99 | } 100 | 101 | @Override 102 | public Set setInitParameters(Map initParameters) { 103 | return Collections.emptySet(); 104 | } 105 | 106 | @Override 107 | public Map getInitParameters() { 108 | return Collections.emptyMap(); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/HttpContentInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import com.google.common.primitives.Ints; 21 | import io.netty.buffer.ByteBuf; 22 | import io.netty.channel.Channel; 23 | import io.netty.handler.codec.http.HttpContent; 24 | import io.netty.handler.codec.http.LastHttpContent; 25 | 26 | import javax.servlet.ReadListener; 27 | import javax.servlet.ServletInputStream; 28 | import java.io.IOException; 29 | import java.util.Queue; 30 | import java.util.concurrent.BlockingQueue; 31 | import java.util.concurrent.LinkedBlockingQueue; 32 | import java.util.concurrent.TimeUnit; 33 | import java.util.concurrent.atomic.AtomicBoolean; 34 | 35 | import static com.google.common.base.Preconditions.checkNotNull; 36 | 37 | /** 38 | * A {@link javax.servlet.ServletInputStream} that allows reading from {@link Queue} of {@link HttpContent}, adapting 39 | * Netty HTTP codec POJOs into a stream readable by servlets. 40 | * 41 | * @author Danny Thomas 42 | */ 43 | class HttpContentInputStream extends ServletInputStream { 44 | private final Channel channel; 45 | private AtomicBoolean closed; 46 | private final BlockingQueue queue; 47 | private HttpContent current; 48 | private ReadListener readListener; 49 | 50 | HttpContentInputStream(Channel channel) { 51 | this.channel = checkNotNull(channel); 52 | this.closed = new AtomicBoolean(); 53 | queue = new LinkedBlockingQueue<>(); 54 | } 55 | 56 | public void addContent(HttpContent httpContent) { 57 | checkNotClosed(); 58 | queue.offer(httpContent.retain()); 59 | // TODO limit the number of queued inputs, stop handler from reading from channel 60 | } 61 | 62 | @Override 63 | public int readLine(byte[] b, int off, int len) throws IOException { 64 | checkNotNull(b); 65 | // TODO use ByteBuf native approach, i.e. bytesBefore, ByteBufProcessor 66 | return super.readLine(b, off, len); 67 | } 68 | 69 | @Override 70 | public boolean isFinished() { 71 | checkNotClosed(); 72 | return isLastContent() && current.content().readableBytes() == 0; 73 | } 74 | 75 | private boolean isLastContent() { 76 | return current instanceof LastHttpContent; 77 | } 78 | 79 | @Override 80 | public boolean isReady() { 81 | checkNotClosed(); 82 | return (current != null && current.content().readableBytes() > 0) || !queue.isEmpty(); 83 | } 84 | 85 | @Override 86 | public void setReadListener(ReadListener readListener) { 87 | checkNotClosed(); 88 | checkNotNull(readListener); 89 | this.readListener = readListener; 90 | } 91 | 92 | @Override 93 | public long skip(long n) throws IOException { 94 | checkNotClosed(); 95 | // TODO implement skip that doesn't read bytes 96 | return readContent(Ints.checkedCast(n)).readableBytes(); 97 | } 98 | 99 | @Override 100 | public int available() throws IOException { 101 | return null == current ? 0 : current.content().readableBytes(); 102 | } 103 | 104 | @Override 105 | public void close() throws IOException { 106 | if (closed.compareAndSet(false, true)) { 107 | // FIXME release the non-written HttpContents? 108 | queue.clear(); 109 | current = null; 110 | } 111 | } 112 | 113 | @Override 114 | public int read(byte[] b, int off, int len) throws IOException { 115 | checkNotNull(b); 116 | if (0 == len) { 117 | return 0; 118 | } 119 | poll(); 120 | if (isFinished()) { 121 | return -1; 122 | } 123 | ByteBuf byteBuf = readContent(len); 124 | int readableBytes = byteBuf.readableBytes(); 125 | byteBuf.readBytes(b, off, readableBytes); 126 | return readableBytes - byteBuf.readableBytes(); 127 | } 128 | 129 | @Override 130 | public int read() throws IOException { 131 | poll(); 132 | if (isFinished()) { 133 | return -1; 134 | } 135 | return readContent(1).getByte(0); 136 | } 137 | 138 | private ByteBuf readContent(int length) throws IOException { 139 | ByteBuf content = current.content(); 140 | if (length < content.readableBytes()) { 141 | return content.readSlice(length); 142 | } else { 143 | return content; 144 | } 145 | } 146 | 147 | private void poll() throws IOException { 148 | checkNotClosed(); 149 | if (null == current || current.content().readableBytes() == 0) { 150 | boolean blocking = null == readListener; 151 | while (!isLastContent()) { 152 | try { 153 | // FIXME add appropriate timeout value 154 | current = queue.poll(0, TimeUnit.NANOSECONDS); 155 | } catch (InterruptedException ignored) { 156 | } 157 | if (current != null || !blocking) { 158 | break; 159 | } 160 | if (!channel.isActive()) { 161 | throw new IOException("Channel is not active"); 162 | } 163 | } 164 | } 165 | } 166 | 167 | private void checkNotClosed() { 168 | if (closed.get()) { 169 | throw new IllegalStateException("Stream is closed"); 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/HttpResponseOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.buffer.ByteBuf; 21 | import io.netty.buffer.Unpooled; 22 | import io.netty.channel.ChannelFuture; 23 | import io.netty.channel.ChannelFutureListener; 24 | import io.netty.channel.ChannelHandlerContext; 25 | import io.netty.handler.codec.http.DefaultLastHttpContent; 26 | import io.netty.handler.codec.http.HttpHeaders; 27 | import io.netty.handler.codec.http.HttpResponse; 28 | 29 | import javax.servlet.ServletOutputStream; 30 | import javax.servlet.WriteListener; 31 | import java.io.IOException; 32 | 33 | import static com.google.common.base.Preconditions.checkNotNull; 34 | import static com.google.common.base.Preconditions.checkState; 35 | 36 | /** 37 | * A buffered {@link ServletOutputStream}, that writes Netty HTTP codec POJOs to the associated 38 | * {@link ChannelHandlerContext}. 39 | * 40 | * @author Danny Thomas 41 | */ 42 | class HttpResponseOutputStream extends ServletOutputStream { 43 | private static final int DEFAULT_BUFFER_SIZE = 1024 * 8; 44 | 45 | private final ChannelHandlerContext ctx; 46 | private final NettyHttpServletResponse servletResponse; 47 | private byte[] buf; 48 | private int count; 49 | private boolean closed; 50 | private WriteListener writeListener; 51 | 52 | HttpResponseOutputStream(ChannelHandlerContext ctx, NettyHttpServletResponse servletResponse) { 53 | this.ctx = ctx; 54 | this.servletResponse = servletResponse; 55 | this.buf = new byte[DEFAULT_BUFFER_SIZE]; 56 | } 57 | 58 | @Override 59 | public boolean isReady() { 60 | return true; // TODO implement 61 | } 62 | 63 | @Override 64 | public void setWriteListener(WriteListener writeListener) { 65 | checkNotNull(writeListener); 66 | // TODO ISE when called more than once 67 | // TODO ISE when associated request is not async 68 | } 69 | 70 | @Override 71 | public void write(byte[] b, int off, int len) throws IOException { 72 | if (len > count) { 73 | flushBuffer(); 74 | ByteBuf content = ctx.alloc().buffer(len); 75 | content.writeBytes(b, off, len); 76 | writeContent(content, false); 77 | return; 78 | } 79 | writeBufferIfNeeded(len); 80 | System.arraycopy(b, off, buf, count, len); 81 | count += len; 82 | } 83 | 84 | @Override 85 | public void write(int b) throws IOException { 86 | writeBufferIfNeeded(1); 87 | buf[count++] = (byte) b; 88 | } 89 | 90 | private void writeBufferIfNeeded(int len) throws IOException { 91 | if (len > buf.length - count) { 92 | flushBuffer(); 93 | } 94 | } 95 | 96 | @Override 97 | public void flush() throws IOException { 98 | flushBuffer(); 99 | } 100 | 101 | private void flushBuffer() { 102 | flushBuffer(false); 103 | } 104 | 105 | private void flushBuffer(boolean lastContent) { 106 | if (count > 0) { 107 | ByteBuf content = ctx.alloc().buffer(count); 108 | content.writeBytes(buf, 0, count); 109 | count = 0; 110 | writeContent(content, lastContent); 111 | } else if (lastContent) { 112 | writeContent(Unpooled.EMPTY_BUFFER, true); 113 | } 114 | } 115 | 116 | private void writeContent(ByteBuf content, boolean lastContent) { 117 | // TODO block if channel is not writable to avoid heap utilisation 118 | if (!servletResponse.isCommitted()) { 119 | writeResponse(lastContent); 120 | } 121 | if (content.readableBytes() > 0) { 122 | assert content.refCnt() == 1; 123 | ctx.write(content, ctx.voidPromise()); 124 | } 125 | if (lastContent) { 126 | HttpResponse nettyResponse = servletResponse.getNettyResponse(); 127 | ChannelFuture future = ctx.write(DefaultLastHttpContent.EMPTY_LAST_CONTENT); 128 | if (!HttpHeaders.isKeepAlive(nettyResponse)) { 129 | future.addListener(ChannelFutureListener.CLOSE); 130 | } 131 | } 132 | } 133 | 134 | private void writeResponse(boolean lastContent) { 135 | HttpResponse response = servletResponse.getNettyResponse(); 136 | // TODO implement exceptions required by http://tools.ietf.org/html/rfc2616#section-4.4 137 | if (!HttpHeaders.isContentLengthSet(response)) { 138 | if (lastContent) { 139 | HttpHeaders.setContentLength(response, count); 140 | } else { 141 | HttpHeaders.setTransferEncodingChunked(response); 142 | } 143 | } 144 | ctx.write(response, ctx.voidPromise()); 145 | } 146 | 147 | @Override 148 | public void close() throws IOException { 149 | if (closed) { 150 | return; 151 | } 152 | closed = true; 153 | try { 154 | flushBuffer(true); 155 | ctx.flush(); 156 | } finally { 157 | buf = null; 158 | } 159 | } 160 | 161 | void resetBuffer() { 162 | assert !servletResponse.isCommitted(); 163 | count = 0; 164 | } 165 | 166 | int getBufferSize() { 167 | return buf.length; 168 | } 169 | 170 | void setBufferSize(int size) { 171 | assert !servletResponse.isCommitted(); 172 | checkState(count == 0, "Response body content has been written"); 173 | buf = new byte[size]; 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyAsyncContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import com.google.common.collect.ImmutableList; 21 | import io.netty.channel.ChannelHandlerContext; 22 | 23 | import javax.servlet.*; 24 | import javax.servlet.http.HttpServletRequest; 25 | import java.io.IOException; 26 | import java.util.ArrayList; 27 | import java.util.List; 28 | 29 | /** 30 | * Netty {@link AsyncContext}. 31 | * 32 | * @author Danny Thomas 33 | */ 34 | class NettyAsyncContext implements AsyncContext { 35 | private ServletRequest servletRequest; 36 | private final ChannelHandlerContext ctx; 37 | private ServletResponse servletResponse; 38 | private boolean asyncStarted; 39 | private List listeners; 40 | 41 | NettyAsyncContext(ServletRequest servletRequest, ChannelHandlerContext ctx) { 42 | this.servletRequest = servletRequest; 43 | this.ctx = ctx; 44 | this.listeners = new ArrayList<>(); 45 | } 46 | 47 | AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) { 48 | this.servletRequest = servletRequest; 49 | this.servletResponse = servletResponse; 50 | asyncStarted = true; 51 | return this; 52 | } 53 | 54 | @Override 55 | public ServletRequest getRequest() { 56 | return servletRequest; 57 | } 58 | 59 | @Override 60 | public ServletResponse getResponse() { 61 | return servletResponse; 62 | } 63 | 64 | @Override 65 | public boolean hasOriginalRequestAndResponse() { 66 | return true; 67 | } 68 | 69 | @Override 70 | public void dispatch() { 71 | if (servletRequest instanceof HttpServletRequest) { 72 | HttpServletRequest request = (HttpServletRequest) servletRequest; 73 | String path = request.getServletPath(); 74 | String pathInfo = request.getPathInfo(); 75 | if (null != pathInfo) { 76 | path += pathInfo; 77 | } 78 | dispatch(path); 79 | } 80 | } 81 | 82 | @Override 83 | public void dispatch(String path) { 84 | dispatch(servletRequest.getServletContext(), path); 85 | } 86 | 87 | @Override 88 | public void dispatch(ServletContext context, String path) { 89 | final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; 90 | httpRequest.setAttribute(ASYNC_CONTEXT_PATH, httpRequest.getContextPath()); 91 | httpRequest.setAttribute(ASYNC_PATH_INFO, httpRequest.getPathInfo()); 92 | httpRequest.setAttribute(ASYNC_QUERY_STRING, httpRequest.getQueryString()); 93 | httpRequest.setAttribute(ASYNC_REQUEST_URI, httpRequest.getRequestURI()); 94 | httpRequest.setAttribute(ASYNC_SERVLET_PATH, httpRequest.getServletPath()); 95 | final NettyRequestDispatcher dispatcher = (NettyRequestDispatcher) context.getRequestDispatcher(path); 96 | ctx.executor().submit(new Runnable() { 97 | @Override 98 | public void run() { 99 | try { 100 | dispatcher.dispatch(httpRequest, servletResponse); 101 | // TODO is this right? 102 | for (AsyncListener listener : ImmutableList.copyOf(listeners)) { 103 | listener.onComplete(new AsyncEvent(NettyAsyncContext.this)); 104 | } 105 | } catch (ServletException | IOException e) { 106 | // TODO notify listeners 107 | e.printStackTrace(); 108 | } 109 | } 110 | }); 111 | } 112 | 113 | @Override 114 | public void complete() { 115 | try { 116 | servletResponse.getOutputStream().close(); 117 | } catch (IOException e) { 118 | // TODO notify listeners 119 | e.printStackTrace(); 120 | } 121 | } 122 | 123 | @Override 124 | public void start(Runnable run) { 125 | ctx.executor().submit(run, Object.class); 126 | } 127 | 128 | @Override 129 | public void addListener(AsyncListener listener) { 130 | listeners.add(listener); 131 | } 132 | 133 | @Override 134 | public void addListener(AsyncListener listener, ServletRequest servletRequest, ServletResponse servletResponse) { 135 | 136 | } 137 | 138 | @Override 139 | public T createListener(Class clazz) throws ServletException { 140 | return null; 141 | } 142 | 143 | @Override 144 | public void setTimeout(long timeout) { 145 | 146 | } 147 | 148 | @Override 149 | public long getTimeout() { 150 | return 0; 151 | } 152 | 153 | public boolean isAsyncStarted() { 154 | return asyncStarted; 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyEmbeddedContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import com.google.common.collect.ImmutableMap; 21 | import io.netty.util.AsciiString; 22 | import org.apache.commons.logging.Log; 23 | import org.apache.commons.logging.LogFactory; 24 | 25 | import javax.servlet.*; 26 | import javax.servlet.descriptor.JspConfigDescriptor; 27 | import java.io.InputStream; 28 | import java.net.MalformedURLException; 29 | import java.net.URL; 30 | import java.util.*; 31 | 32 | import static com.google.common.base.Preconditions.checkNotNull; 33 | import static com.google.common.base.Preconditions.checkState; 34 | 35 | /** 36 | * Netty servlet bridge {@link ServletContext} implementation. 37 | */ 38 | class NettyEmbeddedContext implements ServletContext { 39 | private final Log logger = LogFactory.getLog(NettyEmbeddedContext.class); 40 | 41 | private final String contextPath; 42 | private final ClassLoader classLoader; 43 | private final Map servlets = new HashMap<>(); 44 | private final Map servletMappings = new HashMap<>(); 45 | private final Map filters = new HashMap<>(); 46 | private final AsciiString serverInfo; 47 | private volatile boolean initialised; 48 | 49 | NettyEmbeddedContext(String contextPath, ClassLoader classLoader, String serverInfo) { 50 | this.contextPath = contextPath; 51 | this.classLoader = classLoader; 52 | this.serverInfo = new AsciiString(serverInfo); 53 | } 54 | 55 | public void setInitialised(boolean initialised) { 56 | this.initialised = initialised; 57 | } 58 | 59 | public boolean isInitialised() { 60 | return initialised; 61 | } 62 | 63 | public void checkNotInitialised() { 64 | checkState(!isInitialised(), "This method may not be called after the context has been initialised"); 65 | } 66 | 67 | public void addServletMapping(String urlPattern, String name) { 68 | checkNotInitialised(); 69 | servletMappings.put(urlPattern, checkNotNull(name)); 70 | } 71 | 72 | public void addFilterMapping(EnumSet dispatcherTypes, boolean isMatchAfter, String urlPattern) { 73 | checkNotInitialised(); 74 | // TODO 75 | } 76 | 77 | @Override 78 | public ServletContext getContext(String uripath) { 79 | return null; 80 | } 81 | 82 | @Override 83 | public String getContextPath() { 84 | return contextPath; 85 | } 86 | 87 | @Override 88 | public int getMajorVersion() { 89 | return 0; 90 | } 91 | 92 | @Override 93 | public int getMinorVersion() { 94 | return 0; 95 | } 96 | 97 | @Override 98 | public int getEffectiveMajorVersion() { 99 | return 0; 100 | } 101 | 102 | @Override 103 | public int getEffectiveMinorVersion() { 104 | return 0; 105 | } 106 | 107 | @Override 108 | public String getMimeType(String file) { 109 | return null; 110 | } 111 | 112 | @Override 113 | public Set getResourcePaths(String path) { 114 | return null; 115 | } 116 | 117 | @Override 118 | public URL getResource(String path) throws MalformedURLException { 119 | return null; 120 | } 121 | 122 | @Override 123 | public InputStream getResourceAsStream(String path) { 124 | return null; 125 | } 126 | 127 | @Override 128 | public RequestDispatcher getRequestDispatcher(String path) { 129 | // FIXME proper path matching 130 | String servletName = servletMappings.get(path); 131 | if (servletName == null) { 132 | servletName = servletMappings.get("/"); 133 | } 134 | Servlet servlet = null; 135 | try { 136 | servlet = null == servletName ? null : servlets.get(servletName).getServlet(); 137 | if (servlet == null) { 138 | return null; 139 | } 140 | // FIXME proper path matching 141 | List filters = new ArrayList<>(); 142 | for (NettyFilterRegistration registration : this.filters.values()) { 143 | filters.add(registration.getFilter()); 144 | } 145 | FilterChain filterChain = new SimpleFilterChain(servlet, filters); 146 | return new NettyRequestDispatcher(this, filterChain); 147 | } catch (ServletException e) { 148 | // TODO log exception 149 | return null; 150 | } 151 | } 152 | 153 | @Override 154 | public RequestDispatcher getNamedDispatcher(String name) { 155 | return null; 156 | } 157 | 158 | @Override 159 | public Servlet getServlet(String name) throws ServletException { 160 | return servlets.get(name).getServlet(); 161 | } 162 | 163 | @Override 164 | public Enumeration getServlets() { 165 | return Collections.emptyEnumeration(); 166 | } 167 | 168 | @Override 169 | public Enumeration getServletNames() { 170 | return Collections.emptyEnumeration(); 171 | } 172 | 173 | @Override 174 | public void log(String msg) { 175 | logger.info(msg); 176 | } 177 | 178 | @Override 179 | public void log(Exception exception, String msg) { 180 | logger.error(msg, exception); 181 | } 182 | 183 | @Override 184 | public void log(String message, Throwable throwable) { 185 | logger.error(message, throwable); 186 | } 187 | 188 | @Override 189 | public String getRealPath(String path) { 190 | return null; 191 | } 192 | 193 | @Override 194 | public String getServerInfo() { 195 | return serverInfo.toString(); 196 | } 197 | 198 | AsciiString getServerInfoAscii() { 199 | return serverInfo; 200 | } 201 | 202 | @Override 203 | public String getInitParameter(String name) { 204 | return null; 205 | } 206 | 207 | @Override 208 | public Enumeration getInitParameterNames() { 209 | return Collections.emptyEnumeration(); 210 | } 211 | 212 | @Override 213 | public boolean setInitParameter(String name, String value) { 214 | return false; 215 | } 216 | 217 | @Override 218 | public Object getAttribute(String name) { 219 | return null; 220 | } 221 | 222 | @Override 223 | public Enumeration getAttributeNames() { 224 | return Collections.emptyEnumeration(); 225 | } 226 | 227 | @Override 228 | public void setAttribute(String name, Object object) { 229 | 230 | } 231 | 232 | @Override 233 | public void removeAttribute(String name) { 234 | 235 | } 236 | 237 | @Override 238 | public String getServletContextName() { 239 | return null; 240 | } 241 | 242 | @Override 243 | public ServletRegistration.Dynamic addServlet(String servletName, String className) { 244 | return addServlet(servletName, className, null); 245 | } 246 | 247 | @Override 248 | public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) { 249 | return addServlet(servletName, servlet.getClass().getName(), servlet); 250 | } 251 | 252 | @Override 253 | public ServletRegistration.Dynamic addServlet(String servletName, Class servletClass) { 254 | return addServlet(servletName, servletClass.getName()); 255 | } 256 | 257 | private ServletRegistration.Dynamic addServlet(String servletName, String className, Servlet servlet) { 258 | NettyServletRegistration servletRegistration = new NettyServletRegistration(this, servletName, className, servlet); 259 | servlets.put(servletName, servletRegistration); 260 | return servletRegistration; 261 | } 262 | 263 | @Override 264 | public T createServlet(Class c) throws ServletException { 265 | return null; 266 | } 267 | 268 | @Override 269 | public ServletRegistration getServletRegistration(String servletName) { 270 | return null; 271 | } 272 | 273 | @Override 274 | public Map getServletRegistrations() { 275 | return null; 276 | } 277 | 278 | @Override 279 | public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, String className) { 280 | return addFilter(filterName, className, null); 281 | } 282 | 283 | @Override 284 | public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, Filter filter) { 285 | return addFilter(filterName, filter.getClass().getName(), filter); 286 | } 287 | 288 | private javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, String className, Filter filter) { 289 | NettyFilterRegistration filterRegistration = new NettyFilterRegistration(this, filterName, className, filter); 290 | filters.put(filterName, filterRegistration); 291 | return filterRegistration; 292 | } 293 | 294 | 295 | @Override 296 | public javax.servlet.FilterRegistration.Dynamic addFilter(String filterName, Class filterClass) { 297 | return addFilter(filterName, filterClass.getName()); 298 | } 299 | 300 | @Override 301 | public T createFilter(Class c) throws ServletException { 302 | return null; 303 | } 304 | 305 | @Override 306 | public javax.servlet.FilterRegistration getFilterRegistration(String filterName) { 307 | return filters.get(filterName); 308 | } 309 | 310 | @Override 311 | public Map getFilterRegistrations() { 312 | return ImmutableMap.copyOf(filters); 313 | } 314 | 315 | @Override 316 | public SessionCookieConfig getSessionCookieConfig() { 317 | return null; 318 | } 319 | 320 | @Override 321 | public void setSessionTrackingModes(Set sessionTrackingModes) throws IllegalStateException, IllegalArgumentException { 322 | 323 | } 324 | 325 | @Override 326 | public Set getDefaultSessionTrackingModes() { 327 | return null; 328 | } 329 | 330 | @Override 331 | public Set getEffectiveSessionTrackingModes() { 332 | return null; 333 | } 334 | 335 | @Override 336 | public void addListener(String className) { 337 | 338 | } 339 | 340 | @Override 341 | public void addListener(T t) { 342 | 343 | } 344 | 345 | @Override 346 | public void addListener(Class listenerClass) { 347 | 348 | } 349 | 350 | @Override 351 | public T createListener(Class c) throws ServletException { 352 | return null; 353 | } 354 | 355 | @Override 356 | public void declareRoles(String... roleNames) { 357 | 358 | } 359 | 360 | @Override 361 | public String getVirtualServerName() { 362 | return null; 363 | } 364 | 365 | @Override 366 | public ClassLoader getClassLoader() { 367 | return classLoader; 368 | } 369 | 370 | @Override 371 | public JspConfigDescriptor getJspConfigDescriptor() { 372 | return null; 373 | } 374 | } 375 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyEmbeddedServletContainer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import com.google.common.base.StandardSystemProperty; 21 | import io.netty.bootstrap.ServerBootstrap; 22 | import io.netty.channel.ChannelFuture; 23 | import io.netty.channel.ChannelOption; 24 | import io.netty.channel.EventLoopGroup; 25 | import io.netty.channel.epoll.EpollChannelOption; 26 | import io.netty.channel.epoll.EpollEventLoopGroup; 27 | import io.netty.channel.epoll.EpollServerSocketChannel; 28 | import io.netty.channel.nio.NioEventLoopGroup; 29 | import io.netty.channel.socket.nio.NioServerSocketChannel; 30 | import io.netty.util.concurrent.DefaultEventExecutorGroup; 31 | import org.apache.commons.logging.Log; 32 | import org.apache.commons.logging.LogFactory; 33 | import org.springframework.boot.context.embedded.EmbeddedServletContainer; 34 | import org.springframework.boot.context.embedded.EmbeddedServletContainerException; 35 | 36 | import java.net.InetSocketAddress; 37 | 38 | /** 39 | * An {@link EmbeddedServletContainer} used to control an embedded Netty instance, that bridges to 40 | * {@link javax.servlet.http.HttpServletRequest} and from {@link javax.servlet.http.HttpServletResponse} 41 | * to Netty HTTP codec {@link io.netty.handler.codec.http.HttpMessage}s. 42 | *

43 | * This is a minimal Servlet 3.1 implementation to provide for the opinionated embedded servlet container model for 44 | * Spring Boot, supporting a single context, runtime {@link javax.servlet.Registration} only, and no default or JSP 45 | * servlets. 46 | *

47 | * This class should be created using the {@link NettyEmbeddedServletContainerFactory}. 48 | * 49 | * @author Danny Thomas 50 | */ 51 | public class NettyEmbeddedServletContainer implements EmbeddedServletContainer { 52 | private final Log logger = LogFactory.getLog(getClass()); 53 | private final InetSocketAddress address; 54 | private final NettyEmbeddedContext context; 55 | 56 | private EventLoopGroup bossGroup; 57 | private EventLoopGroup workerGroup; 58 | private DefaultEventExecutorGroup servletExecutor; 59 | 60 | public NettyEmbeddedServletContainer(InetSocketAddress address, NettyEmbeddedContext context) { 61 | this.address = address; 62 | this.context = context; 63 | } 64 | 65 | @Override 66 | public void start() throws EmbeddedServletContainerException { 67 | ServerBootstrap b = new ServerBootstrap(); 68 | groups(b); 69 | servletExecutor = new DefaultEventExecutorGroup(50); 70 | b.childHandler(new NettyEmbeddedServletInitializer(servletExecutor, context)); 71 | 72 | // Don't yet need the complexity of lifecycle state, listeners etc, so tell the context it's initialised here 73 | context.setInitialised(true); 74 | 75 | ChannelFuture future = b.bind(address).awaitUninterruptibly(); 76 | //noinspection ThrowableResultOfMethodCallIgnored 77 | Throwable cause = future.cause(); 78 | if (null != cause) { 79 | throw new EmbeddedServletContainerException("Could not start Netty server", cause); 80 | } 81 | logger.info(context.getServerInfo() + " started on port: " + getPort()); 82 | } 83 | 84 | private void groups(ServerBootstrap b) { 85 | if (StandardSystemProperty.OS_NAME.value().equals("Linux")) { 86 | bossGroup = new EpollEventLoopGroup(1); 87 | workerGroup = new EpollEventLoopGroup(); 88 | b.channel(EpollServerSocketChannel.class) 89 | .group(bossGroup, workerGroup) 90 | .option(EpollChannelOption.TCP_CORK, true); 91 | } else { 92 | bossGroup = new NioEventLoopGroup(1); 93 | workerGroup = new NioEventLoopGroup(); 94 | b.channel(NioServerSocketChannel.class) 95 | .group(bossGroup, workerGroup); 96 | } 97 | b.option(ChannelOption.TCP_NODELAY, true) 98 | .option(ChannelOption.SO_REUSEADDR, true) 99 | .option(ChannelOption.SO_BACKLOG, 100); 100 | logger.info("Bootstrap configuration: " + b.toString()); 101 | } 102 | 103 | @Override 104 | public void stop() throws EmbeddedServletContainerException { 105 | try { 106 | if (null != bossGroup) { 107 | bossGroup.shutdownGracefully().await(); 108 | } 109 | if (null != workerGroup) { 110 | workerGroup.shutdownGracefully().await(); 111 | } 112 | if (null != servletExecutor) { 113 | servletExecutor.shutdownGracefully().await(); 114 | } 115 | } catch (InterruptedException e) { 116 | throw new EmbeddedServletContainerException("Container stop interrupted", e); 117 | } 118 | } 119 | 120 | @Override 121 | public int getPort() { 122 | return address.getPort(); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyEmbeddedServletContainerAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.bootstrap.Bootstrap; 21 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 22 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 23 | import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; 24 | import org.springframework.boot.autoconfigure.condition.SearchStrategy; 25 | import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration.EmbeddedServletContainerCustomizerBeanPostProcessorRegistrar; 26 | import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; 27 | import org.springframework.context.annotation.Bean; 28 | import org.springframework.context.annotation.Configuration; 29 | import org.springframework.context.annotation.Import; 30 | import org.springframework.core.Ordered; 31 | import org.springframework.core.annotation.Order; 32 | 33 | /** 34 | * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration Auto-configuration} for an embedded servlet containers. 35 | * 36 | * @author Danny Thomas 37 | */ 38 | @Order(Ordered.HIGHEST_PRECEDENCE) 39 | @Configuration 40 | @ConditionalOnWebApplication 41 | @Import(EmbeddedServletContainerCustomizerBeanPostProcessorRegistrar.class) 42 | public class NettyEmbeddedServletContainerAutoConfiguration { 43 | @Configuration 44 | @ConditionalOnClass({Bootstrap.class}) 45 | @ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT) 46 | public static class EmbeddedNetty { 47 | @Bean 48 | public NettyEmbeddedServletContainerFactory nettyEmbeddedServletContainerFactory() { 49 | return new NettyEmbeddedServletContainerFactory(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyEmbeddedServletContainerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.bootstrap.Bootstrap; 21 | import org.springframework.boot.context.embedded.AbstractEmbeddedServletContainerFactory; 22 | import org.springframework.boot.context.embedded.EmbeddedServletContainer; 23 | import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; 24 | import org.springframework.boot.context.embedded.ServletContextInitializer; 25 | import org.springframework.context.ResourceLoaderAware; 26 | import org.springframework.core.io.ResourceLoader; 27 | import org.springframework.util.ClassUtils; 28 | 29 | import javax.servlet.ServletException; 30 | import java.net.InetSocketAddress; 31 | import java.net.URL; 32 | import java.net.URLClassLoader; 33 | import java.util.Random; 34 | 35 | /** 36 | * An {@link EmbeddedServletContainerFactory} that can be used to create {@link NettyEmbeddedServletContainer}s. 37 | * 38 | * @author Danny Thomas 39 | */ 40 | public class NettyEmbeddedServletContainerFactory extends AbstractEmbeddedServletContainerFactory implements ResourceLoaderAware { 41 | public static final String SERVER_INFO = "netty/servlet"; 42 | private ResourceLoader resourceLoader; 43 | 44 | @Override 45 | public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) { 46 | ClassLoader parentClassLoader = resourceLoader != null ? resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader(); 47 | Package nettyPackage = Bootstrap.class.getPackage(); 48 | String title = nettyPackage.getImplementationTitle(); 49 | String version = nettyPackage.getImplementationVersion(); 50 | logger.info("Running with " + title + " " + version); 51 | NettyEmbeddedContext context = new NettyEmbeddedContext(getContextPath(), new URLClassLoader(new URL[]{}, parentClassLoader), SERVER_INFO); 52 | if (isRegisterDefaultServlet()) { 53 | logger.warn("This container does not support a default servlet"); 54 | } 55 | if (isRegisterJspServlet()) { 56 | logger.warn("This container does not support a JSP servlet"); 57 | } 58 | for (ServletContextInitializer initializer : initializers) { 59 | try { 60 | initializer.onStartup(context); 61 | } catch (ServletException e) { 62 | throw new RuntimeException(e); 63 | } 64 | } 65 | int port = getPort() > 0 ? getPort() : new Random().nextInt(65535 - 1024) + 1024; 66 | InetSocketAddress address = new InetSocketAddress(port); 67 | logger.info("Server initialized with port: " + port); 68 | return new NettyEmbeddedServletContainer(address, context); 69 | } 70 | 71 | @Override 72 | public void setResourceLoader(ResourceLoader resourceLoader) { 73 | this.resourceLoader = resourceLoader; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyEmbeddedServletInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.channel.ChannelInitializer; 21 | import io.netty.channel.ChannelPipeline; 22 | import io.netty.channel.socket.SocketChannel; 23 | import io.netty.handler.codec.http.HttpServerCodec; 24 | import io.netty.util.concurrent.EventExecutorGroup; 25 | 26 | import static com.google.common.base.Preconditions.checkNotNull; 27 | 28 | /** 29 | * {@link ChannelInitializer} for {@link org.springframework.boot.context.embedded.netty.NettyEmbeddedServletContainer}. 30 | * 31 | * @author Danny Thomas 32 | */ 33 | class NettyEmbeddedServletInitializer extends ChannelInitializer { 34 | private final EventExecutorGroup servletExecutor; 35 | private final RequestDispatcherHandler requestDispatcherHandler; 36 | private final NettyEmbeddedContext servletContext; 37 | 38 | NettyEmbeddedServletInitializer(EventExecutorGroup servletExecutor, NettyEmbeddedContext servletContext) { 39 | this.servletContext = servletContext; 40 | this.servletExecutor = checkNotNull(servletExecutor); 41 | requestDispatcherHandler = new RequestDispatcherHandler(servletContext); 42 | } 43 | 44 | @Override 45 | protected void initChannel(SocketChannel ch) throws Exception { 46 | ChannelPipeline p = ch.pipeline(); 47 | p.addLast("codec", new HttpServerCodec(4096, 8192, 8192, false)); 48 | p.addLast("servletInput", new ServletContentHandler(servletContext)); 49 | p.addLast(servletExecutor, "filterChain", requestDispatcherHandler); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyFilterRegistration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import javax.servlet.DispatcherType; 21 | import javax.servlet.Filter; 22 | import javax.servlet.FilterRegistration; 23 | import javax.servlet.ServletException; 24 | import java.util.Collection; 25 | import java.util.EnumSet; 26 | 27 | /** 28 | * A {@link org.springframework.boot.context.embedded.netty.NettyEmbeddedContext} {@link javax.servlet.FilterRegistration}. 29 | * 30 | * @author Danny Thomas 31 | */ 32 | class NettyFilterRegistration extends AbstractNettyRegistration implements FilterRegistration.Dynamic { 33 | private volatile boolean initialised; 34 | private Filter filter; 35 | 36 | NettyFilterRegistration(NettyEmbeddedContext context, String filterName, String className, Filter filter) { 37 | super(filterName, className, context); 38 | this.filter = filter; 39 | } 40 | 41 | public Filter getFilter() throws ServletException { 42 | if (!initialised) { 43 | synchronized (this) { 44 | if (!initialised) { 45 | if (null == filter) { 46 | try { 47 | filter = (Filter) Class.forName(getClassName()).newInstance(); 48 | } catch (Exception e) { 49 | throw new ServletException(e); 50 | } 51 | } 52 | filter.init(this); 53 | initialised = true; 54 | } 55 | } 56 | } 57 | return filter; 58 | } 59 | 60 | @Override 61 | public void addMappingForServletNames(EnumSet dispatcherTypes, boolean isMatchAfter, String... servletNames) { 62 | 63 | } 64 | 65 | @Override 66 | public Collection getServletNameMappings() { 67 | return null; 68 | } 69 | 70 | @Override 71 | public void addMappingForUrlPatterns(EnumSet dispatcherTypes, boolean isMatchAfter, String... urlPatterns) { 72 | NettyEmbeddedContext context = getNettyContext(); 73 | for (String urlPattern : urlPatterns) { 74 | context.addFilterMapping(dispatcherTypes, isMatchAfter, urlPattern); 75 | } 76 | } 77 | 78 | @Override 79 | public Collection getUrlPatternMappings() { 80 | return null; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyHttpServletRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.handler.codec.http.HttpRequest; 22 | 23 | import javax.servlet.*; 24 | import javax.servlet.http.*; 25 | import java.io.BufferedReader; 26 | import java.io.IOException; 27 | import java.io.UnsupportedEncodingException; 28 | import java.security.Principal; 29 | import java.util.*; 30 | 31 | /** 32 | * {@link HttpServletRequest} wrapper for Netty's {@link HttpRequest}. 33 | * 34 | * @author Danny Thomas 35 | */ 36 | class NettyHttpServletRequest implements HttpServletRequest { 37 | public static final String DISPATCHER_TYPE = NettyRequestDispatcher.class.getName() + ".DISPATCHER_TYPE"; 38 | 39 | private final ChannelHandlerContext ctx; 40 | private final NettyEmbeddedContext servletContext; 41 | private final HttpRequest request; 42 | private final ServletInputStream inputStream; 43 | private final Map attributes; 44 | 45 | private boolean asyncSupported = true; 46 | private NettyAsyncContext asyncContext; 47 | private HttpServletResponse servletResponse; 48 | 49 | NettyHttpServletRequest(ChannelHandlerContext ctx, NettyEmbeddedContext servletContext, HttpRequest request, HttpServletResponse servletResponse, ServletInputStream inputStream) { 50 | this.ctx = ctx; 51 | this.servletContext = servletContext; 52 | this.request = request; 53 | this.servletResponse = servletResponse; 54 | this.inputStream = inputStream; 55 | this.attributes = new HashMap<>(); 56 | } 57 | 58 | HttpRequest getNettyRequest() { 59 | return request; 60 | } 61 | 62 | @Override 63 | public String getAuthType() { 64 | return null; 65 | } 66 | 67 | @Override 68 | public Cookie[] getCookies() { 69 | return new Cookie[0]; 70 | } 71 | 72 | @Override 73 | public long getDateHeader(String name) { 74 | return 0; 75 | } 76 | 77 | @Override 78 | public String getHeader(String name) { 79 | return null; 80 | } 81 | 82 | @Override 83 | public Enumeration getHeaders(String name) { 84 | return Collections.emptyEnumeration(); 85 | } 86 | 87 | @Override 88 | public Enumeration getHeaderNames() { 89 | return Collections.emptyEnumeration(); 90 | } 91 | 92 | @Override 93 | public int getIntHeader(String name) { 94 | return 0; 95 | } 96 | 97 | @Override 98 | public String getMethod() { 99 | return request.method().name(); 100 | } 101 | 102 | @Override 103 | public String getPathInfo() { 104 | return null; 105 | } 106 | 107 | @Override 108 | public String getPathTranslated() { 109 | return null; 110 | } 111 | 112 | @Override 113 | public String getContextPath() { 114 | String requestURI = getRequestURI(); 115 | // FIXME implement properly 116 | return "/".equals(requestURI) ? "" : requestURI; 117 | } 118 | 119 | @Override 120 | public String getQueryString() { 121 | return null; 122 | } 123 | 124 | @Override 125 | public String getRemoteUser() { 126 | return null; 127 | } 128 | 129 | @Override 130 | public boolean isUserInRole(String role) { 131 | return false; 132 | } 133 | 134 | @Override 135 | public Principal getUserPrincipal() { 136 | return null; 137 | } 138 | 139 | @Override 140 | public String getRequestedSessionId() { 141 | return null; 142 | } 143 | 144 | @Override 145 | public String getRequestURI() { 146 | return request.uri(); 147 | } 148 | 149 | @Override 150 | public StringBuffer getRequestURL() { 151 | return null; 152 | } 153 | 154 | @Override 155 | public String getServletPath() { 156 | return getRequestURI(); 157 | } 158 | 159 | @Override 160 | public HttpSession getSession(boolean create) { 161 | return null; 162 | } 163 | 164 | @Override 165 | public HttpSession getSession() { 166 | return null; 167 | } 168 | 169 | @Override 170 | public String changeSessionId() { 171 | return null; 172 | } 173 | 174 | @Override 175 | public boolean isRequestedSessionIdValid() { 176 | return false; 177 | } 178 | 179 | @Override 180 | public boolean isRequestedSessionIdFromCookie() { 181 | return false; 182 | } 183 | 184 | @Override 185 | public boolean isRequestedSessionIdFromURL() { 186 | return false; 187 | } 188 | 189 | @Override 190 | public boolean isRequestedSessionIdFromUrl() { 191 | return false; 192 | } 193 | 194 | @Override 195 | public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { 196 | return false; 197 | } 198 | 199 | @Override 200 | public void login(String username, String password) throws ServletException { 201 | 202 | } 203 | 204 | @Override 205 | public void logout() throws ServletException { 206 | 207 | } 208 | 209 | @Override 210 | public Collection getParts() throws IOException, IllegalStateException, ServletException { 211 | return null; 212 | } 213 | 214 | @Override 215 | public Part getPart(String name) throws IOException, IllegalStateException, ServletException { 216 | return null; 217 | } 218 | 219 | @Override 220 | public T upgrade(Class handlerClass) throws IOException, ServletException { 221 | return null; 222 | } 223 | 224 | @Override 225 | public Object getAttribute(String name) { 226 | synchronized (attributes) { 227 | return attributes.get(name); 228 | } 229 | } 230 | 231 | @Override 232 | public Enumeration getAttributeNames() { 233 | synchronized (attributes) { 234 | return Collections.enumeration(attributes.keySet()); 235 | } 236 | } 237 | 238 | @Override 239 | public String getCharacterEncoding() { 240 | return null; 241 | } 242 | 243 | @Override 244 | public void setCharacterEncoding(String env) throws UnsupportedEncodingException { 245 | 246 | } 247 | 248 | @Override 249 | public int getContentLength() { 250 | return 0; 251 | } 252 | 253 | @Override 254 | public long getContentLengthLong() { 255 | return 0; 256 | } 257 | 258 | @Override 259 | public String getContentType() { 260 | return null; 261 | } 262 | 263 | @Override 264 | public ServletInputStream getInputStream() throws IOException { 265 | return inputStream; 266 | } 267 | 268 | @Override 269 | public String getParameter(String name) { 270 | return null; 271 | } 272 | 273 | @Override 274 | public Enumeration getParameterNames() { 275 | return null; 276 | } 277 | 278 | @Override 279 | public String[] getParameterValues(String name) { 280 | return new String[0]; 281 | } 282 | 283 | @Override 284 | public Map getParameterMap() { 285 | return null; 286 | } 287 | 288 | @Override 289 | public String getProtocol() { 290 | return request.protocolVersion().protocolName(); 291 | } 292 | 293 | @Override 294 | public String getScheme() { 295 | return null; 296 | } 297 | 298 | @Override 299 | public String getServerName() { 300 | return null; 301 | } 302 | 303 | @Override 304 | public int getServerPort() { 305 | return 0; 306 | } 307 | 308 | @Override 309 | public BufferedReader getReader() throws IOException { 310 | return null; 311 | } 312 | 313 | @Override 314 | public String getRemoteAddr() { 315 | return null; 316 | } 317 | 318 | @Override 319 | public String getRemoteHost() { 320 | return null; 321 | } 322 | 323 | @Override 324 | public void setAttribute(String name, Object o) { 325 | synchronized (attributes) { 326 | attributes.put(name, o); 327 | } 328 | } 329 | 330 | @Override 331 | public void removeAttribute(String name) { 332 | synchronized (attributes) { 333 | attributes.remove(name); 334 | } 335 | } 336 | 337 | @Override 338 | public Locale getLocale() { 339 | return null; 340 | } 341 | 342 | @Override 343 | public Enumeration getLocales() { 344 | return null; 345 | } 346 | 347 | @Override 348 | public boolean isSecure() { 349 | return false; 350 | } 351 | 352 | @Override 353 | public RequestDispatcher getRequestDispatcher(String path) { 354 | return null; 355 | } 356 | 357 | @Override 358 | public String getRealPath(String path) { 359 | return null; 360 | } 361 | 362 | @Override 363 | public int getRemotePort() { 364 | return 0; 365 | } 366 | 367 | @Override 368 | public String getLocalName() { 369 | return null; 370 | } 371 | 372 | @Override 373 | public String getLocalAddr() { 374 | return null; 375 | } 376 | 377 | @Override 378 | public int getLocalPort() { 379 | return 0; 380 | } 381 | 382 | @Override 383 | public ServletContext getServletContext() { 384 | return servletContext; 385 | } 386 | 387 | @Override 388 | public AsyncContext startAsync() { 389 | return startAsync(this, null); 390 | } 391 | 392 | @Override 393 | public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) { 394 | return ((NettyAsyncContext) getAsyncContext()).startAsync(servletRequest, servletResponse); 395 | } 396 | 397 | @Override 398 | public boolean isAsyncStarted() { 399 | return null != asyncContext && asyncContext.isAsyncStarted(); 400 | } 401 | 402 | void setAsyncSupported(boolean asyncSupported) { 403 | this.asyncSupported = asyncSupported; 404 | } 405 | 406 | @Override 407 | public boolean isAsyncSupported() { 408 | return asyncSupported; 409 | } 410 | 411 | @Override 412 | public AsyncContext getAsyncContext() { 413 | if (null == asyncContext) { 414 | asyncContext = new NettyAsyncContext(this, ctx); 415 | } 416 | return asyncContext; 417 | } 418 | 419 | @Override 420 | public DispatcherType getDispatcherType() { 421 | return attributes.containsKey(DISPATCHER_TYPE) ? (DispatcherType) attributes.get(DISPATCHER_TYPE) : DispatcherType.REQUEST; 422 | } 423 | 424 | public ServletResponse getServletResponse() { 425 | return servletResponse; 426 | } 427 | } 428 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyHttpServletResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import com.google.common.annotations.VisibleForTesting; 21 | import com.google.common.base.Charsets; 22 | import com.google.common.base.Optional; 23 | import com.google.common.net.MediaType; 24 | import io.netty.channel.ChannelHandlerContext; 25 | import io.netty.handler.codec.http.HttpHeaders; 26 | import io.netty.handler.codec.http.HttpResponse; 27 | import io.netty.handler.codec.http.HttpResponseStatus; 28 | import io.netty.util.concurrent.FastThreadLocal; 29 | 30 | import javax.servlet.ServletOutputStream; 31 | import javax.servlet.http.Cookie; 32 | import javax.servlet.http.HttpServletResponse; 33 | import java.io.IOException; 34 | import java.io.PrintWriter; 35 | import java.nio.charset.Charset; 36 | import java.text.DateFormat; 37 | import java.text.SimpleDateFormat; 38 | import java.util.*; 39 | 40 | import static com.google.common.base.Preconditions.checkState; 41 | 42 | /** 43 | * {@link HttpServletResponse} wrapper for Netty's {@link HttpResponse}. 44 | * 45 | * @author Danny Thomas 46 | */ 47 | class NettyHttpServletResponse implements HttpServletResponse { 48 | private static final FastThreadLocal FORMAT = new FastThreadLocal() { 49 | @Override 50 | protected DateFormat initialValue() { 51 | return new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z"); 52 | } 53 | }; 54 | 55 | private static final Locale DEFAULT_LOCALE = Locale.getDefault(); 56 | private static final String DEFAULT_CHARACTER_ENCODING = Charsets.ISO_8859_1.name(); 57 | 58 | private final NettyEmbeddedContext servletContext; 59 | private HttpResponse response; 60 | private HttpResponseOutputStream outputStream; 61 | private boolean usingOutputStream; 62 | private PrintWriter writer; 63 | private boolean committed; 64 | private List cookies; 65 | private String contentType; 66 | private String characterEncoding = DEFAULT_CHARACTER_ENCODING; 67 | private Locale locale; 68 | 69 | NettyHttpServletResponse(ChannelHandlerContext ctx, NettyEmbeddedContext servletContext, HttpResponse response) { 70 | this.servletContext = servletContext; 71 | this.response = response; 72 | this.outputStream = new HttpResponseOutputStream(ctx, this); 73 | cookies = new ArrayList<>(); 74 | } 75 | 76 | /** 77 | * Get a Netty {@link HttpResponse}, committing the {@link HttpServletResponse}. 78 | */ 79 | public HttpResponse getNettyResponse() { 80 | if (committed) { 81 | return response; 82 | } 83 | committed = true; 84 | HttpHeaders headers = response.headers(); 85 | if (null != contentType) { 86 | String value = null == characterEncoding ? contentType : contentType + "; charset=" + characterEncoding; 87 | headers.set(HttpHeaders.Names.CONTENT_TYPE, value); 88 | } 89 | CharSequence date = getFormattedDate(); 90 | headers.set(HttpHeaders.Names.DATE, date); 91 | headers.set(HttpHeaders.Names.SERVER, servletContext.getServerInfoAscii()); 92 | // TODO cookies 93 | return response; 94 | } 95 | 96 | @VisibleForTesting 97 | CharSequence getFormattedDate() { 98 | return HttpHeaders.newEntity(FORMAT.get().format(new Date())); 99 | } 100 | 101 | @Override 102 | public void addCookie(Cookie cookie) { 103 | cookies.add(cookie); 104 | } 105 | 106 | @Override 107 | public boolean containsHeader(String name) { 108 | return response.headers().contains(name); 109 | } 110 | 111 | @Override 112 | public String encodeURL(String url) { 113 | return null; 114 | } 115 | 116 | @Override 117 | public String encodeRedirectURL(String url) { 118 | return null; 119 | } 120 | 121 | @Override 122 | public String encodeUrl(String url) { 123 | return null; 124 | } 125 | 126 | @Override 127 | public String encodeRedirectUrl(String url) { 128 | return null; 129 | } 130 | 131 | @Override 132 | public void sendError(int sc, String msg) throws IOException { 133 | checkNotCommitted(); 134 | response.setStatus(new HttpResponseStatus(sc, msg)); 135 | } 136 | 137 | @Override 138 | public void sendError(int sc) throws IOException { 139 | checkNotCommitted(); 140 | response.setStatus(HttpResponseStatus.valueOf(sc)); 141 | } 142 | 143 | @Override 144 | public void sendRedirect(String location) throws IOException { 145 | checkNotCommitted(); 146 | // TODO implement 147 | } 148 | 149 | @Override 150 | public void setDateHeader(String name, long date) { 151 | response.headers().set(name, date); 152 | } 153 | 154 | @Override 155 | public void addDateHeader(String name, long date) { 156 | response.headers().add(name, date); 157 | } 158 | 159 | @Override 160 | public void setHeader(String name, String value) { 161 | if (setHeaderField(name, value)) { 162 | return; 163 | } 164 | response.headers().set(name, value); 165 | } 166 | 167 | private boolean setHeaderField(String name, String value) { 168 | // Handle headers that shouldn't be set directly, and are instance fields 169 | char c = name.charAt(0); 170 | if ('C' == c || 'c' == c) { 171 | if (HttpHeaders.Names.CONTENT_TYPE.equalsIgnoreCase(name)) { 172 | setContentType(value); 173 | return true; 174 | } 175 | // TODO Content-Language? 176 | } 177 | return false; 178 | } 179 | 180 | @Override 181 | public void addHeader(String name, String value) { 182 | if (setHeaderField(name, value)) { 183 | return; 184 | } 185 | response.headers().add(name, value); 186 | } 187 | 188 | @Override 189 | public void setIntHeader(String name, int value) { 190 | response.headers().set(name, value); 191 | } 192 | 193 | @Override 194 | public void addIntHeader(String name, int value) { 195 | response.headers().add(name, value); 196 | } 197 | 198 | @Override 199 | public void setStatus(int sc) { 200 | response.setStatus(HttpResponseStatus.valueOf(sc)); 201 | } 202 | 203 | @Override 204 | public void setStatus(int sc, String sm) { 205 | response.setStatus(new HttpResponseStatus(sc, sm)); 206 | } 207 | 208 | @Override 209 | public int getStatus() { 210 | return response.status().code(); 211 | } 212 | 213 | @Override 214 | public String getHeader(String name) { 215 | return response.headers().get(name); 216 | } 217 | 218 | @Override 219 | public Collection getHeaders(String name) { 220 | return response.headers().getAll(name); 221 | } 222 | 223 | @Override 224 | public Collection getHeaderNames() { 225 | return response.headers().names(); 226 | } 227 | 228 | @Override 229 | public String getCharacterEncoding() { 230 | return characterEncoding; 231 | } 232 | 233 | @Override 234 | public String getContentType() { 235 | return contentType; 236 | } 237 | 238 | @Override 239 | public ServletOutputStream getOutputStream() throws IOException { 240 | checkState(!hasWriter(), "getWriter has already been called for this response"); 241 | usingOutputStream = true; 242 | return outputStream; 243 | } 244 | 245 | @Override 246 | public PrintWriter getWriter() throws IOException { 247 | checkState(!usingOutputStream, "getOutputStream has already been called for this response"); 248 | if (!hasWriter()) { 249 | writer = new PrintWriter(outputStream); 250 | } 251 | return writer; 252 | } 253 | 254 | @Override 255 | public void setCharacterEncoding(String charset) { 256 | if (hasWriter()) { 257 | return; 258 | } 259 | characterEncoding = charset; 260 | } 261 | 262 | @Override 263 | public void setContentType(String type) { 264 | if (isCommitted()) { 265 | return; 266 | } 267 | if (hasWriter()) { 268 | return; 269 | } 270 | if (null == type) { 271 | contentType = null; 272 | return; 273 | } 274 | MediaType mediaType = MediaType.parse(type); 275 | Optional charset = mediaType.charset(); 276 | if (charset.isPresent()) { 277 | setCharacterEncoding(charset.get().name()); 278 | } 279 | contentType = mediaType.type() + '/' + mediaType.subtype(); 280 | } 281 | 282 | private boolean hasWriter() { 283 | return null != writer; 284 | } 285 | 286 | @Override 287 | public void setContentLength(int len) { 288 | HttpHeaders.setContentLength(response, len); 289 | } 290 | 291 | @Override 292 | public void setContentLengthLong(long len) { 293 | HttpHeaders.setContentLength(response, len); 294 | } 295 | 296 | @Override 297 | public void setBufferSize(int size) { 298 | checkNotCommitted(); 299 | outputStream.setBufferSize(size); 300 | } 301 | 302 | @Override 303 | public int getBufferSize() { 304 | return outputStream.getBufferSize(); 305 | } 306 | 307 | @Override 308 | public void flushBuffer() throws IOException { 309 | checkNotCommitted(); 310 | outputStream.flush(); 311 | } 312 | 313 | @Override 314 | public void resetBuffer() { 315 | checkNotCommitted(); 316 | outputStream.resetBuffer(); 317 | } 318 | 319 | @Override 320 | public boolean isCommitted() { 321 | return committed; 322 | } 323 | 324 | void checkNotCommitted() { 325 | checkState(!committed, "Cannot perform this operation after response has been committed"); 326 | } 327 | 328 | @Override 329 | public void reset() { 330 | resetBuffer(); 331 | usingOutputStream = false; 332 | writer = null; 333 | } 334 | 335 | @Override 336 | public void setLocale(Locale loc) { 337 | locale = loc; 338 | } 339 | 340 | @Override 341 | public Locale getLocale() { 342 | return null == locale ? DEFAULT_LOCALE : locale; 343 | } 344 | } 345 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyRequestDispatcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import javax.servlet.*; 21 | import java.io.IOException; 22 | 23 | /** 24 | * @author Danny Thomas 25 | */ 26 | class NettyRequestDispatcher implements RequestDispatcher { 27 | private final ServletContext context; 28 | private final FilterChain filterChain; 29 | 30 | NettyRequestDispatcher(ServletContext context, FilterChain filterChain) { 31 | this.context = context; 32 | this.filterChain = filterChain; 33 | } 34 | 35 | @Override 36 | public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { 37 | request.setAttribute(NettyHttpServletRequest.DISPATCHER_TYPE, DispatcherType.FORWARD); 38 | // TODO implement 39 | } 40 | 41 | @Override 42 | public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { 43 | request.setAttribute(NettyHttpServletRequest.DISPATCHER_TYPE, DispatcherType.INCLUDE); 44 | // TODO implement 45 | } 46 | 47 | void dispatch(ServletRequest request, ServletResponse response) throws ServletException, IOException { 48 | request.setAttribute(NettyHttpServletRequest.DISPATCHER_TYPE, DispatcherType.ASYNC); 49 | filterChain.doFilter(request, response); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/NettyServletRegistration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import javax.servlet.*; 21 | import java.util.Collection; 22 | import java.util.Collections; 23 | import java.util.Set; 24 | 25 | /** 26 | * A {@link org.springframework.boot.context.embedded.netty.NettyEmbeddedContext} {@link javax.servlet.ServletRegistration}. 27 | * 28 | * @author Danny Thomas 29 | */ 30 | class NettyServletRegistration extends AbstractNettyRegistration implements ServletRegistration.Dynamic { 31 | private volatile boolean initialised; 32 | private Servlet servlet; 33 | 34 | NettyServletRegistration(NettyEmbeddedContext context, String servletName, String className, Servlet servlet) { 35 | super(servletName, className, context); 36 | this.servlet = servlet; 37 | } 38 | 39 | public Servlet getServlet() throws ServletException { 40 | if (!initialised) { 41 | synchronized (this) { 42 | if (!initialised) { 43 | if (null == servlet) { 44 | try { 45 | servlet = (Servlet) Class.forName(getClassName()).newInstance(); 46 | } catch (Exception e) { 47 | throw new ServletException(e); 48 | } 49 | } 50 | servlet.init(this); 51 | initialised = true; 52 | } 53 | } 54 | } 55 | return servlet; 56 | } 57 | 58 | @Override 59 | public void setLoadOnStartup(int loadOnStartup) { 60 | 61 | } 62 | 63 | @Override 64 | public Set setServletSecurity(ServletSecurityElement constraint) { 65 | return null; 66 | } 67 | 68 | @Override 69 | public void setMultipartConfig(MultipartConfigElement multipartConfig) { 70 | 71 | } 72 | 73 | @Override 74 | public void setRunAsRole(String roleName) { 75 | 76 | } 77 | 78 | @Override 79 | public Set addMapping(String... urlPatterns) { 80 | // TODO check for conflicts 81 | 82 | NettyEmbeddedContext context = getNettyContext(); 83 | for (String urlPattern : urlPatterns) { 84 | context.addServletMapping(urlPattern, getName()); 85 | } 86 | return Collections.emptySet(); 87 | } 88 | 89 | @Override 90 | public Collection getMappings() { 91 | return null; 92 | } 93 | 94 | @Override 95 | public String getRunAsRole() { 96 | return null; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/RequestDispatcherHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.channel.ChannelHandler; 21 | import io.netty.channel.ChannelHandlerContext; 22 | import io.netty.channel.SimpleChannelInboundHandler; 23 | import org.apache.commons.logging.Log; 24 | import org.apache.commons.logging.LogFactory; 25 | 26 | import javax.servlet.http.HttpServletRequest; 27 | import javax.servlet.http.HttpServletResponse; 28 | 29 | import static com.google.common.base.Preconditions.checkNotNull; 30 | 31 | /** 32 | * A {@link io.netty.channel.ChannelInboundHandler} that bridges to and from {@link HttpServletRequest}s and 33 | * {@link HttpServletResponse}s from Netty HTTP codec objects. 34 | * 35 | * @author Danny Thomas 36 | */ 37 | @ChannelHandler.Sharable 38 | class RequestDispatcherHandler extends SimpleChannelInboundHandler { 39 | private final Log logger = LogFactory.getLog(getClass()); 40 | private final NettyEmbeddedContext context; 41 | 42 | RequestDispatcherHandler(NettyEmbeddedContext context) { 43 | this.context = checkNotNull(context); 44 | } 45 | 46 | @Override 47 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 48 | ctx.flush(); 49 | } 50 | 51 | @Override 52 | protected void channelRead0(ChannelHandlerContext ctx, NettyHttpServletRequest request) throws Exception { 53 | HttpServletResponse servletResponse = (HttpServletResponse) request.getServletResponse(); 54 | try { 55 | NettyRequestDispatcher dispatcher = (NettyRequestDispatcher) context.getRequestDispatcher(request.getRequestURI()); 56 | if (dispatcher == null) { 57 | servletResponse.sendError(404); 58 | return; 59 | } 60 | dispatcher.dispatch(request, servletResponse); 61 | } finally { 62 | if (!request.isAsyncStarted()) { 63 | servletResponse.getOutputStream().close(); 64 | } 65 | } 66 | } 67 | 68 | @Override 69 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 70 | logger.error("Unexpected exception caught during request", cause); 71 | ctx.close(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/ServletContentHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.channel.ChannelInboundHandlerAdapter; 22 | import io.netty.handler.codec.http.*; 23 | 24 | /** 25 | * {@link io.netty.channel.ChannelInboundHandler} responsible for initial request handling, and getting received 26 | * {@link HttpContent} messages to the {@link HttpContentInputStream} for the request. 27 | */ 28 | class ServletContentHandler extends ChannelInboundHandlerAdapter { 29 | private final NettyEmbeddedContext servletContext; 30 | private HttpContentInputStream inputStream; // FIXME this feels wonky, need a better approach 31 | 32 | ServletContentHandler(NettyEmbeddedContext servletContext) { 33 | this.servletContext = servletContext; 34 | } 35 | 36 | @Override 37 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 38 | inputStream = new HttpContentInputStream(ctx.channel()); 39 | } 40 | 41 | @Override 42 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 43 | if (msg instanceof HttpRequest) { 44 | HttpRequest request = (HttpRequest) msg; 45 | HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, false); 46 | HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request)); 47 | NettyHttpServletResponse servletResponse = new NettyHttpServletResponse(ctx, servletContext, response); 48 | NettyHttpServletRequest servletRequest = new NettyHttpServletRequest(ctx, servletContext, request, servletResponse, inputStream); 49 | if (HttpHeaders.is100ContinueExpected(request)) { 50 | ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE), ctx.voidPromise()); 51 | } 52 | ctx.fireChannelRead(servletRequest); 53 | } 54 | if (msg instanceof HttpContent) { 55 | inputStream.addContent((HttpContent) msg); 56 | } 57 | } 58 | 59 | @Override 60 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 61 | inputStream.close(); 62 | } 63 | } -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/SimpleFilterChain.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty; 19 | 20 | import javax.servlet.*; 21 | import java.io.IOException; 22 | import java.util.Iterator; 23 | 24 | import static com.google.common.base.Preconditions.checkNotNull; 25 | 26 | /** 27 | * A very simple {@link FilterChain} implementation. 28 | * 29 | * @author Danny Thomas 30 | */ 31 | class SimpleFilterChain implements FilterChain { 32 | private final Iterator filterIterator; 33 | private final Servlet servlet; 34 | 35 | SimpleFilterChain(Servlet servlet, Iterable filters) throws ServletException { 36 | this.filterIterator = checkNotNull(filters).iterator(); 37 | this.servlet = checkNotNull(servlet); 38 | } 39 | 40 | @Override 41 | public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { 42 | if (filterIterator.hasNext()) { 43 | Filter filter = filterIterator.next(); 44 | filter.doFilter(request, response, this); 45 | } else { 46 | servlet.service(request, response); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/boot/context/embedded/netty/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | /** 19 | * Comment here. 20 | */ 21 | package org.springframework.boot.context.embedded.netty; -------------------------------------------------------------------------------- /src/test/groovy/org/springframework/boot/context/embedded/netty/HttpContentInputStreamTest.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty 19 | 20 | import com.google.common.base.Charsets 21 | import io.netty.buffer.Unpooled 22 | import io.netty.channel.Channel 23 | import io.netty.handler.codec.http.DefaultHttpContent 24 | import io.netty.handler.codec.http.LastHttpContent 25 | import spock.lang.Specification 26 | 27 | /** 28 | * Tests for {@link HttpContentInputStream}. 29 | */ 30 | class HttpContentInputStreamTest extends Specification { 31 | def channel 32 | def stream 33 | 34 | def setup() { 35 | channel = Mock(Channel) 36 | stream = new HttpContentInputStream(channel) 37 | } 38 | 39 | def 'a read with a an empty last content returns -1'() { 40 | given: 41 | stream.addContent(LastHttpContent.EMPTY_LAST_CONTENT) 42 | 43 | expect: 44 | stream.read() == -1 45 | } 46 | 47 | def 'a read with an empty last content, for a non-active channel, returns -1'() { 48 | given: 49 | stream.addContent(LastHttpContent.EMPTY_LAST_CONTENT) 50 | 51 | expect: 52 | stream.read() == -1 53 | } 54 | 55 | def 'an attempt to read with a non-active channel, throws IOException'() { 56 | given: 57 | channel.isActive() >> false 58 | 59 | when: 60 | stream.read() 61 | 62 | then: 63 | thrown(IOException) 64 | } 65 | 66 | def 'expected number of bytes and content is read for a single content read'() { 67 | when: 68 | stream.addContent(new DefaultHttpContent(Unpooled.copiedBuffer("My hovercraft is full of eels.", Charsets.UTF_8))) 69 | 70 | then: 71 | def b = new byte[30] 72 | stream.read(b, 0, 30) == 30 73 | new String(b) == "My hovercraft is full of eels." 74 | } 75 | 76 | def 'the expected number of bytes and content is read for partial read of two component contents'() { 77 | when: 78 | stream.addContent(new DefaultHttpContent(Unpooled.copiedBuffer("My hovercraft is full of eels.", Charsets.UTF_8))) 79 | stream.addContent(new DefaultHttpContent(Unpooled.copiedBuffer(" I will not buy this record, it is scratched.", Charsets.UTF_8))) 80 | 81 | then: 82 | def b = new byte[75] 83 | stream.read(b, 0, 30) == 30 84 | stream.read(b, 30, 45) == 45 85 | new String(b) == "My hovercraft is full of eels. I will not buy this record, it is scratched." 86 | } 87 | 88 | def 'zero length read returns 0'() { 89 | expect: 90 | stream.read(new byte[0], 0, 0) == 0 91 | } 92 | 93 | def 'stream is not finished'() { 94 | expect: 95 | !stream.isFinished() 96 | } 97 | 98 | def 'stream is not ready'() { 99 | expect: 100 | !stream.isReady() 101 | } 102 | 103 | def 'stream has no available bytes'() { 104 | expect: 105 | stream.available() == 0 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/test/groovy/org/springframework/boot/context/embedded/netty/PackageSanityTest.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * 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, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package org.springframework.boot.context.embedded.netty 19 | 20 | import com.google.common.base.Predicate 21 | import com.google.common.testing.AbstractPackageSanityTests 22 | import io.netty.buffer.ByteBuf 23 | import io.netty.buffer.Unpooled 24 | import org.junit.Ignore 25 | 26 | import javax.annotation.Nullable 27 | 28 | /** 29 | * Sanity tests for {@link org.springframework.boot.context.embedded.netty}. 30 | */ 31 | @Ignore 32 | // FIXME I've added a bunch of new classes that can't be instantiated automatically, that'll I'll need to add back here 33 | class PackageSanityTest extends AbstractPackageSanityTests { 34 | PackageSanityTest() { 35 | setDefault(ByteBuf, Unpooled.buffer()) 36 | setDefault(NettyEmbeddedContext, new NettyEmbeddedContext("/", Thread.currentThread().getContextClassLoader(), "ServerInfo")) 37 | ignoreClasses(new Predicate>() { 38 | @Override 39 | boolean apply(@Nullable Class input) { 40 | input == AbstractNettyRegistration 41 | } 42 | }) 43 | } 44 | } 45 | --------------------------------------------------------------------------------