根据P3C优化代码

This commit is contained in:
smallchill 2018-12-27 13:53:02 +08:00
parent 912e0dd227
commit 0d4f08b475
12 changed files with 124 additions and 414 deletions

View File

@ -47,7 +47,7 @@ public class BladeBootAutoConfiguration {
SystemConstant me = SystemConstant.me();
//设定开发模式
me.setDevMode((bladeProperties.getEnv().equals("dev") ? true : false));
me.setDevMode(("dev".equals(bladeProperties.getEnv())));
//设定文件上传远程地址
me.setDomain(bladeProperties.get("upload-domain", "http://localhost:8888"));

View File

@ -67,7 +67,9 @@ public class Condition {
qw.setEntity(BeanUtil.newInstance(clazz));
if (Func.isNotEmpty(query)) {
query.forEach((k, v) -> {
if (Func.isNotEmpty(v)) qw.like(k, v);
if (Func.isNotEmpty(v)) {
qw.like(k, v);
}
});
}
return qw;

View File

@ -1,94 +0,0 @@
package org.springblade.core.tool.date;
import java.sql.Timestamp;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* 系统时钟<br>
* 高并发场景下System.currentTimeMillis()的性能问题的优化
* System.currentTimeMillis()的调用比new一个普通对象要耗时的多具体耗时高出多少我还没测试过有人说是100倍左右
* System.currentTimeMillis()之所以慢是因为去跟系统打了一次交道
* 后台定时更新时钟JVM退出时线程自动回收
*
* see http://git.oschina.net/yu120/sequence
* @author lry,looly
*/
public class SystemClock {
/** 时钟更新间隔,单位毫秒 */
private final long period;
/** 现在时刻的毫秒数 */
private volatile long now;
/**
* 构造
* @param period
*/
private SystemClock(long period) {
this.period = period;
this.now = System.currentTimeMillis();
scheduleClockUpdating();
}
/**
* 开启计时器线程
*/
private void scheduleClockUpdating() {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory(){
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "System Clock");
thread.setDaemon(true);
return thread;
}
});
scheduler.scheduleAtFixedRate(new Runnable(){
@Override
public void run() {
now = System.currentTimeMillis();
}
}, period, period, TimeUnit.MILLISECONDS);
}
/**
* @return 当前时间毫秒数
*/
private long currentTimeMillis() {
return now;
}
//------------------------------------------------------------------------ static
/**
* 单例
* @author Looly
*
*/
private static class InstanceHolder {
public static final SystemClock INSTANCE = new SystemClock(1);
}
/**
* 单例实例
* @return 单例实例
*/
private static SystemClock instance() {
return InstanceHolder.INSTANCE;
}
/**
* @return 当前时间
*/
public static long now() {
return instance().currentTimeMillis();
}
/**
* @return 当前时间字符串表现形式
*/
public static String nowDate() {
return new Timestamp(instance().currentTimeMillis()).toString();
}
}

View File

@ -1,74 +0,0 @@
/**
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 org.springblade.core.tool.support;
import java.util.*;
/**
* 大小写忽略Map拓展
*
* @param <K>
* @param <V>
* @author smallchill
*/
public class CaseInsensitiveHashMap<K, V> extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 9178606903603606031L;
private final Map<String, String> lowerCaseMap = new HashMap<String, String>();
@Override
public boolean containsKey(Object key) {
Object realKey = lowerCaseMap.get(key.toString().toLowerCase(Locale.ENGLISH));
return super.containsKey(realKey);
}
@Override
public Object get(Object key) {
Object realKey = lowerCaseMap.get(key.toString().toLowerCase(Locale.ENGLISH));
return super.get(realKey);
}
@Override
public Set keySet() {
return lowerCaseMap.keySet();
}
@Override
public Object put(String key, Object value) {
Object oldKey = lowerCaseMap.put(key.toLowerCase(Locale.ENGLISH), key);
Object oldValue = super.remove(oldKey);
super.put(key, value);
return oldValue;
}
@Override
public void putAll(Map<? extends String, ?> m) {
for (Map.Entry<? extends String, ?> entry : m.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
this.put(key, value);
}
}
@Override
public Object remove(Object key) {
Object realKey = lowerCaseMap.remove(key.toString().toLowerCase(Locale.ENGLISH));
return super.remove(realKey);
}
}

