修正regx为regex

This commit is contained in:
redkale
2024-06-29 16:32:03 +08:00
parent def85ca1ac
commit 8136345484
19 changed files with 196 additions and 176 deletions

View File

@@ -1,30 +1,30 @@
handlers = java.util.logging.ConsoleHandler,java.util.logging.FileHandler handlers = java.util.logging.ConsoleHandler,java.util.logging.FileHandler
.handlers = java.util.logging.ConsoleHandler,java.util.logging.FileHandler .handlers = java.util.logging.ConsoleHandler,java.util.logging.FileHandler
############################################################ ############################################################
.level = FINE .level = FINE
sun.level = INFO sun.level = INFO
java.level = INFO java.level = INFO
javax.level = INFO javax.level = INFO
com.sun.level = INFO com.sun.level = INFO
#java.util.logging.FileHandler.level = FINE #java.util.logging.FileHandler.level = FINE
java.util.logging.FileHandler.limit = 20M java.util.logging.FileHandler.limit = 20M
java.util.logging.FileHandler.count = 100 java.util.logging.FileHandler.count = 100
java.util.logging.FileHandler.encoding = UTF-8 java.util.logging.FileHandler.encoding = UTF-8
java.util.logging.FileHandler.pattern = ${APP_HOME}/logs-%tY%tm/log-%tY%tm%td.log java.util.logging.FileHandler.pattern = ${APP_HOME}/logs-%tY%tm/log-%tY%tm%td.log
#java.util.logging.FileHandler.unusual \u5c5e\u6027\u8868\u793a\u5c06 WARNING\u3001SEVERE \u7ea7\u522b\u7684\u65e5\u5fd7\u590d\u5236\u5199\u5165\u5355\u72ec\u7684\u6587\u4ef6\u4e2d #java.util.logging.FileHandler.unusual \u5c5e\u6027\u8868\u793a\u5c06 WARNING\u3001SEVERE \u7ea7\u522b\u7684\u65e5\u5fd7\u590d\u5236\u5199\u5165\u5355\u72ec\u7684\u6587\u4ef6\u4e2d
java.util.logging.FileHandler.unusual = ${APP_HOME}/logs-%tY%tm/log-warnerr-%tY%tm%td.log java.util.logging.FileHandler.unusual = ${APP_HOME}/logs-%tY%tm/log-warnerr-%tY%tm%td.log
#\u9700\u8981\u5c4f\u853d\u6d88\u606f\u5185\u5bb9\u7684\u6b63\u5219\u8868\u8fbe\u5f0f #\u9700\u8981\u5c4f\u853d\u6d88\u606f\u5185\u5bb9\u7684\u6b63\u5219\u8868\u8fbe\u5f0f
java.util.logging.FileHandler.denyregx = java.util.logging.FileHandler.denyregex =
java.util.logging.FileHandler.append = true java.util.logging.FileHandler.append = true
#java.util.logging.ConsoleHandler.level = FINE #java.util.logging.ConsoleHandler.level = FINE
#\u5c06\u65e5\u5fd7\u5199\u8fdbSearchSource, \u5fc5\u987b\u6307\u5b9asource\u8d44\u6e90\u540d\uff0c\u5728source.properties\u4e2d\u5b9a\u4e49 #\u5c06\u65e5\u5fd7\u5199\u8fdbSearchSource, \u5fc5\u987b\u6307\u5b9asource\u8d44\u6e90\u540d\uff0c\u5728source.properties\u4e2d\u5b9a\u4e49
#java.util.logging.SearchHandler.source = platfsearch #java.util.logging.SearchHandler.source = platfsearch
#\u6307\u5b9a\u5199\u8fdbSearchSource\u7684\u8868\u540d\uff0c\u9ed8\u8ba4\u503c\u4e3alog-record #\u6307\u5b9a\u5199\u8fdbSearchSource\u7684\u8868\u540d\uff0c\u9ed8\u8ba4\u503c\u4e3alog-record
#java.util.logging.SearchHandler.tag = log-${APP_NAME}-%tY%tm%td #java.util.logging.SearchHandler.tag = log-${APP_NAME}-%tY%tm%td

View File

