Skip to content

Commit

Permalink
代码优化
Browse files Browse the repository at this point in the history
  • Loading branch information
smthing committed Aug 11, 2024
1 parent 0a31215 commit a44c661
Show file tree
Hide file tree
Showing 26 changed files with 180 additions and 213 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@
import tech.smartboot.servlet.conf.FilterInfo;
import tech.smartboot.servlet.conf.FilterMappingInfo;
import tech.smartboot.servlet.conf.ServletInfo;
import tech.smartboot.servlet.conf.ServletMappingInfo;
import tech.smartboot.servlet.enums.FilterMappingType;
import tech.smartboot.servlet.third.bcel.Const;
import tech.smartboot.servlet.third.bcel.classfile.AnnotationEntry;
import tech.smartboot.servlet.third.bcel.classfile.ClassParser;
import tech.smartboot.servlet.third.bcel.classfile.JavaClass;
import tech.smartboot.servlet.util.CollectionUtils;
import tech.smartboot.servlet.util.PathMatcherUtil;

import java.io.File;
import java.io.FileInputStream;
Expand Down Expand Up @@ -58,14 +58,12 @@
* @version V1.0 , 2021/6/27
*/
public class AnnotationsLoader {
private final Map<ServletContainerInitializer, Set<Class<?>>> initializerClassMap =
new LinkedHashMap<>();
private final Map<ServletContainerInitializer, Set<Class<?>>> initializerClassMap = new LinkedHashMap<>();
/**
* Map of Types to ServletContainerInitializer that are interested in those
* types.
*/
private final Map<Class<?>, Set<ServletContainerInitializer>> typeInitializerMap =
new HashMap<>();
private final Map<Class<?>, Set<ServletContainerInitializer>> typeInitializerMap = new HashMap<>();
private final ClassLoader classLoader;
/**
* Flag that indicates if at least one {@link HandlesTypes} entry is present
Expand All @@ -81,7 +79,9 @@ public class AnnotationsLoader {
private final Map<Class, List<String>> annotations = new HashMap<>();

private final Map<String, ServletInfo> servlets = new HashMap<>();
private final Map<String, FilterInfo> filters = new HashMap<>();
private final List<ServletMappingInfo> servletMappings = new ArrayList<>();
private final List<FilterInfo> filters = new ArrayList<>();
private final List<FilterMappingInfo> filterMappings = new ArrayList<>();

public AnnotationsLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
Expand Down Expand Up @@ -118,8 +118,7 @@ public void scanAnnotations() {
processAnnotationsJar(url, javaClassCache);
} else if ("file".equals(url.getProtocol())) {
try {
processAnnotationsFile(
new File(url.toURI()), javaClassCache);
processAnnotationsFile(new File(url.toURI()), javaClassCache);
} catch (URISyntaxException e) {
e.printStackTrace();
}
Expand Down Expand Up @@ -147,7 +146,7 @@ public Map<String, ServletInfo> getServlets() {
return servlets;
}

public Map<String, FilterInfo> getFilters() {
public List<FilterInfo> getFilters() {
return filters;
}

Expand Down Expand Up @@ -209,8 +208,7 @@ private void processAnnotationsFile(File file, Map<String, JavaClassCacheEntry>
/**
* 检查是否包含待加载的注解
*/
private void checkAnnotation(JavaClass javaClass,
Map<String, JavaClassCacheEntry> javaClassCache) throws ClassNotFoundException {
private void checkAnnotation(JavaClass javaClass, Map<String, JavaClassCacheEntry> javaClassCache) throws ClassNotFoundException {
if ((javaClass.getAccessFlags() & Const.ACC_ANNOTATION) != 0) {
// Skip annotations.
return;
Expand Down Expand Up @@ -240,20 +238,12 @@ private void checkAnnotation(JavaClass javaClass,
}
Set<DispatcherType> set = new HashSet<>(Arrays.asList(webFilter.dispatcherTypes()));
for (String urlPattern : webFilter.urlPatterns()) {
FilterMappingInfo filterMappingInfo =
new FilterMappingInfo(name,
FilterMappingType.URL, null, PathMatcherUtil.addMapping(urlPattern),
set);
filterInfo.addMapping(filterMappingInfo);
filterMappings.add(new FilterMappingInfo(name, FilterMappingType.URL, null, urlPattern, set));
}
for (String servletName : webFilter.servletNames()) {
FilterMappingInfo filterMappingInfo =
new FilterMappingInfo(name,
FilterMappingType.SERVLET, servletName, null,
set);
filterInfo.addMapping(filterMappingInfo);
filterMappings.add(new FilterMappingInfo(name, FilterMappingType.SERVLET, servletName, null, set));
}
filters.put(name, filterInfo);
filters.add(filterInfo);
} else if (WebServlet.class.getName().equals(annotationName)) {
Class<?> clazz = classLoader.loadClass(className);
WebServlet webServlet = clazz.getAnnotation(WebServlet.class);
Expand All @@ -270,10 +260,10 @@ private void checkAnnotation(JavaClass javaClass,
servletInfo.addInitParam(param.name(), param.value());
}
for (String urlPattern : webServlet.urlPatterns()) {
servletInfo.addMapping(urlPattern);
servletMappings.add(new ServletMappingInfo(name, urlPattern));
}
for (String url : webServlet.value()) {
servletInfo.addMapping(url);
servletMappings.add(new ServletMappingInfo(name, url));
}
ServletSecurity servletSecurity = clazz.getAnnotation(ServletSecurity.class);
// if (servletSecurity != null) {
Expand Down Expand Up @@ -313,16 +303,14 @@ private void checkAnnotation(JavaClass javaClass,

AnnotationEntry[] annotationEntries = javaClass.getAnnotationEntries();
if (handlesTypesAnnotations && annotationEntries != null) {
for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry :
typeInitializerMap.entrySet()) {
for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry : typeInitializerMap.entrySet()) {
//当前类非注解
if (!entry.getKey().isAnnotation()) {
continue;
}
String entryClassName = entry.getKey().getName();
for (AnnotationEntry annotationEntry : annotationEntries) {
if (!entryClassName.equals(
getClassName(annotationEntry.getAnnotationType()))) {
if (!entryClassName.equals(getClassName(annotationEntry.getAnnotationType()))) {
continue;
}
if (clazz == null) {
Expand All @@ -343,8 +331,7 @@ private void checkAnnotation(JavaClass javaClass,
}
}

private void populateSCIsForCacheEntry(JavaClassCacheEntry cacheEntry,
Map<String, JavaClassCacheEntry> javaClassCache) {
private void populateSCIsForCacheEntry(JavaClassCacheEntry cacheEntry, Map<String, JavaClassCacheEntry> javaClassCache) {
Set<ServletContainerInitializer> result = new HashSet<>();

// Super class
Expand Down Expand Up @@ -385,8 +372,7 @@ private void populateSCIsForCacheEntry(JavaClassCacheEntry cacheEntry,
}

private Set<ServletContainerInitializer> getSCIsForClass(String className) {
for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry :
typeInitializerMap.entrySet()) {
for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry : typeInitializerMap.entrySet()) {
Class<?> clazz = entry.getKey();
if (!clazz.isAnnotation()) {
if (clazz.getName().equals(className)) {
Expand All @@ -398,8 +384,7 @@ private Set<ServletContainerInitializer> getSCIsForClass(String className) {
}


private void populateJavaClassCache(String className, JavaClass javaClass,
Map<String, JavaClassCacheEntry> javaClassCache) {
private void populateJavaClassCache(String className, JavaClass javaClass, Map<String, JavaClassCacheEntry> javaClassCache) {
if (javaClassCache.containsKey(className) || className.startsWith("java") || className.startsWith("sun.")) {
return;
}
Expand All @@ -422,8 +407,7 @@ private void populateJavaClassCache(String className, JavaClass javaClass,
* @param className
* @param javaClassCache
*/
private void populateJavaClassCache(String className,
Map<String, JavaClassCacheEntry> javaClassCache) {
private void populateJavaClassCache(String className, Map<String, JavaClassCacheEntry> javaClassCache) {
if (javaClassCache.containsKey(className)) {
return;
}
Expand All @@ -446,8 +430,7 @@ private String getClassName(String internalForm) {
}

// Assume starts with L, ends with ; and uses / rather than .
return internalForm.substring(1,
internalForm.length() - 1).replace('/', '.');
return internalForm.substring(1, internalForm.length() - 1).replace('/', '.');
}

static class JavaClassCacheEntry {
Expand Down
16 changes: 4 additions & 12 deletions servlet-core/src/main/java/tech/smartboot/servlet/Container.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import tech.smartboot.servlet.conf.DeploymentInfo;
import tech.smartboot.servlet.conf.FilterInfo;
import tech.smartboot.servlet.conf.OrderMeta;
import tech.smartboot.servlet.conf.ServletInfo;
import tech.smartboot.servlet.conf.ServletMappingInfo;
import tech.smartboot.servlet.conf.WebAppInfo;
import tech.smartboot.servlet.conf.WebFragmentInfo;
Expand Down Expand Up @@ -55,7 +54,6 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
Expand Down Expand Up @@ -260,8 +258,8 @@ public void doHandle(HttpRequest request, HttpResponse response, CompletableFutu
HttpServletResponseImpl servletResponse = new HttpServletResponseImpl(servletRequest, response);
servletRequest.setHttpServletResponse(servletResponse);
HandlerContext handlerContext = new HandlerContext(servletRequest, servletResponse, runtime.getServletContext(), false);
ServletMappingInfo servletMappingInfo = runtime.getMappingProvider().match(servletRequest.getRequestURI());
handlerContext.setServletInfo(servletMappingInfo.getServletInfo());
ServletMappingInfo servletMappingInfo = runtime.getMappingProvider().matchServlet(servletRequest.getRequestURI());
handlerContext.setServletInfo(runtime.getDeploymentInfo().getServlets().get(servletMappingInfo.getServletName()));
servletRequest.setServletMappingInfo(servletMappingInfo);
runtime.getVendorProvider().signature(servletResponse);
// just do it
Expand Down Expand Up @@ -387,14 +385,6 @@ private ServletContextRuntime getServletRuntime(String localPath, String context
}
}

webAppInfo.getFilterMappingInfos().forEach(filterMappingInfo -> {
Optional<FilterInfo> optional = webAppInfo.getFilters().stream().filter(filter -> filterMappingInfo.getFilterName().equals(filter.getFilterName())).findFirst();
if (optional.isPresent()) {
optional.get().addMapping(filterMappingInfo);
} else {
LOGGER.error("invalid filterMapping:{}", filterMappingInfo);
}
});

//new runtime object
servletRuntime.setDisplayName(webAppInfo.getDisplayName());
Expand All @@ -403,11 +393,13 @@ private ServletContextRuntime getServletRuntime(String localPath, String context
//set session timeout
deploymentInfo.setSessionTimeout(webAppInfo.getSessionTimeout());
//register Servlet into deploymentInfo
webAppInfo.getServletMappings().forEach(deploymentInfo::addServletMapping);
webAppInfo.getServlets().values().forEach(deploymentInfo::addServlet);

webAppInfo.getErrorPages().forEach(deploymentInfo::addErrorPage);

//register Filter
webAppInfo.getFilterMappingInfos().forEach(deploymentInfo::addFilterMapping);
for (FilterInfo filterInfo : webAppInfo.getFilters()) {
deploymentInfo.addFilter(filterInfo);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import org.smartboot.http.common.utils.Mimetypes;
import org.smartboot.http.common.utils.StringUtils;
import tech.smartboot.servlet.conf.DeploymentInfo;
import tech.smartboot.servlet.conf.ServletInfo;
import tech.smartboot.servlet.exception.WrappedRuntimeException;

import java.io.File;
Expand Down Expand Up @@ -224,7 +223,7 @@ private String matchForwardWelcome(HttpServletRequest request) throws MalformedU
return uri + file;
}
//是否匹配 Servlet url-pattern
if (deploymentInfo.getServlets().values().stream().map(ServletInfo::getMappings).anyMatch(list -> list.stream().anyMatch(mapping -> mapping.getMapping().equals("/" + file)))) {
if (deploymentInfo.getServletMappings().stream().anyMatch(mapping -> mapping.getMapping().equals("/" + file))) {
return file;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import tech.smartboot.servlet.conf.FilterInfo;
import tech.smartboot.servlet.conf.ServletContainerInitializerInfo;
import tech.smartboot.servlet.conf.ServletInfo;
import tech.smartboot.servlet.conf.ServletMappingInfo;
import tech.smartboot.servlet.impl.FilterConfigImpl;
import tech.smartboot.servlet.impl.ServletContextImpl;
import tech.smartboot.servlet.impl.ServletContextWrapperListener;
Expand Down Expand Up @@ -172,11 +173,7 @@ public void start() throws Throwable {
}

private void newServletsInstance(DeploymentInfo deploymentInfo) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
boolean noneDefault = true;
for (ServletInfo servletInfo : deploymentInfo.getServlets().values()) {
if (servletInfo.getMappings().stream().anyMatch(servletMappingInfo -> "/".equals(servletMappingInfo.getMapping()))) {
noneDefault = false;
}
if (servletInfo.isDynamic()) {
continue;
}
Expand All @@ -189,14 +186,14 @@ private void newServletsInstance(DeploymentInfo deploymentInfo) throws Instantia
servletInfo.setServlet(servlet);
}
//绑定 default Servlet
if (noneDefault) {
if (deploymentInfo.getServletMappings().stream().noneMatch(mapping -> mapping.getMapping().equals("/"))) {
ServletInfo servletInfo = new ServletInfo();
servletInfo.setServletName(ServletInfo.DEFAULT_SERVLET_NAME);
servletInfo.setServlet(new DefaultServlet(deploymentInfo));
servletInfo.setDynamic(true);
servletInfo.setLoadOnStartup(1);
servletInfo.addMapping("/");
deploymentInfo.addServlet(servletInfo);
deploymentInfo.addServletMapping(new ServletMappingInfo(ServletInfo.DEFAULT_SERVLET_NAME, "/"));
}


Expand Down Expand Up @@ -231,7 +228,7 @@ private void initContainer(DeploymentInfo deploymentInfo) throws ServletExceptio
deploymentInfo.addServlet(servletInfo);
}
});
deploymentInfo.getHandlesTypesLoader().getFilters().values().forEach(filterInfo -> {
deploymentInfo.getHandlesTypesLoader().getFilters().forEach(filterInfo -> {
deploymentInfo.addFilter(filterInfo);
});
deploymentInfo.getHandlesTypesLoader().clear();
Expand Down Expand Up @@ -278,7 +275,7 @@ private void initServlet(DeploymentInfo deploymentInfo) throws Exception {
* @param deploymentInfo 部署信息
*/
private void initFilter(DeploymentInfo deploymentInfo) throws Exception {
for (FilterInfo filterInfo : deploymentInfo.getFilters()) {
for (FilterInfo filterInfo : deploymentInfo.getFilters().values()) {
FilterConfig filterConfig = new FilterConfigImpl(filterInfo, servletContext);
Filter filter;
if (filterInfo.isDynamic()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
import tech.smartboot.servlet.conf.OrderMeta;
import tech.smartboot.servlet.conf.SecurityConstraint;
import tech.smartboot.servlet.conf.ServletInfo;
import tech.smartboot.servlet.conf.ServletMappingInfo;
import tech.smartboot.servlet.conf.WebAppInfo;
import tech.smartboot.servlet.conf.WebFragmentInfo;
import tech.smartboot.servlet.enums.FilterMappingType;
import tech.smartboot.servlet.util.CollectionUtils;
import tech.smartboot.servlet.util.PathMatcherUtil;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
Expand Down Expand Up @@ -230,7 +230,7 @@ private void parseFilterMapping(WebAppInfo webAppInfo, Element parentElement) {
} else {
dispatcher.forEach(dispatcherElement -> dispatcherTypes.add(DispatcherType.valueOf(StringUtils.trim(dispatcherElement.getFirstChild().getNodeValue()))));
}
FilterMappingInfo filterInfo = new FilterMappingInfo(filterName, StringUtils.isBlank(urlPattern) ? FilterMappingType.SERVLET : FilterMappingType.URL, servletName, StringUtils.isBlank(urlPattern) ? null : PathMatcherUtil.addMapping(urlPattern), dispatcherTypes);
FilterMappingInfo filterInfo = new FilterMappingInfo(filterName, StringUtils.isBlank(urlPattern) ? FilterMappingType.SERVLET : FilterMappingType.URL, servletName, urlPattern, dispatcherTypes);
webAppInfo.getFilterMappingInfos().add(filterInfo);
}
}
Expand Down Expand Up @@ -306,8 +306,8 @@ private void parseServletMapping(WebAppInfo webAppInfo, Element parentElement) {
List<Node> childNodeList = getChildNodes(parentElement, "servlet-mapping");
for (Node node : childNodeList) {
Map<String, String> nodeData = getNodeValue(node, Collections.singletonList("servlet-name"));
ServletInfo servletInfo = webAppInfo.getServlet(nodeData.get("servlet-name"));
getNodeValues(node, "url-pattern").forEach(servletInfo::addMapping);
String servletName = nodeData.get("servlet-name");
getNodeValues(node, "url-pattern").forEach(urlPattern -> webAppInfo.getServletMappings().add(new ServletMappingInfo(servletName, urlPattern)));
}
}

Expand Down
Loading

0 comments on commit a44c661

Please sign in to comment.