├── .gitignore ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .travis.yml ├── src ├── main │ ├── java │ │ └── rxweb │ │ │ ├── support │ │ │ ├── Constants.java │ │ │ ├── Converter.java │ │ │ └── DefaultConverter.java │ │ │ ├── annotation │ │ │ ├── Controller.java │ │ │ ├── RequestBody.java │ │ │ └── RequestMapping.java │ │ │ ├── mapping │ │ │ ├── Condition.java │ │ │ ├── HandlerRegistry.java │ │ │ └── HandlerResolver.java │ │ │ ├── bean │ │ │ ├── Params.java │ │ │ └── WebRequest.java │ │ │ ├── server │ │ │ ├── WebInvoker.java │ │ │ ├── WebRequestHandler.java │ │ │ ├── NotFoundHandler.java │ │ │ ├── Handler.java │ │ │ ├── DefaultHandlerResolver.java │ │ │ ├── BootstrapConfig.java │ │ │ └── DefaultHandlerInvoker.java │ │ │ ├── Server.java │ │ │ ├── engine │ │ │ └── server │ │ │ │ └── netty │ │ │ │ ├── NettyServer.java │ │ │ │ └── Dispatcher.java │ │ │ └── sample │ │ │ └── TestController.java │ └── resources │ │ └── logback.xml └── test │ └── java │ └── rxweb │ └── RxJavaServerTests.java ├── gradlew.bat ├── README-CN.md ├── README.md ├── gradlew └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.war 3 | *.ear 4 | hs_err_pid* 5 | *.iml 6 | build/ 7 | .gradle/ 8 | .idea/ -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangjessey/rxweb/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: oraclejdk8 3 | script: 4 | ./gradlew clean test 5 | after_success: 6 | - ./gradlew jacocoTestReport 7 | - bash <(curl -s https://codecov.io/bash) -------------------------------------------------------------------------------- /src/main/java/rxweb/support/Constants.java: -------------------------------------------------------------------------------- 1 | package rxweb.support; 2 | 3 | /** 4 | * @author zhangjessey 5 | */ 6 | public class Constants { 7 | 8 | public static final String JSON = "application/json"; 9 | } 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/java/rxweb/annotation/Controller.java: -------------------------------------------------------------------------------- 1 | package rxweb.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * 控制器注解 10 | * 11 | * @author zhangjessey 12 | */ 13 | @Target(ElementType.TYPE) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | public @interface Controller {} -------------------------------------------------------------------------------- /src/main/java/rxweb/annotation/RequestBody.java: -------------------------------------------------------------------------------- 1 | package rxweb.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * 标记请求参数为JSON 10 | * 11 | * @author zhangjessey 12 | */ 13 | @Target(ElementType.PARAMETER) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | public @interface RequestBody { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/rxweb/mapping/Condition.java: -------------------------------------------------------------------------------- 1 | package rxweb.mapping; 2 | 3 | import io.netty.handler.codec.http.HttpMethod; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.EqualsAndHashCode; 7 | 8 | /** 9 | * 请求条件,即method和url 10 | * 11 | * @author zhangjessey 12 | */ 13 | @Data 14 | @AllArgsConstructor 15 | @EqualsAndHashCode 16 | public class Condition { 17 | private HttpMethod httpMethod; 18 | private String url; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/main/java/rxweb/bean/Params.java: -------------------------------------------------------------------------------- 1 | package rxweb.bean; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import java.util.Map; 8 | 9 | /** 10 | * url参数 11 | * 12 | * @author zhangjessey 13 | */ 14 | @Data 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | public class Params { 18 | private Map map; 19 | 20 | @Override 21 | public String toString() { 22 | return String.join(":", map.keySet()); 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /src/main/java/rxweb/support/Converter.java: -------------------------------------------------------------------------------- 1 | package rxweb.support; 2 | 3 | /** 4 | * 转换器,负责序列化与反序列化 5 | * 6 | * @author zhangjessey 7 | */ 8 | public interface Converter { 9 | 10 | /** 11 | * 序列化为字符串 12 | * @param t 序列化目标对象 13 | * @param 序列化目标对象类型 14 | * @return 序列化后的String 15 | */ 16 | String serialize(T t); 17 | 18 | /** 19 | * 反序列化为一个对象 20 | * @param string 反序列化目标字符串 21 | * @param tClass 序列化后的class 22 | * @param 序列化后的类型 23 | * @return tClass对应的对象 24 | */ 25 | T deserialize(String string, Class tClass); 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/rxweb/server/WebInvoker.java: -------------------------------------------------------------------------------- 1 | package rxweb.server; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 5 | import rxweb.bean.WebRequest; 6 | 7 | /** 8 | * Handler调用器接口 9 | * 10 | * @author zhangjessey 11 | */ 12 | public interface WebInvoker { 13 | 14 | /** 15 | * 调用具体Handler 16 | * @param request 内部请求对象 17 | * @param handler 将被调用的Handler 18 | * @param response RxNetty原生的response 19 | * @return 调用结束后的返回值 20 | */ 21 | Object invokeHandler(WebRequest request, Handler handler, HttpServerResponse response); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/rxweb/server/WebRequestHandler.java: -------------------------------------------------------------------------------- 1 | package rxweb.server; 2 | 3 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 4 | import rx.Observable; 5 | import rxweb.bean.WebRequest; 6 | 7 | /** 8 | * 自定义handler接口 9 | * 10 | * @author zhangjessey 11 | */ 12 | public interface WebRequestHandler { 13 | 14 | /** 15 | * 实际的处理过程 16 | * 17 | * @param webRequest 内部请求对象 18 | * @param response RxNetty原生的response 19 | * @return 实际返回为空,可以理解为无作用,实际在response返回 20 | */ 21 | Observable handle(WebRequest webRequest, HttpServerResponse response); 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/rxweb/server/NotFoundHandler.java: -------------------------------------------------------------------------------- 1 | package rxweb.server; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.handler.codec.http.HttpResponseStatus; 5 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 6 | import rx.Observable; 7 | import rxweb.bean.WebRequest; 8 | 9 | /** 10 | * 专门负责404的处理器 11 | * 12 | * @author zhangjessey 13 | */ 14 | public class NotFoundHandler implements WebRequestHandler { 15 | 16 | 17 | @Override 18 | public Observable handle(WebRequest webRequest, HttpServerResponse response) { 19 | response.setStatus(HttpResponseStatus.NOT_FOUND); 20 | return Observable.empty(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/rxweb/annotation/RequestMapping.java: -------------------------------------------------------------------------------- 1 | package rxweb.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * 标记url及其method 10 | * 11 | * @author zhangjessey 12 | */ 13 | @Target(ElementType.METHOD) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | public @interface RequestMapping { 16 | 17 | @Target(ElementType.METHOD) 18 | @Retention(RetentionPolicy.RUNTIME) 19 | @interface Get { 20 | 21 | String value(); 22 | } 23 | 24 | @Target(ElementType.METHOD) 25 | @Retention(RetentionPolicy.RUNTIME) 26 | @interface Post { 27 | 28 | String value(); 29 | } 30 | 31 | @Target(ElementType.METHOD) 32 | @Retention(RetentionPolicy.RUNTIME) 33 | @interface Put { 34 | 35 | String value(); 36 | } 37 | 38 | @Target(ElementType.METHOD) 39 | @Retention(RetentionPolicy.RUNTIME) 40 | @interface Delete { 41 | 42 | String value(); 43 | } 44 | } -------------------------------------------------------------------------------- /src/main/java/rxweb/support/DefaultConverter.java: -------------------------------------------------------------------------------- 1 | package rxweb.support; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import java.io.IOException; 9 | 10 | /** 11 | * 默认转换器,使用Jackson 12 | * 13 | * @author zhangjessey 14 | */ 15 | public class DefaultConverter implements Converter { 16 | private final Logger logger = LoggerFactory.getLogger(getClass()); 17 | @Override 18 | public String serialize(T t) { 19 | try { 20 | return new ObjectMapper().writeValueAsString(t); 21 | } catch (JsonProcessingException e) { 22 | logger.error(e.getMessage()); 23 | return null; 24 | } 25 | } 26 | 27 | @Override 28 | public T deserialize(String string, Class tClass) { 29 | try { 30 | return new ObjectMapper().readValue(string, tClass); 31 | } catch (IOException e) { 32 | logger.error(e.getMessage()); 33 | return null; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/rxweb/mapping/HandlerRegistry.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-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 | package rxweb.mapping; 18 | 19 | import io.netty.buffer.ByteBuf; 20 | import rxweb.server.WebRequestHandler; 21 | 22 | /** 23 | * handler管理器 24 | * 25 | * @author Sebastien Deleuze 26 | * @author zhangjessey 27 | */ 28 | public interface HandlerRegistry { 29 | 30 | /** 31 | * 添加一个RequestHandler 32 | * @param condition 某一个WebRequestHandler的匹配条件 33 | * @param handler 具体的WebRequestHandler 34 | * @return 解析器对象 35 | */ 36 | HandlerResolver addHandler(final Condition condition, final WebRequestHandler handler); 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/rxweb/mapping/HandlerResolver.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-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 | package rxweb.mapping; 18 | 19 | import io.netty.buffer.ByteBuf; 20 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 21 | import rxweb.bean.WebRequest; 22 | import rxweb.server.WebRequestHandler; 23 | 24 | import java.util.List; 25 | 26 | /** 27 | * 请求解析器 28 | * 29 | * @author Sebastien Deleuze 30 | * @author zhangjessey 31 | */ 32 | public interface HandlerResolver extends HandlerRegistry { 33 | 34 | /** 35 | * 根据request找到对应的RequestHandler 36 | * @param request 内部请求对象 37 | * @return 符合要求的WebRequestHandler列表 38 | */ 39 | List> resolve(WebRequest request); 40 | 41 | } -------------------------------------------------------------------------------- /src/main/java/rxweb/server/Handler.java: -------------------------------------------------------------------------------- 1 | package rxweb.server; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 5 | import lombok.Data; 6 | import rx.Observable; 7 | import rxweb.bean.WebRequest; 8 | import rxweb.support.DefaultConverter; 9 | 10 | import java.lang.reflect.Method; 11 | 12 | /** 13 | * 实际的请求处理器,对应一个注解方式的方法或者函数式路由的函数式接口 14 | * 15 | * @author huangyong 16 | * @author zhangjessey 17 | */ 18 | @Data 19 | public class Handler implements WebRequestHandler { 20 | 21 | private Class actionClass; 22 | private Method actionMethod; 23 | 24 | private Class requestBodyClass; 25 | private String requestBody; 26 | 27 | 28 | public Handler(Class actionClass, Method actionMethod, Class requestBodyClass) { 29 | this.actionClass = actionClass; 30 | this.actionMethod = actionMethod; 31 | this.requestBodyClass = requestBodyClass; 32 | } 33 | 34 | 35 | 36 | @Override 37 | public Observable handle(WebRequest webRequest, HttpServerResponse response) { 38 | 39 | DefaultHandlerInvoker defaultHandlerInvoker = new DefaultHandlerInvoker(); 40 | Observable obs = defaultHandlerInvoker.invokeHandler(webRequest, this, response); 41 | DefaultConverter defaultConverter = new DefaultConverter(); 42 | 43 | return response.writeString(obs.map(o -> { 44 | if (o instanceof String) { 45 | return (String) o; 46 | } else { 47 | return defaultConverter.serialize(o); 48 | } 49 | 50 | })); 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /src/main/java/rxweb/bean/WebRequest.java: -------------------------------------------------------------------------------- 1 | package rxweb.bean; 2 | 3 | /******************************************************************************* 4 | * Copyright (c) 2017 @gt_tech 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | *******************************************************************************/ 18 | 19 | 20 | import io.netty.buffer.ByteBuf; 21 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 22 | import lombok.AllArgsConstructor; 23 | import lombok.Data; 24 | import rxweb.server.WebRequestHandler; 25 | 26 | import java.util.List; 27 | import java.util.regex.Matcher; 28 | 29 | /** 30 | * 内部请求对象,包裹HttpServerRequest 31 | * 32 | * @author gt_tech 33 | * @author zhangjessey 34 | */ 35 | @Data 36 | @AllArgsConstructor 37 | public class WebRequest { 38 | 39 | private final HttpServerRequest httpServerRequest; 40 | 41 | private Matcher requestPathMatcher; 42 | 43 | private List urlParams; 44 | 45 | private WebRequestHandler webRequestHandler; 46 | 47 | private T body; 48 | 49 | private final String requestContentType; 50 | 51 | private final String responseAcceptType; 52 | 53 | 54 | public WebRequest(final HttpServerRequest httpServerRequest) { 55 | 56 | this.httpServerRequest = httpServerRequest; 57 | this.requestContentType = httpServerRequest.getHeader("Content-Type"); 58 | 59 | this.responseAcceptType = httpServerRequest.getHeader("Accept"); 60 | } 61 | 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/rxweb/Server.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-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 | package rxweb; 18 | 19 | import io.netty.buffer.ByteBuf; 20 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 21 | import rxweb.mapping.HandlerRegistry; 22 | import rxweb.server.WebRequestHandler; 23 | 24 | /** 25 | * 服务器接口 26 | * 27 | * @author Sebastien Deleuze 28 | * @author zhangjessey 29 | */ 30 | public interface Server extends HandlerRegistry { 31 | 32 | /** 33 | * 启动 34 | */ 35 | void start(); 36 | 37 | /** 38 | * 关闭 39 | */ 40 | void stop(); 41 | 42 | /** 43 | * 配置get方法 44 | * @param path 路径 45 | * @param handler 具体的WebRequestHandler 46 | * @return Server对象,可以链式调用 47 | */ 48 | Server get(final String path, final WebRequestHandler handler); 49 | 50 | /** 51 | * 配置post方法 52 | * @param path 路径 53 | * @param handler 具体的WebRequestHandler 54 | * @return Server对象,可以链式调用 55 | */ 56 | Server post(final String path, final WebRequestHandler handler); 57 | 58 | /** 59 | * 配置put方法 60 | * @param path 路径 61 | * @param handler 具体的WebRequestHandler 62 | * @return Server对象,可以链式调用 63 | */ 64 | Server put(final String path, final WebRequestHandler handler); 65 | 66 | /** 67 | * 配置delete方法 68 | * @param path 路径 69 | * @param handler 具体的WebRequestHandler 70 | * @return Server对象,可以链式调用 71 | */ 72 | Server delete(final String path, final WebRequestHandler handler); 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/rxweb/server/DefaultHandlerResolver.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-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 | package rxweb.server; 18 | 19 | import io.netty.buffer.ByteBuf; 20 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 21 | import rxweb.bean.WebRequest; 22 | import rxweb.mapping.Condition; 23 | import rxweb.mapping.HandlerResolver; 24 | 25 | import java.util.ArrayList; 26 | import java.util.List; 27 | import java.util.regex.Matcher; 28 | 29 | /** 30 | * 默认的HandlerResolver 31 | * 32 | * @author Sebastien Deleuze 33 | * @author zhangjessey 34 | */ 35 | public class DefaultHandlerResolver implements HandlerResolver { 36 | 37 | private static DefaultHandlerResolver DEFAULT_HANDLER_RESOLVER = new DefaultHandlerResolver(); 38 | 39 | public static DefaultHandlerResolver getSingleton() { 40 | return DEFAULT_HANDLER_RESOLVER; 41 | } 42 | 43 | @Override 44 | public HandlerResolver addHandler(final Condition condition, final WebRequestHandler handler) { 45 | BootstrapConfig.CONDITION_REQUEST_HANDLER_MAP.put(condition, handler); 46 | return this; 47 | } 48 | 49 | @Override 50 | public List> resolve(WebRequest webRequest) { 51 | 52 | Matcher matcher = webRequest.getRequestPathMatcher(); 53 | List> requestHandlers = new ArrayList<>(); 54 | if (matcher != null && matcher.matches()) { 55 | WebRequestHandler value = webRequest.getWebRequestHandler(); 56 | requestHandlers.add(value); 57 | } 58 | return requestHandlers; 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /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 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 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 Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /README-CN.md: -------------------------------------------------------------------------------- 1 | # rxweb 2 | 3 | [![Build Status](https://travis-ci.org/zhangjessey/rxweb.svg?branch=master)](https://travis-ci.org/zhangjessey/rxweb) 4 | [![codecov](https://codecov.io/gh/zhangjessey/rxweb/branch/master/graph/badge.svg)](https://codecov.io/gh/zhangjessey/rxweb) 5 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 6 | 7 | *[rxweb](https://github.com/zhangjessey/rxweb)* 基于 [rxweb](https://github.com/sdeleuze/rxweb) , [smart-framework](https://gitee.com/huangyong/smart-framework) and [nano-rxnetty-mvc-server](https://bitbucket.org/gt_tech/nano-rxnetty-mvc-server/) 8 | 9 | 这是一个基于 RxJava + RxNetty 的微型web框架 10 | 11 | 12 | ## 特性 13 | * 注解式路由与函数式路由 14 | * 支持的HTTP方法 - GET, POST, PUT, DELETE 15 | * 维持RxNetty的非阻塞特性 16 | * 与Java 8兼容 17 | * 作为MVC框架当前只支持JSON请求与响应 18 | * 支持REST URI的路径参数(基于注解式路由或者函数式路由,自动检测从HTTP请求中提取出来的路径参数) 19 | 20 | 21 | ## 依赖 22 | * Jackson (为了支持JSON) 23 | * RxNetty (包含Netty依赖) 24 | * RxJava 25 | * SLF4J (静态绑定到Logback) 26 | * Reflections 27 | * Google Guava 28 | * lombok 29 | 30 | ## 启动方式 31 | 32 | * 作为一个独立的应用运行 33 | * 用户的应用需要满足所有的依赖,并且启动服务器 34 | 35 | ## 如何使用 36 | ### 注解式路由 37 | 38 | ```java 39 | @Controller 40 | public class TestController { 41 | @RequestMapping.Post(value = "/postBean/{c}") 42 | public Observable postBean(@RequestBody User user, int c, Params params) { 43 | 44 | HashMap stringStringHashMap = new LinkedHashMap<>(5); 45 | stringStringHashMap.put("result", "success"); 46 | stringStringHashMap.put("id", user.getId()); 47 | stringStringHashMap.put("name", user.getName()); 48 | stringStringHashMap.put("pathValue", c); 49 | stringStringHashMap.put("param_a_value", params.getMap().get("a")); 50 | Params p = new Params(stringStringHashMap); 51 | 52 | return Observable.just(p); 53 | 54 | } 55 | } 56 | ``` 57 | 58 | ### 函数式路由 59 | 60 | ```java 61 | nettyServer.get("/functionalRoute/{a}/{b}", 62 | (request, response) -> 63 | response.writeString(Observable.just("this is functionalRoute".concat(request.getUrlParams().toString())))). 64 | post("/functionalRoutePost", 65 | (request, response) -> 66 | response.writeString(Observable.just("this is functionalRoutePost"))); 67 | ``` 68 | 69 | ## 未来改进点 70 | *(如果时间允许并且有价值的话)* 71 | 72 | * @RequestMapping 注解支持多种方法,不是仅包含一种方法,比如仅支持Get 73 | * 拦截器支持 74 | * Websocket支持 75 | * SpringBoot starter支持 76 | * 支持其他Mime/Types 77 | 78 | ## 贡献 79 | 非常欢迎提供贡献, 鼓励提PR或者issue. 80 | 81 | 贡献者务必确保已存在的测试用例通过 (或者修改它以适应新的变化) 82 | 83 | ## LICENSE 84 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 85 | 86 | http://www.apache.org/licenses/LICENSE-2.0 87 | 88 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 89 | -------------------------------------------------------------------------------- /src/main/java/rxweb/engine/server/netty/NettyServer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-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 | package rxweb.engine.server.netty; 18 | 19 | import io.netty.buffer.ByteBuf; 20 | import io.netty.buffer.PooledByteBufAllocator; 21 | import io.netty.channel.ChannelOption; 22 | import io.netty.handler.codec.http.HttpMethod; 23 | import io.reactivex.netty.protocol.http.server.HttpServer; 24 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 25 | import rxweb.Server; 26 | import rxweb.mapping.Condition; 27 | import rxweb.mapping.HandlerResolver; 28 | import rxweb.server.DefaultHandlerResolver; 29 | import rxweb.server.WebRequestHandler; 30 | 31 | /** 32 | * 启动类 33 | * 34 | * @author Sebastien Deleuze 35 | * @author zhangjessey 36 | */ 37 | public class NettyServer implements Server { 38 | 39 | private HandlerResolver handlerResolver = DefaultHandlerResolver.getSingleton(); 40 | private HttpServer httpServer; 41 | 42 | public NettyServer() { 43 | httpServer = HttpServer.newServer(8080). 44 | channelOption(ChannelOption.SO_KEEPALIVE, true). 45 | channelOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); 46 | 47 | 48 | } 49 | 50 | public HttpServer getHttpServer() { 51 | return httpServer; 52 | } 53 | 54 | public static void main(String[] args) { 55 | new NettyServer().start(); 56 | } 57 | 58 | 59 | @Override 60 | public void start() { 61 | httpServer.start(new Dispatcher()).awaitShutdown(); 62 | } 63 | 64 | @Override 65 | public void stop() { 66 | httpServer.shutdown(); 67 | } 68 | 69 | @Override 70 | public NettyServer get(String path, WebRequestHandler handler) { 71 | addHandler(new Condition<>(HttpMethod.GET, path), handler); 72 | return this; 73 | } 74 | 75 | @Override 76 | public NettyServer post(String path, WebRequestHandler handler) { 77 | addHandler(new Condition<>(HttpMethod.POST, path), handler); 78 | return this; 79 | } 80 | 81 | @Override 82 | public NettyServer put(String path, WebRequestHandler handler) { 83 | addHandler(new Condition<>(HttpMethod.PUT, path), handler); 84 | return this; 85 | } 86 | 87 | @Override 88 | public NettyServer delete(String path, WebRequestHandler handler) { 89 | addHandler(new Condition<>(HttpMethod.DELETE, path), handler); 90 | return this; 91 | } 92 | 93 | @Override 94 | public HandlerResolver addHandler(Condition condition, WebRequestHandler handler) { 95 | return this.handlerResolver.addHandler(condition, handler); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/rxweb/sample/TestController.java: -------------------------------------------------------------------------------- 1 | package rxweb.sample; 2 | 3 | import rx.Observable; 4 | import rxweb.annotation.Controller; 5 | import rxweb.annotation.RequestBody; 6 | import rxweb.annotation.RequestMapping; 7 | import rxweb.bean.Params; 8 | 9 | import java.util.HashMap; 10 | import java.util.LinkedHashMap; 11 | 12 | /** 13 | * 测试用Controller 14 | * 15 | * @author zhangjessey 16 | */ 17 | @Controller 18 | public class TestController { 19 | 20 | @RequestMapping.Get(value = "/hi") 21 | public Observable noParam() { 22 | 23 | return Observable.just("hello world"); 24 | } 25 | 26 | 27 | @RequestMapping.Get(value = "/withQueryParam") 28 | public Observable withQueryParam(Params params) { 29 | 30 | return Observable.just("query name:".concat(params.toString())); 31 | } 32 | 33 | @RequestMapping.Post(value = "/post/{c}") 34 | public Observable post(Params params, int c) { 35 | return getStr(params, c); 36 | } 37 | 38 | @RequestMapping.Delete(value = "/delete/{c}") 39 | public Observable delete(Params params, int c) { 40 | return getStr(params, c); 41 | } 42 | 43 | @RequestMapping.Put(value = "/put/{c}") 44 | public Observable put(Params params, int c) { 45 | return getStr(params, c); 46 | } 47 | 48 | 49 | @RequestMapping.Post(value = "/postAndReturnBean/{c}") 50 | public Observable postAndReturnBean(int c, Params params) { 51 | 52 | HashMap stringStringHashMap = new HashMap<>(3); 53 | stringStringHashMap.put("a", "1"); 54 | stringStringHashMap.put("b", "2"); 55 | stringStringHashMap.put("c", "3"); 56 | Params p = new Params(stringStringHashMap); 57 | return Observable.just(p); 58 | 59 | } 60 | 61 | 62 | @RequestMapping.Post(value = "/postBean/{c}") 63 | public Observable postBean(@RequestBody User user, int c, Params params) { 64 | 65 | HashMap stringStringHashMap = new LinkedHashMap<>(5); 66 | stringStringHashMap.put("result", "success"); 67 | stringStringHashMap.put("id", user.getId()); 68 | stringStringHashMap.put("name", user.getName()); 69 | stringStringHashMap.put("pathValue", c); 70 | stringStringHashMap.put("param_a_value", params.getMap().get("a")); 71 | Params p = new Params(stringStringHashMap); 72 | 73 | return Observable.just(p); 74 | 75 | } 76 | 77 | 78 | private Observable getStr(Params params, int c) { 79 | 80 | String a = String.join(":", params.getMap().keySet()); 81 | String pathValue = String.valueOf(c); 82 | return Observable.just("query name:".concat(a).concat(",pathValue:").concat(pathValue)); 83 | } 84 | 85 | public static class User { 86 | private String id; 87 | private String name; 88 | 89 | public User() { 90 | } 91 | 92 | public String getId() { 93 | return id; 94 | } 95 | 96 | public void setId(String id) { 97 | this.id = id; 98 | } 99 | 100 | public String getName() { 101 | return name; 102 | } 103 | 104 | public void setName(String name) { 105 | this.name = name; 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rxweb 2 | 3 | [![Build Status](https://travis-ci.org/zhangjessey/rxweb.svg?branch=master)](https://travis-ci.org/zhangjessey/rxweb) 4 | [![codecov](https://codecov.io/gh/zhangjessey/rxweb/branch/master/graph/badge.svg)](https://codecov.io/gh/zhangjessey/rxweb) 5 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 6 | 7 | *[rxweb](https://github.com/zhangjessey/rxweb)* based on [rxweb](https://github.com/sdeleuze/rxweb) , [smart-framework](https://gitee.com/huangyong/smart-framework) and [nano-rxnetty-mvc-server](https://bitbucket.org/gt_tech/nano-rxnetty-mvc-server/) 8 | 9 | It's a RxJava + RxNetty based micro web framework 10 | 11 | ## [中文README](https://github.com/zhangjessey/rxweb/blob/master/README-CN.md) 12 | 13 | ## Features 14 | * Annotated Route and Functional route 15 | * Supported HTTP methods - GET, POST, PUT, DELETE 16 | * Maintains non-blocking feature of RxNetty 17 | * Compatible with Java 8 18 | * MVC framework current support is limited to JSON request and responses 19 | * Supports REST URI Path variables (automatically detect path variables to be extracted from HTTP Request URI based on path definition in annotated Route or functional Route) 20 | 21 | ## Dependencies 22 | * Jackson (for JSON support) 23 | * RxNetty (includes *netty* dependencies) 24 | * RxJava 25 | * SLF4J (with static binding to Logback) 26 | * Reflections 27 | * Google Guava 28 | * lombok 29 | 30 | ## Ways to use 31 | 32 | * Run as a standalone app 33 | * User application will be required to satisfy all dependencies and start the server 34 | 35 | ## How to use 36 | ### Annotated Route 37 | 38 | ```java 39 | @Controller 40 | public class TestController { 41 | @RequestMapping.Post(value = "/postBean/{c}") 42 | public Observable postBean(@RequestBody User user, int c, Params params) { 43 | 44 | HashMap stringStringHashMap = new LinkedHashMap<>(5); 45 | stringStringHashMap.put("result", "success"); 46 | stringStringHashMap.put("id", user.getId()); 47 | stringStringHashMap.put("name", user.getName()); 48 | stringStringHashMap.put("pathValue", c); 49 | stringStringHashMap.put("param_a_value", params.getMap().get("a")); 50 | Params p = new Params(stringStringHashMap); 51 | 52 | return Observable.just(p); 53 | 54 | } 55 | } 56 | ``` 57 | 58 | ### Functional Route 59 | 60 | ```java 61 | nettyServer.get("/functionalRoute/{a}/{b}", 62 | (request, response) -> 63 | response.writeString(Observable.just("this is functionalRoute".concat(request.getUrlParams().toString())))). 64 | post("/functionalRoutePost", 65 | (request, response) -> 66 | response.writeString(Observable.just("this is functionalRoutePost"))); 67 | ``` 68 | 69 | ## Future potential enhancements 70 | *(time-permitting and if there's interest)* 71 | 72 | * @RequestMapping support multi method,not contains just one method,just like Get... 73 | * Interceptors support 74 | * Websocket support 75 | * SpringBoot starter 76 | * Support for other Mime/Types 77 | 78 | ## Contributing 79 | Contributions are highly appreciated, it is encouraged to submit a PULL request or issue. 80 | 81 | Contributors must ensure that existing test cases pass (or are modified to adjust to their changes) 82 | 83 | ## LICENSE 84 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 85 | 86 | http://www.apache.org/licenses/LICENSE-2.0 87 | 88 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 89 | -------------------------------------------------------------------------------- /src/main/java/rxweb/engine/server/netty/Dispatcher.java: -------------------------------------------------------------------------------- 1 | package rxweb.engine.server.netty; 2 | 3 | import com.google.common.collect.Multimap; 4 | import io.netty.buffer.ByteBuf; 5 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 6 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 7 | import io.reactivex.netty.protocol.http.server.RequestHandler; 8 | import rx.Observable; 9 | import rxweb.bean.WebRequest; 10 | import rxweb.mapping.Condition; 11 | import rxweb.mapping.HandlerResolver; 12 | import rxweb.server.BootstrapConfig; 13 | import rxweb.server.DefaultHandlerInvoker; 14 | import rxweb.server.DefaultHandlerResolver; 15 | import rxweb.server.Handler; 16 | import rxweb.server.NotFoundHandler; 17 | import rxweb.server.WebRequestHandler; 18 | import static rxweb.support.Constants.JSON; 19 | 20 | import java.nio.charset.Charset; 21 | import java.util.List; 22 | import java.util.Map; 23 | import java.util.regex.Matcher; 24 | import java.util.regex.Pattern; 25 | import java.util.stream.Collectors; 26 | import java.util.stream.IntStream; 27 | 28 | /** 29 | * 转发器,负责请求转发处理返回 30 | * 31 | * @author gt_tech 32 | * @author zhangjessey 33 | */ 34 | public class Dispatcher implements RequestHandler { 35 | 36 | private HandlerResolver handlerResolver = DefaultHandlerResolver.getSingleton(); 37 | 38 | private final String EMPTY_STRING = ""; 39 | 40 | @Override 41 | @SuppressWarnings("unchecked") 42 | public Observable handle(HttpServerRequest request, HttpServerResponse response) { 43 | 44 | WebRequest wreq = new WebRequest<>(request); 45 | DefaultHandlerInvoker defaultHandlerInvoker = new DefaultHandlerInvoker(); 46 | 47 | return Observable.defer(() -> request.getContent()).map(bf -> bf.toString(Charset.defaultCharset())).reduce(EMPTY_STRING, (acc, value) -> acc.concat(value)).firstOrDefault(EMPTY_STRING).map(strRequestContent -> { 48 | if (strRequestContent != null && !strRequestContent.equals(EMPTY_STRING)) { 49 | if (JSON.equals(wreq.getRequestContentType())) { 50 | wreq.setBody(strRequestContent); 51 | } 52 | } 53 | return wreq; 54 | }).map(stringWebRequest -> { 55 | for (Map.Entry, WebRequestHandler> entry : BootstrapConfig.CONDITION_REQUEST_HANDLER_MAP.entrySet()) { 56 | String path = entry.getKey().getUrl(); 57 | if (path.matches(".+\\{\\w+}.*")) { 58 | // 将请求路径中的占位符 {\w+} 转换为正则表达式 (\\w+) 59 | path = path.replaceAll("\\{\\w+}", "(\\\\w+)"); 60 | } 61 | String decodedPath = stringWebRequest.getHttpServerRequest().getDecodedPath(); 62 | Matcher matcher = Pattern.compile(path).matcher(decodedPath); 63 | if (entry.getKey().getHttpMethod().equals(stringWebRequest.getHttpServerRequest().getHttpMethod()) && matcher.matches()) { 64 | stringWebRequest.setRequestPathMatcher(matcher); 65 | stringWebRequest.setWebRequestHandler(entry.getValue()); 66 | int i = matcher.groupCount(); 67 | List> collect = IntStream.rangeClosed(1, i).mapToObj(ii -> String.class).collect(Collectors.toList()); 68 | Multimap, Object> pathParamList = defaultHandlerInvoker.createPathParamList(stringWebRequest.getRequestPathMatcher(), collect); 69 | List objects = (List) pathParamList.get(String.class); 70 | stringWebRequest.setUrlParams(objects); 71 | return stringWebRequest; 72 | } 73 | 74 | } 75 | return stringWebRequest; 76 | }).map(webRequest -> { 77 | List> resolve = handlerResolver.resolve(webRequest); 78 | if (resolve.isEmpty()) { 79 | return new NotFoundHandler(); 80 | } 81 | 82 | WebRequestHandler rh = resolve.get(0); 83 | if (rh instanceof Handler) { 84 | ((Handler) rh).setRequestBody(webRequest.getBody()); 85 | } 86 | 87 | return rh; 88 | }).flatMap(requestHandler -> requestHandler.handle(wreq, response)); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/rxweb/server/BootstrapConfig.java: -------------------------------------------------------------------------------- 1 | package rxweb.server; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.handler.codec.http.HttpMethod; 5 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 6 | import org.reflections.Reflections; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import rxweb.annotation.Controller; 10 | import rxweb.annotation.RequestBody; 11 | import rxweb.annotation.RequestMapping; 12 | import rxweb.mapping.Condition; 13 | 14 | import java.lang.annotation.Annotation; 15 | import java.lang.reflect.Method; 16 | import java.util.LinkedHashMap; 17 | import java.util.Map; 18 | import java.util.Objects; 19 | import java.util.Set; 20 | import java.util.function.Function; 21 | import java.util.stream.Collectors; 22 | 23 | 24 | /** 25 | * 初始化配置 26 | * 27 | * @author zhangjessey 28 | */ 29 | public class BootstrapConfig { 30 | 31 | private static Set> CONTROLLER_CLASS_SET; 32 | static Map, Object> CONTROLLER_CLASS_OBJECT_MAP; 33 | public static Map, WebRequestHandler> CONDITION_REQUEST_HANDLER_MAP = new LinkedHashMap<>(); 34 | 35 | 36 | static { 37 | 38 | final Logger logger = LoggerFactory.getLogger(BootstrapConfig.class); 39 | Reflections reflections = new Reflections("rxweb.sample.*"); 40 | CONTROLLER_CLASS_SET = reflections.getTypesAnnotatedWith(Controller.class); 41 | 42 | CONTROLLER_CLASS_OBJECT_MAP = CONTROLLER_CLASS_SET.stream().map(aClass -> { 43 | Object o; 44 | try { 45 | o = aClass.newInstance(); 46 | } catch (InstantiationException | IllegalAccessException e) { 47 | logger.error(e.getMessage()); 48 | return null; 49 | } 50 | return o; 51 | 52 | }).filter(Objects::nonNull).collect(Collectors.toMap(Object::getClass, Function.identity())); 53 | 54 | 55 | BootstrapConfig.CONTROLLER_CLASS_SET.forEach(aClass -> { 56 | Method[] methods = aClass.getMethods(); 57 | for (Method method : methods) { 58 | String path; 59 | Condition condition = null; 60 | 61 | Class parameterType = null; 62 | Annotation[][] parameterAnnotations = method.getParameterAnnotations(); 63 | Class[] parameterTypes = method.getParameterTypes(); 64 | int parameterCount = method.getParameterCount(); 65 | boolean needBreak = false; 66 | for (int i = 0; i < parameterCount; i++) { 67 | if (needBreak) { 68 | break; 69 | } 70 | for (Annotation annotation : parameterAnnotations[i]) { 71 | if (annotation.annotationType().isAssignableFrom(RequestBody.class)) { 72 | System.out.println(annotation.annotationType()); 73 | parameterType = parameterTypes[i]; 74 | needBreak = true; 75 | break; 76 | } 77 | } 78 | 79 | } 80 | boolean needPut = true; 81 | 82 | if (method.isAnnotationPresent(RequestMapping.Get.class)) { 83 | path = method.getAnnotation(RequestMapping.Get.class).value(); 84 | condition = new Condition<>(HttpMethod.GET, path); 85 | } else if (method.isAnnotationPresent(RequestMapping.Post.class)) { 86 | path = method.getAnnotation(RequestMapping.Post.class).value(); 87 | condition = new Condition<>(HttpMethod.POST, path); 88 | } else if (method.isAnnotationPresent(RequestMapping.Put.class)) { 89 | path = method.getAnnotation(RequestMapping.Put.class).value(); 90 | condition = new Condition<>(HttpMethod.PUT, path); 91 | } else if (method.isAnnotationPresent(RequestMapping.Delete.class)) { 92 | path = method.getAnnotation(RequestMapping.Delete.class).value(); 93 | condition = new Condition<>(HttpMethod.DELETE, path); 94 | } else { 95 | needPut = false; 96 | } 97 | 98 | if (needPut) { 99 | CONDITION_REQUEST_HANDLER_MAP.put(condition, new Handler(aClass, method, parameterType)); 100 | } 101 | } 102 | 103 | }); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/test/java/rxweb/RxJavaServerTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2002-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 | package rxweb; 18 | 19 | 20 | import org.apache.http.client.fluent.Request; 21 | import org.apache.http.entity.StringEntity; 22 | import org.junit.AfterClass; 23 | import org.junit.Assert; 24 | import org.junit.BeforeClass; 25 | import org.junit.Test; 26 | import org.slf4j.Logger; 27 | import org.slf4j.LoggerFactory; 28 | import rx.Observable; 29 | import rxweb.engine.server.netty.NettyServer; 30 | 31 | import java.io.IOException; 32 | 33 | /** 34 | * 单元测试 35 | * 36 | * @author Sebastien Deleuze 37 | * @author zhangjessey 38 | */ 39 | public class RxJavaServerTests { 40 | 41 | private static NettyServer nettyServer; 42 | private static final Logger logger = LoggerFactory.getLogger(RxJavaServerTests.class); 43 | 44 | @BeforeClass 45 | public static void setup() { 46 | nettyServer = new NettyServer(); 47 | 48 | nettyServer.get("/functionalRoute/{a}/{b}", (request, response) -> response.writeString(Observable.just("this is functionalRoute".concat(request.getUrlParams().toString())))). 49 | post("/functionalRoutePost", (request, response) -> response.writeString(Observable.just("this is functionalRoutePost"))). 50 | put("/functionalRoutePut", (request, response) -> response.writeString(Observable.just("this is functionalRoutePut"))). 51 | delete("/functionalRouteDelete", (request, response) -> response.writeString(Observable.just("this is functionalRouteDelete"))); 52 | 53 | new Thread(() -> { 54 | try { 55 | nettyServer.start(); 56 | } catch (Exception e) { 57 | logger.error(e.getMessage()); 58 | } 59 | }).start(); 60 | 61 | } 62 | 63 | @AfterClass 64 | public static void tearDown() { 65 | nettyServer.stop(); 66 | } 67 | 68 | @Test 69 | public void functionalRoute() throws Exception { 70 | 71 | String content = Request.Get("http://localhost:8080/functionalRoute/3/4").execute().returnContent().asString(); 72 | Assert.assertEquals("this is functionalRoute[3, 4]", content); 73 | content = Request.Post("http://localhost:8080/functionalRoutePost").execute().returnContent().asString(); 74 | Assert.assertEquals("this is functionalRoutePost", content); 75 | } 76 | 77 | @Test 78 | public void notfound() throws IOException { 79 | 80 | int code = Request.Get("http://localhost:8080/notfound").execute().returnResponse().getStatusLine().getStatusCode(); 81 | Assert.assertEquals(404, code); 82 | } 83 | 84 | 85 | @Test 86 | public void noParam() throws IOException { 87 | String content = Request.Get("http://localhost:8080/hi").execute().returnContent().asString(); 88 | Assert.assertEquals("hello world", content); 89 | } 90 | 91 | @Test 92 | public void withQueryParam() throws IOException { 93 | String content = Request.Get("http://localhost:8080/withQueryParam?p1=1&p2=2").execute().returnContent().asString(); 94 | Assert.assertEquals("query name:p1:p2", content); 95 | } 96 | 97 | @Test 98 | public void post() throws IOException { 99 | String content = Request.Post("http://localhost:8080/post/10?a=1").execute().returnContent().asString(); 100 | Assert.assertEquals("query name:a,pathValue:10", content); 101 | } 102 | 103 | @Test 104 | public void delete() throws IOException { 105 | String content = Request.Delete("http://localhost:8080/delete/10?a=1").execute().returnContent().asString(); 106 | Assert.assertEquals("query name:a,pathValue:10", content); 107 | } 108 | 109 | @Test 110 | public void put() throws IOException { 111 | String content = Request.Put("http://localhost:8080/put/10?a=1").execute().returnContent().asString(); 112 | Assert.assertEquals("query name:a,pathValue:10", content); 113 | } 114 | 115 | @Test 116 | public void postAndReturnBean() throws IOException { 117 | String content = Request.Post("http://localhost:8080/postAndReturnBean/10?a=1").execute().returnContent().asString(); 118 | Assert.assertEquals("{\"map\":{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}}", content); 119 | } 120 | 121 | @Test 122 | public void postBean() throws Exception { 123 | StringEntity stringEntity = new StringEntity("{\"id\":1,\"name\":\"hehe\"}"); 124 | stringEntity.setContentEncoding("UTF-8"); 125 | stringEntity.setContentType("application/json");//发送json数据需要设置contentType 126 | 127 | String content = Request.Post("http://localhost:8080/postBean/10?a=1").body(stringEntity).execute().returnContent().asString(); 128 | Assert.assertEquals("{\"map\":{\"result\":\"success\",\"id\":\"1\",\"name\":\"hehe\",\"pathValue\":10,\"param_a_value\":\"1\"}}", content); 129 | } 130 | 131 | 132 | 133 | } 134 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 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 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /src/main/java/rxweb/server/DefaultHandlerInvoker.java: -------------------------------------------------------------------------------- 1 | package rxweb.server; 2 | 3 | import com.google.common.collect.LinkedListMultimap; 4 | import com.google.common.collect.Maps; 5 | import com.google.common.collect.Multimap; 6 | import io.netty.buffer.ByteBuf; 7 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 8 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import rx.Observable; 12 | import rxweb.bean.Params; 13 | import rxweb.bean.WebRequest; 14 | import rxweb.support.DefaultConverter; 15 | 16 | import java.lang.reflect.InvocationTargetException; 17 | import java.lang.reflect.Method; 18 | import java.util.ArrayList; 19 | import java.util.Arrays; 20 | import java.util.Collection; 21 | import java.util.Collections; 22 | import java.util.List; 23 | import java.util.Map; 24 | import java.util.regex.Matcher; 25 | import java.util.stream.Collectors; 26 | import java.util.stream.IntStream; 27 | 28 | /** 29 | * 默认的HandlerInvoker 30 | * 31 | * @author huangyong 32 | * @author zhangjessey 33 | */ 34 | public class DefaultHandlerInvoker implements WebInvoker { 35 | 36 | private final Logger logger = LoggerFactory.getLogger(getClass()); 37 | 38 | 39 | @SuppressWarnings("unchecked") 40 | public Multimap, Object> createActionMethodParamList(HttpServerRequest request, Handler handler, Matcher requestPathMatcher) { 41 | 42 | Multimap, Object> pathParamMap = LinkedListMultimap.create(); 43 | // 获取Controller方法参数类型 44 | Class[] actionParamTypes = handler.getActionMethod().getParameterTypes(); 45 | // 添加路径参数列表(请求路径中的带占位符参数) 46 | if (requestPathMatcher != null) { 47 | List> collect = Arrays.stream(actionParamTypes).filter(aClass -> !aClass.isAssignableFrom(Params.class)).collect(Collectors.toList()); 48 | pathParamMap = createPathParamList(requestPathMatcher, collect); 49 | } 50 | //获取普通请求参数列表 51 | Multimap, Object> requestParamMap = getRequestParamMap(request); 52 | pathParamMap.putAll(requestParamMap); 53 | 54 | if (handler.getRequestBody() != null && handler.getRequestBodyClass() != null) { 55 | DefaultConverter defaultConverter = new DefaultConverter(); 56 | 57 | //获取requestbody参数 58 | Object deserialize = defaultConverter.deserialize((String) handler.getRequestBody(), handler.getRequestBodyClass()); 59 | pathParamMap.put(handler.getRequestBodyClass(), deserialize); 60 | } 61 | 62 | // 返回参数列表 63 | return pathParamMap; 64 | } 65 | 66 | /** 67 | * 获取普通请求参数列表(包括 Query String ,暂不包含 Form Data,multidata) 68 | */ 69 | private Multimap, Object> getRequestParamMap(HttpServerRequest request) { 70 | 71 | Multimap, Object> just = LinkedListMultimap.create(1); 72 | 73 | Map collect = request.getQueryParameters().entrySet().stream().map(stringListEntry -> Maps.immutableEntry(stringListEntry.getKey(), stringListEntry.getValue().get(stringListEntry.getValue().size() - 1))). 74 | collect(Collectors.toMap((Map.Entry o) -> (String) o.getKey(), Map.Entry::getValue)); 75 | 76 | just.put(Params.class, new Params(collect)); 77 | 78 | return just; 79 | 80 | } 81 | 82 | public Multimap, Object> createPathParamList(Matcher requestPathMatcher, List> actionParamTypes) { 83 | 84 | Multimap, Object> multiMap = LinkedListMultimap.create(); 85 | 86 | IntStream.rangeClosed(1, requestPathMatcher.groupCount()).forEach(i -> { 87 | String param = requestPathMatcher.group(i); 88 | //Class paramType = actionParamTypes[i - 1]; 89 | for (Class paramType : actionParamTypes) { 90 | if (paramType.equals(int.class) || paramType.equals(Integer.class)) { 91 | multiMap.put(int.class, Integer.valueOf(param)); 92 | actionParamTypes.remove(paramType); 93 | break; 94 | } else if (paramType.equals(long.class) || paramType.equals(Long.class)) { 95 | multiMap.put(long.class, Long.valueOf(param)); 96 | actionParamTypes.remove(paramType); 97 | break; 98 | } else if (paramType.equals(double.class) || paramType.equals(Double.class)) { 99 | multiMap.put(double.class, Double.valueOf(param)); 100 | actionParamTypes.remove(paramType); 101 | break; 102 | } else if (paramType.equals(String.class)) { 103 | multiMap.put(String.class, param); 104 | actionParamTypes.remove(paramType); 105 | break; 106 | } 107 | } 108 | 109 | }); 110 | return multiMap; 111 | } 112 | 113 | private Observable invokeActionMethod(Method actionMethod, Object actionInstance, List actionMethodParamList) throws IllegalAccessException, InvocationTargetException { 114 | // 通过反射调用 Controller 方法 115 | // 取消类型安全检测(可提高反射性能) 116 | actionMethod.setAccessible(true); 117 | Object invoke = actionMethod.invoke(actionInstance, actionMethodParamList.toArray()); 118 | return (Observable) invoke; 119 | } 120 | 121 | private List getRealParamList(Method actionMethod, Multimap, Object> actionMethodParamList) { 122 | List realParams = new ArrayList<>(); 123 | // 判断 Controller 方法参数的个数是否匹配 124 | Class[] actionMethodParameterTypes = actionMethod.getParameterTypes(); 125 | int pathLength = actionMethodParameterTypes.length; 126 | if (pathLength == 0) { 127 | actionMethodParamList.clear(); 128 | return Collections.emptyList(); 129 | } 130 | //注意:同类型按顺序匹配 131 | for (Class actionMethodParameterType : actionMethodParameterTypes) { 132 | Collection objects = actionMethodParamList.get(actionMethodParameterType); 133 | 134 | Object o = objects.stream().findFirst().orElse(actionMethodParameterType.isInstance(Object.class) ? null : 0); 135 | realParams.add(o); 136 | if (o != null) { 137 | objects.remove(o); 138 | } 139 | } 140 | return realParams; 141 | } 142 | 143 | @Override 144 | public Observable invokeHandler(WebRequest webRequest, Handler handler, HttpServerResponse response) { 145 | Matcher requestPathMatcher = webRequest.getRequestPathMatcher(); 146 | 147 | try { 148 | // 获取 Controller 相关信息 149 | Class actionClass = handler.getActionClass(); 150 | Method actionMethod = handler.getActionMethod(); 151 | // 创建 Controller 实例 152 | Object actionInstance = BootstrapConfig.CONTROLLER_CLASS_OBJECT_MAP.get(actionClass); 153 | // 创建 Controller 方法的参数列表 154 | Multimap, Object> actionMethodParamList = createActionMethodParamList(webRequest.getHttpServerRequest(), handler, requestPathMatcher); 155 | // 检查参数列表是否合法,不合法则使其合法 156 | List realParamList = getRealParamList(actionMethod, actionMethodParamList); 157 | // 调用 Controller 方法 158 | return invokeActionMethod(actionMethod, actionInstance, realParamList); 159 | } catch (Exception e) { 160 | logger.error(e.getMessage()); 161 | return null; 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------