Skip to content

Commit

Permalink
Fix unable to jump because of multiple requests on the same path
Browse files Browse the repository at this point in the history
  • Loading branch information
qianmoQ committed Apr 27, 2021
1 parent b03cdce commit e3e1d4d
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,10 @@ private static final void scanController()
NettyConfiguration.ROUTER_PRINT,
NettyConfigurationDefault.ROUTER_PRINT);
if (routerPrint) {
Routers.getRouters().entrySet().forEach(entry -> {
Router router = entry.getValue();
LOGGER.info("Mapped \"{[{}], methods {}}\" onto {}",
entry.getKey(),
router.getMethods(),
Routers.getRouters().stream().forEach(router -> {
LOGGER.info("Mapped \"{[{}], methods [{}]}\" onto {}",
router.getUrl(),
router.getRequestMethod(),
String.join(".", router.getClazz().getName(), router.getMethod().getName()));
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ else if (parameter.getAnnotation(RequestBody.class) != null) {
classList.add(parameterClass);
}
else if (ObjectUtils.isNotEmpty(parameter.getAnnotation(PathVariable.class))) {
Map<String, String> params = HttpPathHandler.getParams(request.uri(), router.getUrls().toArray(new String[0]));
Map<String, String> params = HttpPathHandler.getParams(request.uri(), new String[] {router.getUrl()});
paramList.add(getParamValue(params.get(parameter.getAnnotation(PathVariable.class).value()),
params.get(parameter.getAnnotation(PathVariable.class).defaultValue())));
classList.add(parameterClass);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io.edurt.gcm.netty.router.Routers;
import io.edurt.gcm.netty.type.Charseter;
import io.edurt.gcm.netty.type.ContentType;
import io.edurt.gcm.netty.type.RequestMethod;
import io.edurt.gcm.netty.view.ParamModel;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
Expand Down Expand Up @@ -74,7 +75,7 @@ public void triggerAction(FullHttpRequest httpRequest, FullHttpResponse httpResp
HttpCharsetContentHandler httpCharsetContentHandler = injector.getInstance(HttpCharsetContentHandler.class);
URI uri = URI.create(httpRequest.uri());
String requestUrl = uri.getPath();
Router router = Routers.getRouter(requestUrl);
Router router = Routers.getRouter(requestUrl, RequestMethod.valueOf(httpRequest.method().name()));
LOGGER.info("Obtain and analyze the client request information from {}", requestUrl);
if (ObjectUtils.isEmpty(router)) {
httpResponse.setStatus(HttpResponseStatus.NOT_FOUND);
Expand Down
5 changes: 2 additions & 3 deletions netty/src/main/java/io/edurt/gcm/netty/router/Router.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import lombok.ToString;

import java.lang.reflect.Method;
import java.util.Set;

@Data
@ToString
Expand All @@ -29,7 +28,7 @@
public class Router
{
private Class clazz;
private Set<RequestMethod> methods;
private Method method;
private Set<String> urls;
private String url;
private RequestMethod requestMethod;
}
25 changes: 7 additions & 18 deletions netty/src/main/java/io/edurt/gcm/netty/router/RouterMapping.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,18 @@
*/
package io.edurt.gcm.netty.router;

import io.edurt.gcm.common.jdk.ObjectBuilder;
import io.edurt.gcm.common.utils.ObjectUtils;
import io.edurt.gcm.netty.annotation.DeleteMapping;
import io.edurt.gcm.netty.annotation.GetMapping;
import io.edurt.gcm.netty.annotation.PostMapping;
import io.edurt.gcm.netty.annotation.PutMapping;
import io.edurt.gcm.netty.annotation.RequestMapping;
import io.edurt.gcm.netty.type.RequestMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;

public class RouterMapping
{
Expand All @@ -36,6 +35,10 @@ private RouterMapping()

public static void getMappingScan(Class<?> clazz, Method method)
{
String[] parentUrls = null;
if (clazz.isAnnotationPresent(RequestMapping.class)) {
parentUrls = clazz.getAnnotation(RequestMapping.class).value();
}
String[] mappingValues = new String[0];
RequestMethod requestMethod = null;
if (method.isAnnotationPresent(GetMapping.class)) {
Expand All @@ -62,22 +65,8 @@ public static void getMappingScan(Class<?> clazz, Method method)
return;
}
RequestMethod finalRequestMethod = requestMethod;
String[] finalParentUrls = parentUrls;
Arrays.stream(mappingValues)
.map(url -> RouterScan.getUrl(null, url))
.forEach(value -> {
Router router = ObjectBuilder.of(Router::new)
.with(Router::setMethods, new HashSet<RequestMethod>()
{{
add(finalRequestMethod);
}})
.with(Router::setMethod, method)
.with(Router::setClazz, clazz)
.with(Router::setUrls, new HashSet<String>()
{{
add(value);
}})
.build();
Routers.setRouter(value, router);
});
.forEach(url -> RouterScan.addRouter(finalParentUrls, method, clazz, finalRequestMethod, url));
}
}
56 changes: 28 additions & 28 deletions netty/src/main/java/io/edurt/gcm/netty/router/RouterScan.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,8 @@

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static java.lang.String.format;
Expand All @@ -43,11 +40,10 @@ public class RouterScan
private RouterScan()
{}

public static Map<String, Router> scanRouters(String scanPackage)
public static void scanRouters(String scanPackage)
{
LOGGER.info("Scan router from {}", scanPackage);
Set<Class<?>> classes = Classs.scanClassInPackage(scanPackage);
Map<String, Router> routers = new ConcurrentHashMap<>();
if (ObjectUtils.isEmpty(classes) || classes.size() < 1) {
LOGGER.warn("Scan router is empty from {}", scanPackage);
}
Expand Down Expand Up @@ -78,28 +74,9 @@ public static Map<String, Router> scanRouters(String scanPackage)
}
// TODO: Add to the global routing controller, and then modify the route loading method
Arrays.stream(mapping.value())
.forEach(value -> {
Set<RequestMethod> requestMethods = new HashSet<>();
Arrays.stream(mapping.method()).forEach(requestMethod -> requestMethods.add(requestMethod));
Set<String> urls = new HashSet<>();
if (ObjectUtils.isNotEmpty(finalParentUrls) && finalParentUrls.length > 0) {
Arrays.asList(finalParentUrls).forEach(parentUrl -> Arrays.stream(mapping.value())
.map(url -> getUrl(parentUrl, url))
.forEach(url -> urls.add(url)));
}
else {
Arrays.stream(mapping.value())
.map(url -> getUrl(null, url))
.forEach(url -> urls.add(url));
}
Router router = ObjectBuilder.of(Router::new)
.with(Router::setMethods, requestMethods)
.with(Router::setMethod, method)
.with(Router::setClazz, clazz)
.with(Router::setUrls, urls)
.build();
Routers.setRouter(value, router);
}
.forEach(value -> Arrays.stream(mapping.method())
.forEach(requestMethod -> Arrays.stream(mapping.value())
.forEach(url -> addRouter(finalParentUrls, method, clazz, requestMethod, url)))
);
}
else {
Expand All @@ -113,7 +90,6 @@ public static Map<String, Router> scanRouters(String scanPackage)
}
});
}
return routers;
}

public static String getUrl(String parentUrl, String url)
Expand All @@ -133,4 +109,28 @@ public static String getUrl(String parentUrl, String url)
}
return url;
}

public static void addRouter(String[] parentUrls, Method method, Class clazz, RequestMethod requestMethod, String url)
{
if (ObjectUtils.isNotEmpty(parentUrls) && parentUrls.length > 0) {
Arrays.asList(parentUrls).forEach(parentUrl -> {
Router router = ObjectBuilder.of(Router::new)
.with(Router::setMethod, method)
.with(Router::setClazz, clazz)
.with(Router::setRequestMethod, requestMethod)
.with(Router::setUrl, getUrl(parentUrl, url))
.build();
Routers.setRouter(router);
});
}
else {
Router router = ObjectBuilder.of(Router::new)
.with(Router::setMethod, method)
.with(Router::setClazz, clazz)
.with(Router::setRequestMethod, requestMethod)
.with(Router::setUrl, getUrl(null, url))
.build();
Routers.setRouter(router);
}
}
}
42 changes: 22 additions & 20 deletions netty/src/main/java/io/edurt/gcm/netty/router/Routers.java
Original file line number Diff line number Diff line change
@@ -1,58 +1,60 @@
package io.edurt.gcm.netty.router;

import io.edurt.gcm.common.utils.ObjectUtils;
import io.edurt.gcm.common.utils.StringUtils;
import io.edurt.gcm.netty.handler.HttpPathHandler;
import io.edurt.gcm.netty.type.RequestMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

public class Routers
{
private static final Logger LOGGER = LoggerFactory.getLogger(Routers.class);
/**
* Buffering all routes in the server
*/
private static final HashMap<String, Router> ROUTERS = new HashMap<>(256);
private static final Set<Router> ROUTERS = new HashSet<>(256);

private Routers()
{}

/**
* Add route buffer information
*
* @param path Routing access address
* @param router Basic routing information
*/
public static final void setRouter(final String path, final Router router)
public static final void setRouter(final Router router)
{
if (StringUtils.isEmpty(path) || ObjectUtils.isEmpty(router)) {
if (ObjectUtils.isEmpty(router)) {
LOGGER.warn("Load router path or router must not null");
return;
}
ROUTERS.put(path, router);
ROUTERS.add(router);
}

public static final Router getRouter(String path)
public static final Router getRouter(String url, RequestMethod requestMethod)
{
Router router = ROUTERS.get(path);
// When the route is not extracted, the path matching parameter pattern extraction is used
if (ObjectUtils.isEmpty(router)) {
Optional<Map.Entry<String, Router>> routerEntry = ROUTERS.entrySet()
.stream()
.filter(entry -> HttpPathHandler.verify(path, entry.getKey()))
.findFirst();
if (routerEntry.isPresent()) {
router = routerEntry.get().getValue();
}
Optional<Router> routerOptional = Routers.ROUTERS.stream()
.filter(router1 -> router1.getRequestMethod().equals(requestMethod) && router1.getUrl().equals(url))
.findAny();
if (routerOptional.isPresent()) {
return routerOptional.get();
}
// Filter PathVariable
Optional<Router> pathVariableOptional = Routers.ROUTERS.stream()
.filter(router1 -> HttpPathHandler.verify(url, router1.getUrl()))
.findAny();
if (pathVariableOptional.isPresent()) {
return pathVariableOptional.get();
}
return router;
return null;
}

public static final HashMap<String, Router> getRouters()
public static final Set<Router> getRouters()
{
return ROUTERS;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.edurt.gcm.netty.controller;

import io.edurt.gcm.netty.annotation.GetMapping;
import io.edurt.gcm.netty.annotation.PostMapping;
import io.edurt.gcm.netty.annotation.RequestBody;
import io.edurt.gcm.netty.annotation.RequestParam;
import io.edurt.gcm.netty.annotation.RestController;
import io.edurt.gcm.netty.model.TestModel;

@RestController
public class TestIssues35Controller
{
@GetMapping("issues/35")
public String getIssues35(@RequestParam(value = "value") String value)
{
return "Get Issues 35 : " + value;
}

@PostMapping("issues/35")
public Object postIssues35(@RequestBody TestModel model)
{
return "Post Issues 35 : " + model;
}
}

0 comments on commit e3e1d4d

Please sign in to comment.