@@ -96,22 +96,22 @@ public final class ClassFilter<T> {
this.classLoader = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader; this.classLoader = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader;
} }
public static ClassFilter create(String includeRegxs, String excludeRegxs) { public static ClassFilter create(String includeRegexs, String excludeRegexs) {
return create(null, null, includeRegxs, excludeRegxs, null, null); return create(null, null, includeRegexs, excludeRegexs, null, null);
} }
public static ClassFilter create( public static ClassFilter create(
RedkaleClassLoader classLoader, RedkaleClassLoader classLoader,
Class[] excludeSuperClasses, Class[] excludeSuperClasses,
String includeRegxs, String includeRegexs,
String excludeRegxs, String excludeRegexs,
Set<String> includeValues, Set<String> includeValues,
Set<String> excludeValues) { Set<String> excludeValues) {
ClassFilter filter = new ClassFilter(classLoader, null, null, excludeSuperClasses); ClassFilter filter = new ClassFilter(classLoader, null, null, excludeSuperClasses);
filter.setIncludePatterns( filter.setIncludePatterns(
includeRegxs == null ? null : includeRegxs.replace(',', ';').split(";")); includeRegexs == null ? null : includeRegexs.replace(',', ';').split(";"));
filter.setExcludePatterns( filter.setExcludePatterns(
excludeRegxs == null ? null : excludeRegxs.replace(',', ';').split(";")); excludeRegexs == null ? null : excludeRegexs.replace(',', ';').split(";"));
filter.setPrivilegeIncludes(includeValues); filter.setPrivilegeIncludes(includeValues);
filter.setPrivilegeExcludes(excludeValues); filter.setPrivilegeExcludes(excludeValues);
return filter; return filter;
@@ -385,17 +385,17 @@ public final class ClassFilter<T> {
return rs; return rs;
} }
public static Pattern[] toPattern(String[] regxs) { public static Pattern[] toPattern(String[] regexs) {
if (regxs == null || regxs.length == 0) { if (regexs == null || regexs.length == 0) {
return null; return null;
} }
int i = 0; int i = 0;
Pattern[] rs = new Pattern[regxs.length]; Pattern[] rs = new Pattern[regexs.length];
for (String regx : regxs) { for (String regex : regexs) {
if (regx == null || regx.trim().isEmpty()) { if (regex == null || regex.trim().isEmpty()) {
continue; continue;
} }
rs[i++] = Pattern.compile(formatPackageRegx(regx.trim())); rs[i++] = Pattern.compile(formatPackageRegex(regex.trim()));
} }
if (i == 0) { if (i == 0) {
return null; return null;
@@ -415,14 +415,14 @@ public final class ClassFilter<T> {
* 例如: * 例如:
* *.platf.** 转成 ^(\w+)\.platf\.(.*)$ * *.platf.** 转成 ^(\w+)\.platf\.(.*)$
* *
* @param regx 正则表达式 * @param regex 正则表达式
* @return Pattern * @return Pattern
*/ */
public static String formatPackageRegx(String regx) { public static String formatPackageRegex(String regex) {
if (regx.indexOf('^') >= 0 || regx.indexOf('$') >= 0 || regx.indexOf('\\') >= 0) { // 已经是标准正则表达式 if (regex.indexOf('^') >= 0 || regex.indexOf('$') >= 0 || regex.indexOf('\\') >= 0) { // 已经是标准正则表达式
return regx; return regex;
} }
String str = regx.replace("**", sxing).replace("*", dxing); String str = regex.replace("**", sxing).replace("*", dxing);
str = str.replace("\\.", dian).replace(".", dian); str = str.replace("\\.", dian).replace(".", dian);
return "^" + str.replace(dian, "\\.").replace(dxing, "(\\w+)").replace(sxing, "(.*)") + "$"; return "^" + str.replace(dian, "\\.").replace(dxing, "(\\w+)").replace(sxing, "(.*)") + "$";
} }

View File

@@ -5,10 +5,9 @@
*/ */
package org.redkale.boot; package org.redkale.boot;
import static java.nio.file.StandardCopyOption.*;
import java.io.*; import java.io.*;
import java.nio.file.Files; import java.nio.file.Files;
import static java.nio.file.StandardCopyOption.*;
import java.util.Calendar; import java.util.Calendar;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.*; import java.util.concurrent.atomic.*;
@@ -37,7 +36,7 @@ public class LoggingFileHandler extends LoggingBaseHandler {
public static class LoggingConsoleHandler extends ConsoleHandler { public static class LoggingConsoleHandler extends ConsoleHandler {
private Pattern denyRegx; private Pattern denyRegex;
public LoggingConsoleHandler() { public LoggingConsoleHandler() {
super(); super();
@@ -47,13 +46,13 @@ public class LoggingFileHandler extends LoggingBaseHandler {
private void configure() { private void configure() {
LogManager manager = LogManager.getLogManager(); LogManager manager = LogManager.getLogManager();
String denyregxstr = manager.getProperty(LoggingConsoleHandler.class.getName() + ".denyregx"); String denyregexstr = manager.getProperty(LoggingConsoleHandler.class.getName() + ".denyregex");
if (denyregxstr == null) { if (denyregexstr == null) {
denyregxstr = manager.getProperty("java.util.logging.ConsoleHandler.denyregx"); denyregexstr = manager.getProperty("java.util.logging.ConsoleHandler.denyregex");
} }
try { try {
if (denyregxstr != null && !denyregxstr.trim().isEmpty()) { if (denyregexstr != null && !denyregexstr.trim().isEmpty()) {
this.denyRegx = Pattern.compile(denyregxstr); this.denyRegex = Pattern.compile(denyregexstr);
} }
} catch (Exception e) { } catch (Exception e) {
// do nothing // do nothing
@@ -62,7 +61,7 @@ public class LoggingFileHandler extends LoggingBaseHandler {
@Override @Override
public void publish(LogRecord log) { public void publish(LogRecord log) {
if (denyRegx != null && denyRegx.matcher(log.getMessage()).find()) { if (denyRegex != null && denyRegex.matcher(log.getMessage()).find()) {
return; return;
} }
fillLogRecord(log); fillLogRecord(log);
@@ -92,7 +91,7 @@ public class LoggingFileHandler extends LoggingBaseHandler {
protected boolean append; protected boolean append;
protected Pattern denyRegx; protected Pattern denyRegex;
private final AtomicLong logLength = new AtomicLong(); private final AtomicLong logLength = new AtomicLong();
@@ -351,10 +350,10 @@ public class LoggingFileHandler extends LoggingBaseHandler {
// do nothing // do nothing
} }
String denyregxstr = manager.getProperty(cname + ".denyregx"); String denyregexstr = manager.getProperty(cname + ".denyregex");
try { try {
if (denyregxstr != null && !denyregxstr.trim().isEmpty()) { if (denyregexstr != null && !denyregexstr.trim().isEmpty()) {
denyRegx = Pattern.compile(denyregxstr); denyRegex = Pattern.compile(denyregexstr);
} }
} catch (Exception e) { } catch (Exception e) {
// do nothing // do nothing
@@ -366,7 +365,7 @@ public class LoggingFileHandler extends LoggingBaseHandler {
if (!isLoggable(log)) { if (!isLoggable(log)) {
return; return;
} }
if (denyRegx != null && denyRegx.matcher(log.getMessage()).find()) { if (denyRegex != null && denyRegex.matcher(log.getMessage()).find()) {
return; return;
} }
fillLogRecord(log); fillLogRecord(log);

View File

@@ -2,9 +2,6 @@
*/ */
package org.redkale.boot; package org.redkale.boot;
import static org.redkale.boot.Application.RESNAME_APP_NAME;
import static org.redkale.boot.Application.SYSNAME_APP_NAME;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
@@ -12,6 +9,8 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.*; import java.util.logging.*;
import java.util.logging.Formatter; import java.util.logging.Formatter;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static org.redkale.boot.Application.RESNAME_APP_NAME;
import static org.redkale.boot.Application.SYSNAME_APP_NAME;
import org.redkale.convert.*; import org.redkale.convert.*;
import org.redkale.convert.json.JsonConvert; import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.*; import org.redkale.persistence.*;
@@ -41,7 +40,7 @@ public class LoggingSearchHandler extends LoggingBaseHandler {
protected String pattern; protected String pattern;
protected Pattern denyRegx; protected Pattern denyRegex;
protected String sourceResourceName; protected String sourceResourceName;
@@ -210,10 +209,10 @@ public class LoggingSearchHandler extends LoggingBaseHandler {
// do nothing // do nothing
} }
String denyRegxStr = manager.getProperty(cname + ".denyregx"); String denyRegexStr = manager.getProperty(cname + ".denyregex");
try { try {
if (denyRegxStr != null && !denyRegxStr.trim().isEmpty()) { if (denyRegexStr != null && !denyRegexStr.trim().isEmpty()) {
denyRegx = Pattern.compile(denyRegxStr); denyRegex = Pattern.compile(denyRegexStr);
} }
} catch (Exception e) { } catch (Exception e) {
// do nothing // do nothing
@@ -225,7 +224,7 @@ public class LoggingSearchHandler extends LoggingBaseHandler {
if (!isLoggable(log)) { if (!isLoggable(log)) {
return; return;
} }
if (denyRegx != null && denyRegx.matcher(log.getMessage()).find()) { if (denyRegex != null && denyRegex.matcher(log.getMessage()).find()) {
return; return;
} }
if (log.getSourceClassName() != null) { if (log.getSourceClassName() != null) {

View File

@@ -33,7 +33,7 @@ public class FilterWatchService extends AbstractWatchService {
@RestMapping(name = "addFilter", auth = false, comment = "动态增加Filter") @RestMapping(name = "addFilter", auth = false, comment = "动态增加Filter")
public RetResult addFilter( public RetResult addFilter(
@RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameRegx = "\\.jar$") byte[] jar, @RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameRegex = "\\.jar$") byte[] jar,
@RestParam(name = "server", comment = "Server节点名") final String serverName, @RestParam(name = "server", comment = "Server节点名") final String serverName,
@RestParam(name = "type", comment = "Filter类名") final String filterType) @RestParam(name = "type", comment = "Filter类名") final String filterType)
throws IOException { throws IOException {

View File

@@ -231,7 +231,7 @@ public class ServiceWatchService extends AbstractWatchService {
@RestMapping(name = "loadService", auth = false, comment = "动态增加Service") @RestMapping(name = "loadService", auth = false, comment = "动态增加Service")
public RetResult loadService( public RetResult loadService(
@RestParam(name = "type", comment = "Service的类名") String type, @RestParam(name = "type", comment = "Service的类名") String type,
@RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameRegx = "\\.jar$") byte[] jar) { @RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameRegex = "\\.jar$") byte[] jar) {
// 待开发 // 待开发
return RetResult.success(); return RetResult.success();
} }

View File

@@ -70,7 +70,7 @@ public interface ResourceEvent<T> {
public static class ResourceChangeEvent<T> implements ResourceEvent<T> { public static class ResourceChangeEvent<T> implements ResourceEvent<T> {
private static final Predicate<String> numRegx = private static final Predicate<String> numRegex =
Pattern.compile("^(\\-\\+)?\\d+(\\.\\d+)?$").asPredicate(); Pattern.compile("^(\\-\\+)?\\d+(\\.\\d+)?$").asPredicate();
protected String name; protected String name;
@@ -84,7 +84,7 @@ public interface ResourceEvent<T> {
String str = val.toString(); String str = val.toString();
if ("false".equalsIgnoreCase(str)) return str; if ("false".equalsIgnoreCase(str)) return str;
if (str.length() <= 4) return str; if (str.length() <= 4) return str;
if (numRegx.test(str)) return str; if (numRegex.test(str)) return str;
return str.substring(0, 2) + "***" + str.substring(str.length() - 2); return str.substring(0, 2) + "***" + str.substring(str.length() - 2);
} }

View File

@@ -1125,7 +1125,7 @@ public final class ResourceFactory {
public ResourceTypeLoader findTypeLoader(Type ft, @Nullable Field field) { public ResourceTypeLoader findTypeLoader(Type ft, @Nullable Field field) {
ResourceTypeLoader it = this.findMatchTypeLoader(ft, field); ResourceTypeLoader it = this.findMatchTypeLoader(ft, field);
return it == null ? findRegxTypeLoader(ft, field) : it; return it == null ? findRegexTypeLoader(ft, field) : it;
} }
private ResourceFactory parentRoot() { private ResourceFactory parentRoot() {
@@ -1146,7 +1146,7 @@ public final class ResourceFactory {
return parent == null ? null : parent.findMatchTypeLoader(ft, field); return parent == null ? null : parent.findMatchTypeLoader(ft, field);
} }
private ResourceTypeLoader findRegxTypeLoader(Type ft, @Nullable Field field) { private ResourceTypeLoader findRegexTypeLoader(Type ft, @Nullable Field field) {
if (field == null) { if (field == null) {
return null; return null;
} }
@@ -1160,7 +1160,7 @@ public final class ResourceFactory {
return en.getValue(); return en.getValue();
} }
} }
return parent == null ? null : parent.findRegxTypeLoader(ft, field); return parent == null ? null : parent.findRegexTypeLoader(ft, field);
} }
private void onResourceInjected(Object src, Field field, Object res) { private void onResourceInjected(Object src, Field field, Object res) {

View File

@@ -34,9 +34,9 @@ public class HttpDispatcherServlet
protected HttpServlet resourceHttpServlet = new HttpResourceServlet(); protected HttpServlet resourceHttpServlet = new HttpResourceServlet();
protected MappingEntry[] regxArray = null; // regxArray 包含 regxWsArray protected MappingEntry[] regexArray = null; // regexArray 包含 regexWsArray
protected MappingEntry[] regxWsArray = null; protected MappingEntry[] regexWsArray = null;
protected Map<String, WebSocketServlet> wsMappings = new HashMap<>(); // super.mappings 包含 wsMappings protected Map<String, WebSocketServlet> wsMappings = new HashMap<>(); // super.mappings 包含 wsMappings
@@ -68,16 +68,16 @@ public class HttpDispatcherServlet
allMapLock.lock(); allMapLock.lock();
try { try {
List<String> keys = new ArrayList<>(); List<String> keys = new ArrayList<>();
if (regxArray != null) { if (regexArray != null) {
for (MappingEntry me : regxArray) { for (MappingEntry me : regexArray) {
if (predicateEntry.test(me)) { if (predicateEntry.test(me)) {
servlets.add(me.servlet); servlets.add(me.servlet);
keys.add(me.mapping); keys.add(me.mapping);
} }
} }
} }
if (regxWsArray != null) { if (regexWsArray != null) {
for (MappingEntry me : regxWsArray) { for (MappingEntry me : regexWsArray) {
if (predicateEntry.test(me)) { if (predicateEntry.test(me)) {
servlets.add(me.servlet); servlets.add(me.servlet);
keys.add(me.mapping); keys.add(me.mapping);
@@ -97,8 +97,8 @@ public class HttpDispatcherServlet
this.wsMappings = newWsMappings; this.wsMappings = newWsMappings;
} }
if (!keys.isEmpty()) { if (!keys.isEmpty()) {
this.regxArray = Utility.remove(this.regxArray, predicateEntry); this.regexArray = Utility.remove(this.regexArray, predicateEntry);
this.regxWsArray = Utility.remove(this.regxWsArray, predicateEntry); this.regexWsArray = Utility.remove(this.regexWsArray, predicateEntry);
for (HttpServlet rs : servlets) { for (HttpServlet rs : servlets) {
super.removeServlet(rs); super.removeServlet(rs);
} }
@@ -184,19 +184,19 @@ public class HttpDispatcherServlet
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public boolean addForbidURIRegx(final String urlRegx) { public boolean addForbidURIRegex(final String urlRegex) {
if (urlRegx == null || urlRegx.isEmpty()) { if (urlRegex == null || urlRegex.isEmpty()) {
return false; return false;
} }
excludeLock.lock(); excludeLock.lock();
try { try {
if (forbidURIMaps != null && forbidURIMaps.containsKey(urlRegx)) { if (forbidURIMaps != null && forbidURIMaps.containsKey(urlRegex)) {
return false; return false;
} }
if (forbidURIMaps == null) { if (forbidURIMaps == null) {
forbidURIMaps = new HashMap<>(); forbidURIMaps = new HashMap<>();
} }
String mapping = urlRegx; String mapping = urlRegex;
if (Utility.contains(mapping, '*', '{', '[', '(', '|', '^', '$', '+', '?', '\\')) { // 是否是正则表达式)) if (Utility.contains(mapping, '*', '{', '[', '(', '|', '^', '$', '+', '?', '\\')) { // 是否是正则表达式))
if (mapping.endsWith("/*")) { if (mapping.endsWith("/*")) {
mapping = mapping.substring(0, mapping.length() - 1) + ".*"; mapping = mapping.substring(0, mapping.length() - 1) + ".*";
@@ -210,7 +210,7 @@ public class HttpDispatcherServlet
BiPredicate<String, String> predicate = (prefix, uri) -> { BiPredicate<String, String> predicate = (prefix, uri) -> {
return begin || prefix.isEmpty() ? regPredicate.test(uri) : uri.matches(prefix + reg); return begin || prefix.isEmpty() ? regPredicate.test(uri) : uri.matches(prefix + reg);
}; };
forbidURIMaps.put(urlRegx, predicate); forbidURIMaps.put(urlRegex, predicate);
forbidURIPredicates = Utility.append(forbidURIPredicates, predicate); forbidURIPredicates = Utility.append(forbidURIPredicates, predicate);
return true; return true;
} finally { } finally {
@@ -328,8 +328,8 @@ public class HttpDispatcherServlet
} }
if (request.isWebSocket()) { if (request.isWebSocket()) {
servlet = wsMappings.get(uri); servlet = wsMappings.get(uri);
if (servlet == null && this.regxWsArray != null) { if (servlet == null && this.regexWsArray != null) {
for (MappingEntry en : regxWsArray) { for (MappingEntry en : regexWsArray) {
if (en.predicate.test(uri)) { if (en.predicate.test(uri)) {
servlet = en.servlet; servlet = en.servlet;
break; break;
@@ -342,8 +342,8 @@ public class HttpDispatcherServlet
} }
} else { } else {
servlet = mappingServlet(uri); servlet = mappingServlet(uri);
if (servlet == null && this.regxArray != null) { if (servlet == null && this.regexArray != null) {
for (MappingEntry en : regxArray) { for (MappingEntry en : regexArray) {
if (en.predicate.test(uri)) { if (en.predicate.test(uri)) {
servlet = en.servlet; servlet = en.servlet;
break; break;
@@ -434,28 +434,28 @@ public class HttpDispatcherServlet
} else { } else {
mappingPath = mappingPath + "$"; mappingPath = mappingPath + "$";
} }
if (regxArray == null) { if (regexArray == null) {
regxArray = new MappingEntry[1]; regexArray = new MappingEntry[1];
regxArray[0] = new MappingEntry( regexArray[0] = new MappingEntry(
mappingPath, Pattern.compile(mappingPath).asPredicate(), servlet); mappingPath, Pattern.compile(mappingPath).asPredicate(), servlet);
} else { } else {
regxArray = Arrays.copyOf(regxArray, regxArray.length + 1); regexArray = Arrays.copyOf(regexArray, regexArray.length + 1);
regxArray[regxArray.length - 1] = new MappingEntry( regexArray[regexArray.length - 1] = new MappingEntry(
mappingPath, Pattern.compile(mappingPath).asPredicate(), servlet); mappingPath, Pattern.compile(mappingPath).asPredicate(), servlet);
Arrays.sort(regxArray); Arrays.sort(regexArray);
} }
if (servlet instanceof WebSocketServlet) { if (servlet instanceof WebSocketServlet) {
if (regxWsArray == null) { if (regexWsArray == null) {
regxWsArray = new MappingEntry[1]; regexWsArray = new MappingEntry[1];
regxWsArray[0] = new MappingEntry( regexWsArray[0] = new MappingEntry(
mappingPath, Pattern.compile(mappingPath).asPredicate(), (WebSocketServlet) mappingPath, Pattern.compile(mappingPath).asPredicate(), (WebSocketServlet)
servlet); servlet);
} else { } else {
regxWsArray = Arrays.copyOf(regxWsArray, regxWsArray.length + 1); regexWsArray = Arrays.copyOf(regexWsArray, regexWsArray.length + 1);
regxWsArray[regxWsArray.length - 1] = new MappingEntry( regexWsArray[regexWsArray.length - 1] = new MappingEntry(
mappingPath, Pattern.compile(mappingPath).asPredicate(), (WebSocketServlet) mappingPath, Pattern.compile(mappingPath).asPredicate(), (WebSocketServlet)
servlet); servlet);
Arrays.sort(regxWsArray); Arrays.sort(regexWsArray);
} }
} }
} else if (mappingPath != null && !mappingPath.isEmpty()) { } else if (mappingPath != null && !mappingPath.isEmpty()) {
@@ -574,8 +574,8 @@ public class HttpDispatcherServlet
}); });
this.allMapStrings.clear(); this.allMapStrings.clear();
this.wsMappings.clear(); this.wsMappings.clear();
this.regxArray = null; this.regexArray = null;
this.regxWsArray = null; this.regexWsArray = null;
} }
protected static class MappingEntry implements Comparable<MappingEntry> { protected static class MappingEntry implements Comparable<MappingEntry> {

View File

@@ -1458,9 +1458,10 @@ public class HttpRequest extends Request<HttpContext> {
} }
/** /**
* 获取客户端地址IP, 与getRemoteAddress() 的区别在于本方法优先取header中指定为RemoteAddress名的值没有则返回getRemoteAddress()的getHostAddress()。 * 获取客户端地址IP, 与getRemoteAddress() 的区别在于本方法优先取header中指定为RemoteAddress名的值
* 没有则返回{@link #getRemoteAddress()}的getHostAddress()。
* <br> * <br>
* 本方法适用于服务前端有如nginx的代理服务器进行中转通过 getRemoteAddress()是获取不到客户端的真实IP。 * 本方法适用于服务前端有如nginx的代理服务器进行中转通过 {@link #getRemoteAddress()}是获取不到客户端的真实IP。
* *
* @return 地址 * @return 地址
*/ */
@@ -1472,6 +1473,10 @@ public class HttpRequest extends Request<HttpContext> {
if (remoteAddrHeader != null) { if (remoteAddrHeader != null) {
String val = getHeader(remoteAddrHeader); String val = getHeader(remoteAddrHeader);
if (val != null) { if (val != null) {
int pos = val.indexOf(',');
if (pos > 6) {
val = val.substring(0, pos);
}
this.remoteAddr = val; this.remoteAddr = val;
return val; return val;
} }
@@ -1542,7 +1547,7 @@ public class HttpRequest extends Request<HttpContext> {
* @return 内容 * @return 内容
*/ */
public <T> T getBodyJson(java.lang.reflect.Type type) { public <T> T getBodyJson(java.lang.reflect.Type type) {
if (array == null || array.isEmpty()) { if (isEmpty(array)) {
return null; return null;
} }
Convert convert = this.reqConvert; Convert convert = this.reqConvert;
@@ -1564,7 +1569,7 @@ public class HttpRequest extends Request<HttpContext> {
* @return 内容 * @return 内容
*/ */
public <T> T getBodyJson(Convert convert, java.lang.reflect.Type type) { public <T> T getBodyJson(Convert convert, java.lang.reflect.Type type) {
if (array.isEmpty()) { if (isEmpty(array)) {
return null; return null;
} }
if (type == byte[].class) { if (type == byte[].class) {

View File

@@ -5,13 +5,12 @@
*/ */
package org.redkale.net.http; package org.redkale.net.http;
import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.net.HttpCookie; import java.net.HttpCookie;
import java.text.*; import java.text.*;
import java.time.ZoneId; import java.time.ZoneId;
import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.atomic.LongAdder;
@@ -153,8 +152,8 @@ public class HttpServer extends Server<String, HttpContext, HttpRequest, HttpRes
* @param urlreg 正则表达式 * @param urlreg 正则表达式
* @return 是否成功 * @return 是否成功
*/ */
public boolean addForbidURIReg(final String urlreg) { public boolean addForbidURIRegex(final String urlreg) {
return ((HttpDispatcherServlet) this.dispatcher).addForbidURIRegx(urlreg); return ((HttpDispatcherServlet) this.dispatcher).addForbidURIRegex(urlreg);
} }
/** /**
@@ -163,7 +162,7 @@ public class HttpServer extends Server<String, HttpContext, HttpRequest, HttpRes
* @param urlreg 正则表达式 * @param urlreg 正则表达式
* @return 是否成功 * @return 是否成功
*/ */
public boolean removeForbidURIReg(final String urlreg) { public boolean removeForbidURIRegex(final String urlreg) {
return ((HttpDispatcherServlet) this.dispatcher).removeForbidURIReg(urlreg); return ((HttpDispatcherServlet) this.dispatcher).removeForbidURIReg(urlreg);
} }

View File

@@ -96,12 +96,12 @@ public final class MultiContext {
* 获取第一个文件的二进制 * 获取第一个文件的二进制
* *
* @param max 可接收的文件大小最大值 * @param max 可接收的文件大小最大值
* @param fileNameRegx 可接收的文件名正则表达式 * @param fileNameRegex 可接收的文件名正则表达式
* @param contentTypeRegx 可接收的ContentType正则表达式 * @param contentTypeRegex 可接收的ContentType正则表达式
* @return 二进制文件 * @return 二进制文件
* @throws IOException IOException * @throws IOException IOException
*/ */
public byte[] partsFirstBytes(final long max, final String fileNameRegx, final String contentTypeRegx) public byte[] partsFirstBytes(final long max, final String fileNameRegex, final String contentTypeRegex)
throws IOException { throws IOException {
if (!isMultipart()) { if (!isMultipart()) {
return null; return null;
@@ -113,14 +113,14 @@ public final class MultiContext {
continue; // 不遍历完后面getParameter可能获取不到值 continue; // 不遍历完后面getParameter可能获取不到值
} }
has = true; has = true;
if (fileNameRegx != null if (fileNameRegex != null
&& !fileNameRegx.isEmpty() && !fileNameRegex.isEmpty()
&& !part.getFileName().matches(fileNameRegx)) { && !part.getFileName().matches(fileNameRegex)) {
continue; continue;
} }
if (contentTypeRegx != null if (contentTypeRegex != null
&& !contentTypeRegx.isEmpty() && !contentTypeRegex.isEmpty()
&& !part.getContentType().matches(contentTypeRegx)) { && !part.getContentType().matches(contentTypeRegex)) {
continue; continue;
} }
tmpfile = part.getContentBytes(max < 1 ? Long.MAX_VALUE : max); tmpfile = part.getContentBytes(max < 1 ? Long.MAX_VALUE : max);
@@ -148,12 +148,12 @@ public final class MultiContext {
* *
* @param home 进程目录 * @param home 进程目录
* @param max 可接收的文件大小最大值 * @param max 可接收的文件大小最大值
* @param fileNameRegx 可接收的文件名正则表达式 * @param fileNameRegex 可接收的文件名正则表达式
* @param contentTypeRegx 可接收的ContentType正则表达式 * @param contentTypeRegex 可接收的ContentType正则表达式
* @return 文件 * @return 文件
* @throws IOException IOException * @throws IOException IOException
*/ */
public File partsFirstFile(final File home, final long max, final String fileNameRegx, final String contentTypeRegx) public File partsFirstFile(final File home, final long max, final String fileNameRegex, final String contentTypeRegex)
throws IOException { throws IOException {
if (!isMultipart()) { if (!isMultipart()) {
return null; return null;
@@ -165,14 +165,14 @@ public final class MultiContext {
continue; // 不遍历完后面getParameter可能获取不到值 continue; // 不遍历完后面getParameter可能获取不到值
} }
has = true; has = true;
if (fileNameRegx != null if (fileNameRegex != null
&& !fileNameRegx.isEmpty() && !fileNameRegex.isEmpty()
&& !part.getFileName().matches(fileNameRegx)) { && !part.getFileName().matches(fileNameRegex)) {
continue; continue;
} }
if (contentTypeRegx != null if (contentTypeRegex != null
&& !contentTypeRegx.isEmpty() && !contentTypeRegex.isEmpty()
&& !part.getContentType().matches(contentTypeRegx)) { && !part.getContentType().matches(contentTypeRegex)) {
continue; continue;
} }
File file = new File(home, "tmp/redkale-" + System.nanoTime() + "_" + part.getFileName()); File file = new File(home, "tmp/redkale-" + System.nanoTime() + "_" + part.getFileName());
@@ -197,26 +197,26 @@ public final class MultiContext {
* *
* @param home 进程目录 * @param home 进程目录
* @param max 可接收的文件大小最大值 * @param max 可接收的文件大小最大值
* @param fileNameRegx 可接收的文件名正则表达式 * @param fileNameRegex 可接收的文件名正则表达式
* @param contentTypeRegx 可接收的ContentType正则表达式 * @param contentTypeRegex 可接收的ContentType正则表达式
* @return 文件列表 * @return 文件列表
* @throws IOException IOException * @throws IOException IOException
*/ */
public File[] partsFiles(final File home, final long max, final String fileNameRegx, final String contentTypeRegx) public File[] partsFiles(final File home, final long max, final String fileNameRegex, final String contentTypeRegex)
throws IOException { throws IOException {
if (!isMultipart()) { if (!isMultipart()) {
return null; return null;
} }
List<File> files = null; List<File> files = null;
for (MultiPart part : parts()) { for (MultiPart part : parts()) {
if (fileNameRegx != null if (fileNameRegex != null
&& !fileNameRegx.isEmpty() && !fileNameRegex.isEmpty()
&& !part.getFileName().matches(fileNameRegx)) { && !part.getFileName().matches(fileNameRegex)) {
continue; continue;
} }
if (contentTypeRegx != null if (contentTypeRegex != null
&& !contentTypeRegx.isEmpty() && !contentTypeRegex.isEmpty()
&& !part.getContentType().matches(contentTypeRegx)) { && !part.getContentType().matches(contentTypeRegex)) {
continue; continue;
} }
File file = new File(home, "tmp/redkale-" + System.nanoTime() + "_" + part.getFileName()); File file = new File(home, "tmp/redkale-" + System.nanoTime() + "_" + part.getFileName());
@@ -249,7 +249,7 @@ public final class MultiContext {
return emptyIterable; return emptyIterable;
} }
final String boundarystr = "--" + this.boundary; final String boundarystr = "--" + this.boundary;
final Pattern fileNameRegx = this.fileNamePattern; final Pattern fileNameRegex = this.fileNamePattern;
final String endboundary = boundarystr + "--"; final String endboundary = boundarystr + "--";
final byte[] boundarray = ("\n" + boundarystr).getBytes(); final byte[] boundarray = ("\n" + boundarystr).getBytes();
final byte[] buffer = new byte[boundarray.length]; final byte[] buffer = new byte[boundarray.length];
@@ -377,8 +377,8 @@ public final class MultiContext {
} }
}; };
this.lastentry = new MultiPart(filename, name, contentType, counter, source); this.lastentry = new MultiPart(filename, name, contentType, counter, source);
if (fileNameRegx != null if (fileNameRegex != null
&& !fileNameRegx.matcher(filename).matches()) { && !fileNameRegex.matcher(filename).matches()) {
return this.hasNext(); return this.hasNext();
} }
return true; return true;

View File

@@ -2765,8 +2765,8 @@ public final class Rest {
mv.visitMethodInsn( mv.visitMethodInsn(
INVOKEVIRTUAL, reqInternalName, "getMultiContext", "()" + multiContextDesc, false); INVOKEVIRTUAL, reqInternalName, "getMultiContext", "()" + multiContextDesc, false);
mv.visitLdcInsn(mupload.maxLength()); mv.visitLdcInsn(mupload.maxLength());
mv.visitLdcInsn(mupload.fileNameRegx()); mv.visitLdcInsn(mupload.fileNameRegex());
mv.visitLdcInsn(mupload.contentTypeRegx()); mv.visitLdcInsn(mupload.contentTypeRegex());
mv.visitMethodInsn( mv.visitMethodInsn(
INVOKEVIRTUAL, INVOKEVIRTUAL,
multiContextName, multiContextName,
@@ -2782,8 +2782,8 @@ public final class Rest {
mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, newDynName, "_redkale_home", "Ljava/io/File;"); mv.visitFieldInsn(GETFIELD, newDynName, "_redkale_home", "Ljava/io/File;");
mv.visitLdcInsn(mupload.maxLength()); mv.visitLdcInsn(mupload.maxLength());
mv.visitLdcInsn(mupload.fileNameRegx()); mv.visitLdcInsn(mupload.fileNameRegex());
mv.visitLdcInsn(mupload.contentTypeRegx()); mv.visitLdcInsn(mupload.contentTypeRegex());
mv.visitMethodInsn( mv.visitMethodInsn(
INVOKEVIRTUAL, INVOKEVIRTUAL,
multiContextName, multiContextName,
@@ -2799,8 +2799,8 @@ public final class Rest {
mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, newDynName, "_redkale_home", "Ljava/io/File;"); mv.visitFieldInsn(GETFIELD, newDynName, "_redkale_home", "Ljava/io/File;");
mv.visitLdcInsn(mupload.maxLength()); mv.visitLdcInsn(mupload.maxLength());
mv.visitLdcInsn(mupload.fileNameRegx()); mv.visitLdcInsn(mupload.fileNameRegex());
mv.visitLdcInsn(mupload.contentTypeRegx()); mv.visitLdcInsn(mupload.contentTypeRegex());
mv.visitMethodInsn( mv.visitMethodInsn(
INVOKEVIRTUAL, INVOKEVIRTUAL,
multiContextName, multiContextName,

View File

@@ -5,15 +5,14 @@
*/ */
package org.redkale.net.http; package org.redkale.net.http;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*; import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
/** /**
* 只能注解于Service类的方法的String参数或参数内的String字段 * 只能注解于Service类的方法的String参数或参数内的String字段
* *
* <p>用于获取HTTP请求端的IP地址 HttpRequest.getRemoteAddr * <p>用于获取HTTP请求端的IP地址 {@link org.redkale.net.http.HttpRequest#getRemoteAddr() }
* *
* <p>详情见: https://redkale.org * <p>详情见: https://redkale.org
* *

View File

@@ -5,11 +5,10 @@
*/ */
package org.redkale.net.http; package org.redkale.net.http;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*; import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
/** /**
* 依附在RestService类的方法的参数上, 用于接收上传文件 <br> * 依附在RestService类的方法的参数上, 用于接收上传文件 <br>
* 只能标记在byte[]/File/File[] 类型的参数上 <br> * 只能标记在byte[]/File/File[] 类型的参数上 <br>
@@ -35,14 +34,14 @@ public @interface RestUploadFile {
* *
* @return String * @return String
*/ */
String fileNameRegx() default ""; String fileNameRegex() default "";
/** /**
* 可接收的ContentType正则表达式, 为空表示接收任何文件类型 <br> * 可接收的ContentType正则表达式, 为空表示接收任何文件类型 <br>
* *
* @return String * @return String
*/ */
String contentTypeRegx() default ""; String contentTypeRegex() default "";
/** /**
* 备注描述, 对应&#64;HttpParam.comment * 备注描述, 对应&#64;HttpParam.comment

View File

@@ -1291,10 +1291,10 @@ public final class CacheMemorySource extends AbstractCacheSource {
.collect(Collectors.toMap( .collect(Collectors.toMap(
Map.Entry::getKey, en -> CacheEntry.serialToObj(convert, type, en.getValue()))); Map.Entry::getKey, en -> CacheEntry.serialToObj(convert, type, en.getValue())));
} else { } else {
Predicate<String> regx = Pattern.compile(pattern.replace("*", ".*")).asPredicate(); Predicate<String> regex = Pattern.compile(pattern.replace("*", ".*")).asPredicate();
Set<Map.Entry<String, Serializable>> set = entry.mapValue.entrySet(); Set<Map.Entry<String, Serializable>> set = entry.mapValue.entrySet();
return set.stream() return set.stream()
.filter(en -> regx.test(en.getKey())) .filter(en -> regex.test(en.getKey()))
.collect(Collectors.toMap( .collect(Collectors.toMap(
Map.Entry::getKey, en -> CacheEntry.serialToObj(convert, type, en.getValue()))); Map.Entry::getKey, en -> CacheEntry.serialToObj(convert, type, en.getValue())));
} }
@@ -2356,8 +2356,8 @@ public final class CacheMemorySource extends AbstractCacheSource {
if (Utility.isEmpty(pattern)) { if (Utility.isEmpty(pattern)) {
return sets.stream().collect(Collectors.toList()); return sets.stream().collect(Collectors.toList());
} else { } else {
Predicate<String> regx = Pattern.compile(pattern.replace("*", ".*")).asPredicate(); Predicate<String> regex = Pattern.compile(pattern.replace("*", ".*")).asPredicate();
return sets.stream().filter(en -> regx.test(en.getValue())).collect(Collectors.toList()); return sets.stream().filter(en -> regex.test(en.getValue())).collect(Collectors.toList());
} }
} }

View File

@@ -33,24 +33,24 @@ public class SelectColumn implements Predicate<String> {
if (len < 1) { if (len < 1) {
return; return;
} }
Pattern[] regxs = null; Pattern[] regexs = null;
String[] cols = null; String[] cols = null;
int regcount = 0; int regcount = 0;
int colcount = 0; int colcount = 0;
for (String col : columns0) { for (String col : columns0) {
boolean regx = false; boolean regex = false;
for (int i = 0; i < col.length(); i++) { for (int i = 0; i < col.length(); i++) {
char ch = col.charAt(i); char ch = col.charAt(i);
if (ch == '^' || ch == '$' || ch == '*' || ch == '?' || ch == '+' || ch == '[' || ch == '(') { if (ch == '^' || ch == '$' || ch == '*' || ch == '?' || ch == '+' || ch == '[' || ch == '(') {
regx = true; regex = true;
break; break;
} }
} }
if (regx) { if (regex) {
if (regxs == null) { if (regexs == null) {
regxs = new Pattern[len]; regexs = new Pattern[len];
} }
regxs[regcount++] = Pattern.compile(col); regexs[regcount++] = Pattern.compile(col);
} else { } else {
if (cols == null) { if (cols == null) {
cols = new String[len]; cols = new String[len];
@@ -58,11 +58,11 @@ public class SelectColumn implements Predicate<String> {
cols[colcount++] = col; cols[colcount++] = col;
} }
} }
if (regxs != null) { if (regexs != null) {
if (regcount == len) { if (regcount == len) {
this.patterns = regxs; this.patterns = regexs;
} else { } else {
this.patterns = Arrays.copyOf(regxs, regcount); this.patterns = Arrays.copyOf(regexs, regcount);
} }
} }
if (cols != null) { if (cols != null) {

View File

@@ -1161,6 +1161,26 @@ public final class Utility {
return array != null && array.length > 0; return array != null && array.length > 0;
} }
/**
* 是否为空
*
* @param array ByteArray
* @return 是否为空
*/
public static boolean isEmpty(ByteArray array) {
return array == null || array.isEmpty();
}
/**
* 是否不为空
*
* @param array ByteArray
* @return 是否不为空
*/
public static boolean isNotEmpty(ByteArray array) {
return array != null && !array.isEmpty();
}
/** /**
* 将字符串首字母大写 * 将字符串首字母大写
* *

View File

@@ -22,19 +22,19 @@ public class ClassFilterTest {
@Test @Test
public void run1() { public void run1() {
String regx = ClassFilter.formatPackageRegx("*.platf.**"); String regx = ClassFilter.formatPackageRegex("*.platf.**");
Assertions.assertEquals("^(\\w+)\\.platf\\.(.*)$", regx); Assertions.assertEquals("^(\\w+)\\.platf\\.(.*)$", regx);
} }
@Test @Test
public void run2() { public void run2() {
String regx = ClassFilter.formatPackageRegx("com.platf.**.api"); String regx = ClassFilter.formatPackageRegex("com.platf.**.api");
Assertions.assertEquals("^com\\.platf\\.(.*)\\.api$", regx); Assertions.assertEquals("^com\\.platf\\.(.*)\\.api$", regx);
} }
@Test @Test
public void run3() { public void run3() {
String regx = ClassFilter.formatPackageRegx("**.platf.api"); String regx = ClassFilter.formatPackageRegex("**.platf.api");
Assertions.assertEquals("^(.*)\\.platf\\.api$", regx); Assertions.assertEquals("^(.*)\\.platf\\.api$", regx);
} }
} }