View File

@ -16,6 +16,7 @@
package org.springblade.core.tool.support;
import org.springblade.core.tool.utils.Func;
import org.springframework.util.LinkedCaseInsensitiveMap;
import java.sql.Time;
import java.sql.Timestamp;
@ -27,24 +28,24 @@ import java.util.HashMap;
*
* @author smallchill
*/
public class CMap extends CaseInsensitiveHashMap<String, Object> {
public class Kv extends LinkedCaseInsensitiveMap<Object> {
private CMap() {
private Kv() {
}
/**
* 创建CMap
* 创建Kv
*
* @return CMap
* @return Kv
*/
public static CMap init() {
return new CMap();
public static Kv init() {
return new Kv();
}
public static HashMap newHashMap() {
return new HashMap();
public static HashMap newMap() {
return new HashMap(16);
}
/**
@ -54,7 +55,7 @@ public class CMap extends CaseInsensitiveHashMap<String, Object> {
* @param value
* @return 本身
*/
public CMap set(String attr, Object value) {
public Kv set(String attr, Object value) {
this.put(attr, value);
return this;
}
@ -66,7 +67,7 @@ public class CMap extends CaseInsensitiveHashMap<String, Object> {
* @param value
* @return 本身
*/
public CMap setIgnoreNull(String attr, Object value) {
public Kv setIgnoreNull(String attr, Object value) {
if (null != attr && null != value) {
set(attr, value);
}
@ -117,7 +118,7 @@ public class CMap extends CaseInsensitiveHashMap<String, Object> {
* @return 字段值
*/
public Long getLong(String attr) {
return Func.toLong(get(attr), -1l);
return Func.toLong(get(attr), -1L);
}
/**
@ -196,8 +197,8 @@ public class CMap extends CaseInsensitiveHashMap<String, Object> {
}
@Override
public CMap clone() {
return (CMap) super.clone();
public Kv clone() {
return (Kv) super.clone();
}
}

View File

@ -1,5 +1,7 @@
package org.springblade.core.tool.support.xss;
import org.springblade.core.tool.utils.StringPool;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@ -27,7 +29,7 @@ import java.util.regex.Pattern;
* <p>
* Sample use:
* String input = ...
* String clean = new HTMLFilter().filter( input );
* String clean = new HtmlFilter().filter( input );
* <p>
* The class is not thread safe. Create a new instance if in doubt.
* <p>
@ -39,7 +41,7 @@ import java.util.regex.Pattern;
* @author Cal Hendersen
* @author Michael Semb Wever
*/
public final class HTMLFilter {
public final class HtmlFilter {
/**
* regex flag union representing /si modifiers in php
@ -69,7 +71,7 @@ public final class HTMLFilter {
private static final Pattern P_RIGHT_ARROW = Pattern.compile(">");
private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>");
// @xxx could grow large... maybe use sesat's ReferenceMap
private static final ConcurrentMap<String, Pattern> P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<String, Pattern>();
private static final ConcurrentMap<String, Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<String, Pattern>();
@ -126,31 +128,31 @@ public final class HTMLFilter {
/**
* Default constructor.
*/
public HTMLFilter() {
public HtmlFilter() {
vAllowed = new HashMap<>();
final ArrayList<String> a_atts = new ArrayList<String>();
a_atts.add("href");
a_atts.add("target");
vAllowed.put("a", a_atts);
final ArrayList<String> aAtts = new ArrayList<String>();
aAtts.add("href");
aAtts.add("target");
vAllowed.put("a", aAtts);
final ArrayList<String> img_atts = new ArrayList<String>();
img_atts.add("src");
img_atts.add("width");
img_atts.add("height");
img_atts.add("alt");
vAllowed.put("img", img_atts);
final ArrayList<String> imgAtts = new ArrayList<String>();
imgAtts.add("src");
imgAtts.add("width");
imgAtts.add("height");
imgAtts.add("alt");
vAllowed.put("img", imgAtts);
final ArrayList<String> no_atts = new ArrayList<String>();
vAllowed.put("b", no_atts);
vAllowed.put("strong", no_atts);
vAllowed.put("i", no_atts);
vAllowed.put("em", no_atts);
final ArrayList<String> noAtts = new ArrayList<String>();
vAllowed.put("b", noAtts);
vAllowed.put("strong", noAtts);
vAllowed.put("i", noAtts);
vAllowed.put("em", noAtts);
vSelfClosingTags = new String[]{"img"};
vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"};
vDisallowed = new String[]{};
vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp.
vAllowedProtocols = new String[]{"http", "mailto", "https"};
vProtocolAtts = new String[]{"src", "href"};
vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"};
vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"};
@ -164,7 +166,7 @@ public final class HTMLFilter {
*
* @param debug turn debug on with a true argument
*/
public HTMLFilter(final boolean debug) {
public HtmlFilter(final boolean debug) {
this();
vDebug = debug;
@ -175,7 +177,7 @@ public final class HTMLFilter {
*
* @param conf map containing configuration. keys match field names.
*/
public HTMLFilter(final Map<String, Object> conf) {
public HtmlFilter(final Map<String, Object> conf) {
assert conf.containsKey("vAllowed") : "configuration requires vAllowed";
assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags";
@ -209,8 +211,6 @@ public final class HTMLFilter {
}
}
//---------------------------------------------------------------
// my versions of some PHP library functions
public static String chr(final int decimal) {
return String.valueOf((char) decimal);
}
@ -271,7 +271,7 @@ public final class HTMLFilter {
final Matcher m = P_COMMENTS.matcher(s);
final StringBuffer buf = new StringBuffer();
if (m.find()) {
final String match = m.group(1); //(.*?)
final String match = m.group(1);
m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->"));
}
m.appendTail(buf);
@ -346,13 +346,12 @@ public final class HTMLFilter {
return result;
}
private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) {
Matcher m = regex_pattern.matcher(s);
private static String regexReplace(final Pattern regexPattern, final String replacement, final String s) {
Matcher m = regexPattern.matcher(s);
return m.replaceAll(replacement);
}
private String processTag(final String s) {
// ending tags
Matcher m = P_END_TAG.matcher(s);
if (m.find()) {
final String name = m.group(1).toLowerCase();
@ -365,40 +364,29 @@ public final class HTMLFilter {
}
}
}
// starting tags
m = P_START_TAG.matcher(s);
if (m.find()) {
final String name = m.group(1).toLowerCase();
final String body = m.group(2);
String ending = m.group(3);
//debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );
if (allowed(name)) {
String params = "";
final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body);
final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body);
final List<String> paramNames = new ArrayList<String>();
final List<String> paramValues = new ArrayList<String>();
while (m2.find()) {
paramNames.add(m2.group(1)); //([a-z0-9]+)
paramValues.add(m2.group(3)); //(.*?)
paramNames.add(m2.group(1));
paramValues.add(m2.group(3));
}
while (m3.find()) {
paramNames.add(m3.group(1)); //([a-z0-9]+)
paramValues.add(m3.group(3)); //([^\"\\s']+)
paramNames.add(m3.group(1));
paramValues.add(m3.group(3));
}
String paramName, paramValue;
for (int ii = 0; ii < paramNames.size(); ii++) {
paramName = paramNames.get(ii).toLowerCase();
paramValue = paramValues.get(ii);
// debug( "paramName='" + paramName + "'" );
// debug( "paramValue='" + paramValue + "'" );
// debug( "allowed? " + vAllowed.get( name ).contains( paramName ) );
if (allowedAttribute(name, paramName)) {
if (inArray(paramName, vProtocolAtts)) {
paramValue = processParamProtocol(paramValue);
@ -406,15 +394,12 @@ public final class HTMLFilter {
params += " " + paramName + "=\"" + paramValue + "\"";
}
}
if (inArray(name, vSelfClosingTags)) {
ending = " /";
}
if (inArray(name, vNeedClosingTags)) {
ending = "";
}
if (ending == null || ending.length() < 1) {
if (vTagCounts.containsKey(name)) {
vTagCounts.put(name, vTagCounts.get(name) + 1);
@ -429,13 +414,10 @@ public final class HTMLFilter {
return "";
}
}
// comments
m = P_COMMENT.matcher(s);
if (!stripComment && m.find()) {
return "<" + m.group() + ">";
}
return "";
}
@ -446,9 +428,9 @@ public final class HTMLFilter {
final String protocol = m.group(1);
if (!inArray(protocol, vAllowedProtocols)) {
// bad protocol, turn into local anchor link instead
s = "#" + s.substring(protocol.length() + 1, s.length());
if (s.startsWith("#//")) {
s = "#" + s.substring(3, s.length());
s = "#" + s.substring(protocol.length() + 1);
if (s.startsWith(StringPool.DOUBLE_SLASH)) {
s = "#" + s.substring(3);
}
}
}
@ -462,7 +444,7 @@ public final class HTMLFilter {
Matcher m = P_ENTITY.matcher(s);
while (m.find()) {
final String match = m.group(1);
final int decimal = Integer.decode(match).intValue();
final int decimal = Integer.decode(match);
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
}
m.appendTail(buf);
@ -498,8 +480,8 @@ public final class HTMLFilter {
// validate entities throughout the string
Matcher m = P_VALID_ENTITIES.matcher(s);
while (m.find()) {
final String one = m.group(1); //([^&;]*)
final String two = m.group(2); //(?=(;|&|$))
final String one = m.group(1);
final String two = m.group(2);
m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));
}
m.appendTail(buf);
@ -512,9 +494,9 @@ public final class HTMLFilter {
StringBuffer buf = new StringBuffer();
Matcher m = P_VALID_QUOTES.matcher(s);
while (m.find()) {
final String one = m.group(1); //(>|^)
final String two = m.group(2); //([^<]+?)
final String three = m.group(3); //(<|$)
final String one = m.group(1);
final String two = m.group(2);
final String three = m.group(3);
m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, "&quot;", two) + three));
}
m.appendTail(buf);

View File

@ -1,56 +0,0 @@
/**
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 org.springblade.core.tool.support.xss;
import org.springblade.core.tool.utils.StringUtil;
/**
* SQL过滤
*/
public class SQLFilter {
/**
* SQL注入过滤
*
* @param str 待验证的字符串
*/
public static String sqlInject(String str) {
if (StringUtil.isBlank(str)) {
return null;
}
//去掉'|"|;|\字符
str = str.replace("'", "");
str = str.replace("\"", "");
str = str.replace(";", "");
str = str.replace("\\", "");
//转换成小写
str = str.toLowerCase();
//非法字符
String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alert", "drop"};
//判断是否包含非法字符
for (String keyword : keywords) {
if (str.indexOf(keyword) != -1) {
throw new RuntimeException("包含非法字符");
}
}
return str;
}
}

View File

@ -1,58 +0,0 @@
/**
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 org.springblade.core.tool.support.xss;
import org.springblade.core.tool.utils.StringUtil;
/**
* SQL过滤
*
* @author smallchill
*/
public class SqlFilter {
/**
* SQL注入过滤
*
* @param str 待验证的字符串
*/
public static String sqlInject(String str) {
if (StringUtil.isBlank(str)) {
return null;
}
//去掉'|"|;|\字符
str = str.replace("'", "");
str = str.replace("\"", "");
str = str.replace(";", "");
str = str.replace("\\", "");
//转换成小写
str = str.toLowerCase();
//非法字符
String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alert", "drop"};
//判断是否包含非法字符
for (String keyword : keywords) {
if (str.indexOf(keyword) != -1) {
throw new RuntimeException("包含非法字符");
}
}
return str;
}
}

View File

@ -47,7 +47,7 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
/**
* html过滤
*/
private final static HTMLFilter htmlFilter = new HTMLFilter();
private final static HtmlFilter HTML_FILTER = new HtmlFilter();
/**
* 缓存报文,支持多次读取流
@ -160,7 +160,7 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
}
private String xssEncode(String input) {
return htmlFilter.filter(input);
return HTML_FILTER.filter(input);
}
/**

View File

@ -447,7 +447,7 @@ public class Func {
* @param defaultValue the default value
* @return the int represented by the string, or the default if conversion fails
*/
public static int toInt(@Nullable final Object value, final int defaultValue) {
public static int toInt(final Object value, final int defaultValue) {
return NumberUtil.toInt(String.valueOf(value), defaultValue);
}
@ -487,7 +487,7 @@ public class Func {
* @param defaultValue the default value
* @return the long represented by the string, or the default if conversion fails
*/
public static long toLong(@Nullable final Object value, final long defaultValue) {
public static long toLong(final Object value, final long defaultValue) {
return NumberUtil.toLong(String.valueOf(value), defaultValue);
}

View File

@ -54,17 +54,23 @@ public class SpringUtil implements ApplicationContextAware {
if (null == beanName || "".equals(beanName.trim())) {
return null;
}
if (clazz == null) return null;
if (clazz == null) {
return null;
}
return (T) context.getBean(beanName, clazz);
}
public static ApplicationContext getContext() {
if (context == null) return null;
if (context == null) {
return null;
}
return context;
}
public static void publishEvent(ApplicationEvent event) {
if (context == null) return;
if (context == null) {
return;
}
try {
context.publishEvent(event);
} catch (Exception ex) {

View File

@ -22,60 +22,61 @@ package org.springblade.core.tool.utils;
*/
public interface StringPool {
String AMPERSAND = "&";
String AND = "and";
String AT = "@";
String ASTERISK = "*";
String STAR = ASTERISK;
char SLASH = '/';
char BACK_SLASH = '\\';
String COLON = ":";
String COMMA = ",";
String DASH = "-";
String DOLLAR = "$";
String DOT = ".";
String EMPTY = "";
String AMPERSAND = "&";
String AND = "and";
String AT = "@";
String ASTERISK = "*";
String STAR = ASTERISK;
char SLASH = '/';
char BACK_SLASH = '\\';
String DOUBLE_SLASH = "#//";
String COLON = ":";
String COMMA = ",";
String DASH = "-";
String DOLLAR = "$";
String DOT = ".";
String EMPTY = "";
String EMPTY_JSON = "{}";
String EQUALS = "=";
String FALSE = "false";
String HASH = "#";
String HAT = "^";
String LEFT_BRACE = "{";
String LEFT_BRACKET = "(";
String LEFT_CHEV = "<";
String NEWLINE = "\n";
String N = "n";
String NO = "no";
String NULL = "null";
String OFF = "off";
String ON = "on";
String PERCENT = "%";
String PIPE = "|";
String PLUS = "+";
String QUESTION_MARK = "?";
String EXCLAMATION_MARK = "!";
String QUOTE = "\"";
String RETURN = "\r";
String TAB = "\t";
String RIGHT_BRACE = "}";
String RIGHT_BRACKET = ")";
String RIGHT_CHEV = ">";
String SEMICOLON = ";";
String SINGLE_QUOTE = "'";
String BACKTICK = "`";
String SPACE = " ";
String TILDA = "~";
String LEFT_SQ_BRACKET = "[";
String RIGHT_SQ_BRACKET = "]";
String TRUE = "true";
String UNDERSCORE = "_";
String UTF_8 = "UTF-8";
String GBK = "GBK";
String EQUALS = "=";
String FALSE = "false";
String HASH = "#";
String HAT = "^";
String LEFT_BRACE = "{";
String LEFT_BRACKET = "(";
String LEFT_CHEV = "<";
String NEWLINE = "\n";
String N = "n";
String NO = "no";
String NULL = "null";
String OFF = "off";
String ON = "on";
String PERCENT = "%";
String PIPE = "|";
String PLUS = "+";
String QUESTION_MARK = "?";
String EXCLAMATION_MARK = "!";
String QUOTE = "\"";
String RETURN = "\r";
String TAB = "\t";
String RIGHT_BRACE = "}";
String RIGHT_BRACKET = ")";
String RIGHT_CHEV = ">";
String SEMICOLON = ";";
String SINGLE_QUOTE = "'";
String BACKTICK = "`";
String SPACE = " ";
String TILDA = "~";
String LEFT_SQ_BRACKET = "[";
String RIGHT_SQ_BRACKET = "]";
String TRUE = "true";
String UNDERSCORE = "_";
String UTF_8 = "UTF-8";
String GBK = "GBK";
String ISO_8859_1 = "ISO-8859-1";
String Y = "y";
String YES = "yes";
String ONE = "1";
String ZERO = "0";
String Y = "y";
String YES = "yes";
String ONE = "1";
String ZERO = "0";
String DOLLAR_LEFT_BRACE= "${";
}