Commit 27e1a554 by liuzz

反编译初始化

parents
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
######################################################################
# Build Tools
.gradle
/build/
!gradle/wrapper/gradle-wrapper.jar
target/
!.mvn/wrapper/maven-wrapper.jar
######################################################################
# IDE
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### JRebel ###
rebel.xml
### NetBeans ###
nbproject/private/
build/*
nbbuild/
dist/
nbdist/
.nb-gradle/
######################################################################
# Others
*.log
*.xml.versionsBackup
*.swp
!*/build/*.java
!*/build/*.html
!*/build/*.xml
This diff is collapsed. Click to expand it.
package com.wechat;
import com.wechat.framework.config.WeChatOAuthProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication(
exclude = {DataSourceAutoConfiguration.class}
)
@EnableConfigurationProperties({WeChatOAuthProperties.class})
@EnableScheduling
public class WechatApplication {
public static void main(String[] args) {
SpringApplication.run(WechatApplication.class, args);
System.out.println("启动成功");
}
}
package com.wechat.common.constant;
public class Constants {
public static final String UTF8 = "UTF-8";
public static final String GBK = "GBK";
public static final String HTTP = "http://";
public static final String HTTPS = "https://";
public static final String SUCCESS = "0";
public static final String FAIL = "1";
public static final String LOGIN_SUCCESS = "Success";
public static final String LOGOUT = "Logout";
public static final String LOGIN_FAIL = "Error";
public static final String CAPTCHA_CODE_KEY = "captcha_codes:";
public static final String LOGIN_TOKEN_KEY = "login_tokens:";
public static final String REPEAT_SUBMIT_KEY = "repeat_submit:";
public static final Integer CAPTCHA_EXPIRATION = 2;
public static final String TOKEN = "token";
public static final String TOKEN_PREFIX = "Bearer ";
public static final String LOGIN_USER_KEY = "login_user_key";
public static final String JWT_USERID = "userid";
public static final String JWT_USERNAME = "sub";
public static final String JWT_AVATAR = "avatar";
public static final String JWT_CREATED = "created";
public static final String JWT_AUTHORITIES = "authorities";
public static final String SYS_CONFIG_KEY = "sys_config:";
public static final String SYS_DICT_KEY = "sys_dict:";
public static final String RESOURCE_PREFIX = "/profile";
}
package com.wechat.common.constant;
public class GenConstants {
public static final String TPL_CRUD = "crud";
public static final String TPL_TREE = "tree";
public static final String TREE_CODE = "treeCode";
public static final String TREE_PARENT_CODE = "treeParentCode";
public static final String TREE_NAME = "treeName";
public static final String PARENT_MENU_ID = "parentMenuId";
public static final String PARENT_MENU_NAME = "parentMenuName";
public static final String[] COLUMNTYPE_STR = new String[]{"char", "varchar", "nvarchar", "varchar2", "tinytext", "text", "mediumtext", "longtext"};
public static final String[] COLUMNTYPE_TIME = new String[]{"datetime", "time", "date", "timestamp"};
public static final String[] COLUMNTYPE_NUMBER = new String[]{
"tinyint", "smallint", "mediumint", "int", "number", "integer", "bit", "bigint", "float", "float", "double", "decimal"
};
public static final String[] COLUMNNAME_NOT_EDIT = new String[]{"id", "create_by", "create_time", "del_flag"};
public static final String[] COLUMNNAME_NOT_LIST = new String[]{"id", "create_by", "create_time", "del_flag", "update_by", "update_time"};
public static final String[] COLUMNNAME_NOT_QUERY = new String[]{"id", "create_by", "create_time", "del_flag", "update_by", "update_time", "remark"};
public static final String[] BASE_ENTITY = new String[]{"createBy", "createTime", "updateBy", "updateTime", "remark"};
public static final String[] TREE_ENTITY = new String[]{"parentName", "parentId", "orderNum", "ancestors", "children"};
public static final String HTML_INPUT = "input";
public static final String HTML_TEXTAREA = "textarea";
public static final String HTML_SELECT = "select";
public static final String HTML_RADIO = "radio";
public static final String HTML_CHECKBOX = "checkbox";
public static final String HTML_DATETIME = "datetime";
public static final String HTML_EDITOR = "editor";
public static final String TYPE_STRING = "String";
public static final String TYPE_INTEGER = "Integer";
public static final String TYPE_LONG = "Long";
public static final String TYPE_DOUBLE = "Double";
public static final String TYPE_BIGDECIMAL = "BigDecimal";
public static final String TYPE_DATE = "Date";
public static final String QUERY_LIKE = "LIKE";
public static final String REQUIRE = "1";
}
package com.wechat.common.constant;
public interface HttpStatus {
int SUCCESS = 200;
int CREATED = 201;
int ACCEPTED = 202;
int NO_CONTENT = 204;
int MOVED_PERM = 301;
int SEE_OTHER = 303;
int NOT_MODIFIED = 304;
int BAD_REQUEST = 400;
int UNAUTHORIZED = 401;
int FORBIDDEN = 403;
int NOT_FOUND = 404;
int BAD_METHOD = 405;
int CONFLICT = 409;
int UNSUPPORTED_TYPE = 415;
int ERROR = 500;
int NOT_IMPLEMENTED = 501;
}
package com.wechat.common.constant;
public interface ScheduleConstants {
String TASK_CLASS_NAME = "TASK_CLASS_NAME";
String TASK_PROPERTIES = "TASK_PROPERTIES";
String MISFIRE_DEFAULT = "0";
String MISFIRE_IGNORE_MISFIRES = "1";
String MISFIRE_FIRE_AND_PROCEED = "2";
String MISFIRE_DO_NOTHING = "3";
public static enum Status {
NORMAL("0"),
PAUSE("1");
private String value;
private Status(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
}
package com.wechat.common.constant;
public class UserConstants {
public static final String SYS_USER = "SYS_USER";
public static final String NORMAL = "0";
public static final String EXCEPTION = "1";
public static final String USER_BLOCKED = "1";
public static final String ROLE_BLOCKED = "1";
public static final String DEPT_NORMAL = "0";
public static final String DICT_NORMAL = "0";
public static final String YES = "Y";
public static final String UNIQUE = "0";
public static final String NOT_UNIQUE = "1";
}
package com.wechat.common.core.lang;
import com.wechat.common.exception.UtilException;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public final class UUID implements Serializable, Comparable<UUID> {
private static final long serialVersionUID = -1185015143654744140L;
private final long mostSigBits;
private final long leastSigBits;
private UUID(byte[] data) {
long msb = 0L;
long lsb = 0L;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++) {
msb = msb << 8 | (long)(data[i] & 255);
}
for (int i = 8; i < 16; i++) {
lsb = lsb << 8 | (long)(data[i] & 255);
}
this.mostSigBits = msb;
this.leastSigBits = lsb;
}
public UUID(long mostSigBits, long leastSigBits) {
this.mostSigBits = mostSigBits;
this.leastSigBits = leastSigBits;
}
public static UUID fastUUID() {
return randomUUID(false);
}
public static UUID randomUUID() {
return randomUUID(true);
}
public static UUID randomUUID(boolean isSecure) {
Random ng = (Random)(isSecure ? UUID.Holder.numberGenerator : getRandom());
byte[] randomBytes = new byte[16];
ng.nextBytes(randomBytes);
randomBytes[6] = (byte)(randomBytes[6] & 15);
randomBytes[6] = (byte)(randomBytes[6] | 64);
randomBytes[8] = (byte)(randomBytes[8] & 63);
randomBytes[8] = (byte)(randomBytes[8] | 128);
return new UUID(randomBytes);
}
public static UUID nameUUIDFromBytes(byte[] name) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException var3) {
throw new InternalError("MD5 not supported");
}
byte[] md5Bytes = md.digest(name);
md5Bytes[6] = (byte)(md5Bytes[6] & 15);
md5Bytes[6] = (byte)(md5Bytes[6] | 48);
md5Bytes[8] = (byte)(md5Bytes[8] & 63);
md5Bytes[8] = (byte)(md5Bytes[8] | 128);
return new UUID(md5Bytes);
}
public static UUID fromString(String name) {
String[] components = name.split("-");
if (components.length != 5) {
throw new IllegalArgumentException("Invalid UUID string: " + name);
} else {
for (int i = 0; i < 5; i++) {
components[i] = "0x" + components[i];
}
long mostSigBits = Long.decode(components[0]);
mostSigBits <<= 16;
mostSigBits |= Long.decode(components[1]);
mostSigBits <<= 16;
mostSigBits |= Long.decode(components[2]);
long leastSigBits = Long.decode(components[3]);
leastSigBits <<= 48;
leastSigBits |= Long.decode(components[4]);
return new UUID(mostSigBits, leastSigBits);
}
}
public long getLeastSignificantBits() {
return this.leastSigBits;
}
public long getMostSignificantBits() {
return this.mostSigBits;
}
public int version() {
return (int)(this.mostSigBits >> 12 & 15L);
}
public int variant() {
return (int)(this.leastSigBits >>> (int)(64L - (this.leastSigBits >>> 62)) & this.leastSigBits >> 63);
}
public long timestamp() throws UnsupportedOperationException {
this.checkTimeBase();
return (this.mostSigBits & 4095L) << 48 | (this.mostSigBits >> 16 & 65535L) << 32 | this.mostSigBits >>> 32;
}
public int clockSequence() throws UnsupportedOperationException {
this.checkTimeBase();
return (int)((this.leastSigBits & 4611404543450677248L) >>> 48);
}
public long node() throws UnsupportedOperationException {
this.checkTimeBase();
return this.leastSigBits & 281474976710655L;
}
@Override
public String toString() {
return this.toString(false);
}
public String toString(boolean isSimple) {
StringBuilder builder = new StringBuilder(isSimple ? 32 : 36);
builder.append(digits(this.mostSigBits >> 32, 8));
if (!isSimple) {
builder.append('-');
}
builder.append(digits(this.mostSigBits >> 16, 4));
if (!isSimple) {
builder.append('-');
}
builder.append(digits(this.mostSigBits, 4));
if (!isSimple) {
builder.append('-');
}
builder.append(digits(this.leastSigBits >> 48, 4));
if (!isSimple) {
builder.append('-');
}
builder.append(digits(this.leastSigBits, 12));
return builder.toString();
}
@Override
public int hashCode() {
long hilo = this.mostSigBits ^ this.leastSigBits;
return (int)(hilo >> 32) ^ (int)hilo;
}
@Override
public boolean equals(Object obj) {
if (null != obj && obj.getClass() == UUID.class) {
UUID id = (UUID)obj;
return this.mostSigBits == id.mostSigBits && this.leastSigBits == id.leastSigBits;
} else {
return false;
}
}
public int compareTo(UUID val) {
return this.mostSigBits < val.mostSigBits
? -1
: (this.mostSigBits > val.mostSigBits ? 1 : (this.leastSigBits < val.leastSigBits ? -1 : (this.leastSigBits > val.leastSigBits ? 1 : 0)));
}
private static String digits(long val, int digits) {
long hi = 1L << digits * 4;
return Long.toHexString(hi | val & hi - 1L).substring(1);
}
private void checkTimeBase() {
if (this.version() != 1) {
throw new UnsupportedOperationException("Not a time-based UUID");
}
}
public static SecureRandom getSecureRandom() {
try {
return SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException var1) {
throw new UtilException(var1);
}
}
public static ThreadLocalRandom getRandom() {
return ThreadLocalRandom.current();
}
private static class Holder {
static final SecureRandom numberGenerator = UUID.getSecureRandom();
}
}
package com.wechat.common.core.text;
import com.wechat.common.utils.StringUtils;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class CharsetKit {
public static final String ISO_8859_1 = "ISO-8859-1";
public static final String UTF_8 = "UTF-8";
public static final String GBK = "GBK";
public static final Charset CHARSET_ISO_8859_1 = Charset.forName("ISO-8859-1");
public static final Charset CHARSET_UTF_8 = Charset.forName("UTF-8");
public static final Charset CHARSET_GBK = Charset.forName("GBK");
public static Charset charset(String charset) {
return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset);
}
public static String convert(String source, String srcCharset, String destCharset) {
return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset));
}
public static String convert(String source, Charset srcCharset, Charset destCharset) {
if (null == srcCharset) {
srcCharset = StandardCharsets.ISO_8859_1;
}
if (null == destCharset) {
srcCharset = StandardCharsets.UTF_8;
}
return !StringUtils.isEmpty(source) && !srcCharset.equals(destCharset) ? new String(source.getBytes(srcCharset), destCharset) : source;
}
public static String systemCharset() {
return Charset.defaultCharset().name();
}
}
package com.wechat.common.core.text;
import com.wechat.common.utils.StringUtils;
public class StrFormatter {
public static final String EMPTY_JSON = "{}";
public static final char C_BACKSLASH = '\\';
public static final char C_DELIM_START = '{';
public static final char C_DELIM_END = '}';
public static String format(final String strPattern, final Object... argArray) {
if (!StringUtils.isEmpty(strPattern) && !StringUtils.isEmpty(argArray)) {
int strPatternLength = strPattern.length();
StringBuilder sbuf = new StringBuilder(strPatternLength + 50);
int handledPosition = 0;
for (int argIndex = 0; argIndex < argArray.length; argIndex++) {
int delimIndex = strPattern.indexOf("{}", handledPosition);
if (delimIndex == -1) {
if (handledPosition == 0) {
return strPattern;
}
sbuf.append(strPattern, handledPosition, strPatternLength);
return sbuf.toString();
}
if (delimIndex <= 0 || strPattern.charAt(delimIndex - 1) != '\\') {
sbuf.append(strPattern, handledPosition, delimIndex);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
} else if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == '\\') {
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
} else {
argIndex--;
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append('{');
handledPosition = delimIndex + 1;
}
}
sbuf.append(strPattern, handledPosition, strPattern.length());
return sbuf.toString();
} else {
return strPattern;
}
}
}
package com.wechat.common.enums;
import java.util.HashMap;
import java.util.Map;
import org.springframework.lang.Nullable;
public enum HttpMethod {
GET,
HEAD,
POST,
PUT,
PATCH,
DELETE,
OPTIONS,
TRACE;
private static final Map<String, HttpMethod> mappings = new HashMap<>(16);
@Nullable
public static HttpMethod resolve(@Nullable String method) {
return method != null ? mappings.get(method) : null;
}
public boolean matches(String method) {
return this == resolve(method);
}
static {
for (HttpMethod httpMethod : values()) {
mappings.put(httpMethod.name(), httpMethod);
}
}
}
package com.wechat.common.enums;
public enum PayStatus {
WAIT_BUYER_PAY("1"),
TRADE_SUCCESS("2"),
REFUND_SUCCESS("3"),
REFUND_FAIL("4"),
TRADE_CLOSED("5");
private String code;
private PayStatus(String code) {
this.code = code;
}
public String getCode() {
return this.code;
}
}
package com.wechat.common.enums;
public enum UserStatus {
OK("0", "正常"),
DISABLE("1", "停用"),
DELETED("2", "删除");
private final String code;
private final String info;
private UserStatus(String code, String info) {
this.code = code;
this.info = info;
}
public String getCode() {
return this.code;
}
public String getInfo() {
return this.info;
}
}
package com.wechat.common.exception;
import com.wechat.common.utils.MessageUtils;
import com.wechat.common.utils.StringUtils;
public class BaseException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String module;
private String code;
private Object[] args;
private String defaultMessage;
public BaseException(String module, String code, Object[] args, String defaultMessage) {
this.module = module;
this.code = code;
this.args = args;
this.defaultMessage = defaultMessage;
}
public BaseException(String module, String code, Object[] args) {
this(module, code, args, null);
}
public BaseException(String module, String defaultMessage) {
this(module, null, null, defaultMessage);
}
public BaseException(String code, Object[] args) {
this(null, code, args, null);
}
public BaseException(String defaultMessage) {
this(null, null, null, defaultMessage);
}
@Override
public String getMessage() {
String message = null;
if (!StringUtils.isEmpty(this.code)) {
message = MessageUtils.message(this.code, this.args);
}
if (message == null) {
message = this.defaultMessage;
}
return message;
}
public String getModule() {
return this.module;
}
public String getCode() {
return this.code;
}
public Object[] getArgs() {
return this.args;
}
public String getDefaultMessage() {
return this.defaultMessage;
}
}
package com.wechat.common.exception;
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
private Integer code;
private String message;
public CustomException(String message) {
this.message = message;
}
public CustomException(String message, Integer code) {
this.message = message;
this.code = code;
}
public CustomException(String message, Throwable e) {
super(message, e);
this.message = message;
}
@Override
public String getMessage() {
return this.message;
}
public Integer getCode() {
return this.code;
}
}
package com.wechat.common.exception;
public class DemoModeException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
package com.wechat.common.exception;
public class UtilException extends RuntimeException {
private static final long serialVersionUID = 8247610319171014183L;
public UtilException(Throwable e) {
super(e.getMessage(), e);
}
public UtilException(String message) {
super(message);
}
public UtilException(String message, Throwable throwable) {
super(message, throwable);
}
}
package com.wechat.common.exception.file;
import com.wechat.common.exception.BaseException;
public class FileException extends BaseException {
private static final long serialVersionUID = 1L;
public FileException(String code, Object[] args) {
super("file", code, args, null);
}
}
package com.wechat.common.exception.file;
public class FileNameLengthLimitExceededException extends FileException {
private static final long serialVersionUID = 1L;
public FileNameLengthLimitExceededException(int defaultFileNameLength) {
super("upload.filename.exceed.length", new Object[]{defaultFileNameLength});
}
}
package com.wechat.common.exception.file;
public class FileSizeLimitExceededException extends FileException {
private static final long serialVersionUID = 1L;
public FileSizeLimitExceededException(long defaultMaxSize) {
super("upload.exceed.maxSize", new Object[]{defaultMaxSize});
}
}
package com.wechat.common.exception.file;
import java.util.Arrays;
import org.apache.commons.fileupload.FileUploadException;
public class InvalidExtensionException extends FileUploadException {
private static final long serialVersionUID = 1L;
private String[] allowedExtension;
private String extension;
private String filename;
public InvalidExtensionException(String[] allowedExtension, String extension, String filename) {
super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString((Object[])allowedExtension) + "]");
this.allowedExtension = allowedExtension;
this.extension = extension;
this.filename = filename;
}
public String[] getAllowedExtension() {
return this.allowedExtension;
}
public String getExtension() {
return this.extension;
}
public String getFilename() {
return this.filename;
}
public static class InvalidFlashExtensionException extends InvalidExtensionException {
private static final long serialVersionUID = 1L;
public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) {
super(allowedExtension, extension, filename);
}
}
public static class InvalidImageExtensionException extends InvalidExtensionException {
private static final long serialVersionUID = 1L;
public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) {
super(allowedExtension, extension, filename);
}
}
public static class InvalidMediaExtensionException extends InvalidExtensionException {
private static final long serialVersionUID = 1L;
public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) {
super(allowedExtension, extension, filename);
}
}
}
package com.wechat.common.exception.job;
public class TaskException extends Exception {
private static final long serialVersionUID = 1L;
private TaskException.Code code;
public TaskException(String msg, TaskException.Code code) {
this(msg, code, null);
}
public TaskException(String msg, TaskException.Code code, Exception nestedEx) {
super(msg, nestedEx);
this.code = code;
}
public TaskException.Code getCode() {
return this.code;
}
public static enum Code {
TASK_EXISTS,
NO_TASK_EXISTS,
TASK_ALREADY_STARTED,
UNKNOWN,
CONFIG_ERROR,
TASK_NODE_NOT_AVAILABLE;
}
}
package com.wechat.common.exception.user;
public class CaptchaException extends UserException {
private static final long serialVersionUID = 1L;
public CaptchaException() {
super("user.jcaptcha.error", null);
}
}
package com.wechat.common.exception.user;
public class CaptchaExpireException extends UserException {
private static final long serialVersionUID = 1L;
public CaptchaExpireException() {
super("user.jcaptcha.expire", null);
}
}
package com.wechat.common.exception.user;
import com.wechat.common.exception.BaseException;
public class UserException extends BaseException {
private static final long serialVersionUID = 1L;
public UserException(String code, Object[] args) {
super("user", code, args, null);
}
}
package com.wechat.common.exception.user;
public class UserPasswordNotMatchException extends UserException {
private static final long serialVersionUID = 1L;
public UserPasswordNotMatchException() {
super("user.password.not.match", null);
}
}
package com.wechat.common.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Arith {
private static final int DEF_DIV_SCALE = 10;
private Arith() {
}
public static double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
public static double sub(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
public static double mul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
public static double div(double v1, double v2) {
return div(v1, v2, 10);
}
public static double div(double v1, double v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
} else {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO.doubleValue() : b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue();
}
}
public static double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
} else {
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue();
}
}
}
package com.wechat.common.utils;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class ConvertUtils {
public static Map<String, Object> objectToMap(Object obj) {
if (obj == null) {
return null;
} else {
Map<String, Object> map = new HashMap<>();
try {
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
} catch (Exception var7) {
}
return map;
}
}
}
package com.wechat.common.utils;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.time.DateFormatUtils;
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static String YYYY_MM_DD = "yyyy-MM-dd";
public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static String YYYYMMDDHHMMSSSSS = "yyyyMMddhhmmssSSS";
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
private static String[] parsePatterns = new String[]{
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm",
"yyyy-MM",
"yyyy/MM/dd",
"yyyy/MM/dd HH:mm:ss",
"yyyy/MM/dd HH:mm",
"yyyy/MM",
"yyyy.MM.dd",
"yyyy.MM.dd HH:mm:ss",
"yyyy.MM.dd HH:mm",
"yyyy.MM"
};
public static Date getNowDate() {
return new Date();
}
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNowFull() {
return dateTimeNow(YYYYMMDDHHMMSSSSS);
}
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date) {
return new SimpleDateFormat(format).format(date);
}
public static final Date dateTime(final String format, final String ts) {
try {
return new SimpleDateFormat(format).parse(ts);
} catch (ParseException var3) {
throw new RuntimeException(var3);
}
}
public static final String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
public static Date parseDate(Object str) {
if (str == null) {
return null;
} else {
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException var2) {
return null;
}
}
}
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
public static String getDatePoor(Date endDate, Date nowDate) {
long nd = 86400000L;
long nh = 3600000L;
long nm = 60000L;
long diff = endDate.getTime() - nowDate.getTime();
long day = diff / nd;
long hour = diff % nd / nh;
long min = diff % nd % nh / nm;
return day + "天" + hour + "小时" + min + "分钟";
}
public static String getDateStr(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
public static String DateToStr(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
String dataFormat = sdf.format(date);
System.out.println(dataFormat);
return dataFormat;
}
public static String getTimeStr(Date date) {
SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
return sdf1.format(date);
}
public static long getTimeLong(String timeStr) {
String[] my = timeStr.split(":");
int hour = Integer.parseInt(my[0]);
int min = Integer.parseInt(my[1]);
int sec = 0;
if (my.length == 3) {
sec = Integer.parseInt(my[2]);
}
return (long)(hour * 3600 + min * 60 + sec);
}
public static boolean nowTimeIsInRange(String beginTimeStr, String endTimeStr) {
long beginTime = getTimeLong(beginTimeStr);
long endTime = getTimeLong(endTimeStr);
long nowTime = getTimeLong(getTimeStr(new Date()));
return nowTime >= beginTime && nowTime <= endTime;
}
public static boolean nowDateIsInRange(String dateStr, String beginTimeStr, String endTimeStr) {
long endTime = parseDate(dateStr + " " + endTimeStr).getTime();
long nowTime = new Date().getTime();
return nowTime <= endTime;
}
public static List<String> findDates(String dBegin, String dEnd) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar calBegin = Calendar.getInstance();
calBegin.setTime(format.parse(dBegin));
Calendar calEnd = Calendar.getInstance();
calEnd.setTime(format.parse(dEnd));
List<String> Datelist = new ArrayList<>();
Datelist.add(format.format(calBegin.getTime()));
while (format.parse(dEnd).after(calBegin.getTime())) {
calBegin.add(5, 1);
Datelist.add(format.format(calBegin.getTime()));
}
return Datelist;
}
}
package com.wechat.common.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class ExceptionUtil {
public static String getExceptionMessage(Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
return sw.toString();
}
public static String getRootErrorMseeage(Exception e) {
Throwable root = ExceptionUtils.getRootCause(e);
root = (Throwable)(root == null ? e : root);
if (root == null) {
return "";
} else {
String msg = root.getMessage();
return msg == null ? "null" : StringUtils.defaultString(msg);
}
}
}
package com.wechat.common.utils;
import com.wechat.common.core.lang.UUID;
public class IdUtils {
public static String randomUUID() {
return UUID.randomUUID().toString();
}
public static String simpleUUID() {
return UUID.randomUUID().toString(true);
}
public static String fastUUID() {
return UUID.fastUUID().toString();
}
public static String fastSimpleUUID() {
return UUID.fastUUID().toString(true);
}
}
package com.wechat.common.utils;
public class LogUtils {
public static String getBlock(Object msg) {
if (msg == null) {
msg = "";
}
return "[" + msg.toString() + "]";
}
}
package com.wechat.common.utils;
import com.wechat.common.utils.spring.SpringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
public class MessageUtils {
public static String message(String code, Object... args) {
MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}
}
package com.wechat.common.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
public class QRCodeUtils {
public static byte[] getQRCodeImageStream(String text, int width, int height) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
return pngOutputStream.toByteArray();
}
public static String getQRCodeImageBase64(String text, int width, int height) throws WriterException, IOException {
return Base64.encodeBase64String(getQRCodeImageStream(text, width, height));
}
public static String Generate2(String text, int width, int height) throws IOException, WriterException {
BitMatrix byteMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.CODE_93, width, height);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(byteMatrix, "PNG", pngOutputStream);
byte[] pngData = pngOutputStream.toByteArray();
return Base64.encodeBase64String(pngData);
}
}
package com.wechat.common.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
public class RandomGUID {
public String valueBeforeMD5 = "";
public String valueAfterMD5 = "";
private static Random myRand;
private static SecureRandom mySecureRand = new SecureRandom();
private static String s_id;
public RandomGUID() {
this.getRandomGUID(false);
}
public RandomGUID(boolean secure) {
this.getRandomGUID(secure);
}
private void getRandomGUID(boolean secure) {
MessageDigest md5 = null;
StringBuffer sbValueBeforeMD5 = new StringBuffer();
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException var12) {
System.out.println("Error: " + var12);
}
try {
long time = System.currentTimeMillis();
long rand = 0L;
if (secure) {
rand = mySecureRand.nextLong();
} else {
rand = myRand.nextLong();
}
sbValueBeforeMD5.append(s_id);
sbValueBeforeMD5.append(":");
sbValueBeforeMD5.append(Long.toString(time));
sbValueBeforeMD5.append(":");
sbValueBeforeMD5.append(Long.toString(rand));
this.valueBeforeMD5 = sbValueBeforeMD5.toString();
md5.update(this.valueBeforeMD5.getBytes());
byte[] array = md5.digest();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < array.length; j++) {
int b = array[j] & 255;
if (b < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(b));
}
this.valueAfterMD5 = sb.toString();
} catch (Exception var13) {
System.out.println("Error:" + var13);
}
}
@Override
public String toString() {
String raw = this.valueAfterMD5.toUpperCase();
StringBuffer sb = new StringBuffer();
sb.append(raw.substring(0, 8));
sb.append(raw.substring(8, 12));
sb.append(raw.substring(12, 16));
sb.append(raw.substring(16, 20));
sb.append(raw.substring(20));
return sb.toString();
}
static {
long secureInitializer = mySecureRand.nextLong();
myRand = new Random(secureInitializer);
try {
s_id = InetAddress.getLocalHost().toString();
} catch (UnknownHostException var3) {
var3.printStackTrace();
}
}
}
package com.wechat.common.utils;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
public class SM3Utills {
private static final String ENCODING = "UTF-8";
public static String encrypt(String paramStr) {
String resultHexString = "";
try {
byte[] srcData = paramStr.getBytes("UTF-8");
byte[] resultHash = hash(srcData);
resultHexString = ByteUtils.toHexString(resultHash);
} catch (UnsupportedEncodingException var4) {
var4.printStackTrace();
}
return resultHexString;
}
public static byte[] hash(byte[] srcData) {
SM3Digest digest = new SM3Digest();
digest.update(srcData, 0, srcData.length);
byte[] hash = new byte[digest.getDigestSize()];
digest.doFinal(hash, 0);
return hash;
}
public static void main(String[] args) {
String json = "{\"name\":\"Marydon\",\"website\":\"http://www.cnblogs.com/Marydon20170307\"}";
String hex = encrypt(json);
System.out.println(hex);
}
static {
Security.addProvider(new BouncyCastleProvider());
}
}
package com.wechat.common.utils;
import com.wechat.common.exception.CustomException;
import com.wechat.framework.security.LoginUser;
import com.wechat.project.system.domain.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class SecurityUtils {
public static String getUsername() {
try {
return getLoginUser().getUsername();
} catch (Exception var1) {
throw new CustomException("获取用户账户异常", 401);
}
}
public static String getUsernameDoctorID() {
try {
SysUser user = getLoginUser().getUser();
return user.getDoctorId();
} catch (Exception var1) {
throw new CustomException("获取用户账户异常", 401);
}
}
public static LoginUser getLoginUser() {
try {
return (LoginUser)getAuthentication().getPrincipal();
} catch (Exception var1) {
throw new CustomException("获取用户信息异常", 401);
}
}
public static Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
public static String encryptPassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password);
}
public static boolean matchesPassword(String rawPassword, String encodedPassword) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.matches(rawPassword, encodedPassword);
}
public static boolean isAdmin(Long userId) {
return userId != null && 1L == userId;
}
}
package com.wechat.common.utils;
import com.wechat.common.core.text.Convert;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class ServletUtils {
public static String getParameter(String name) {
return getRequest().getParameter(name);
}
public static String getParameter(String name, String defaultValue) {
return Convert.toStr(getRequest().getParameter(name), defaultValue);
}
public static Integer getParameterToInt(String name) {
return Convert.toInt(getRequest().getParameter(name));
}
public static Integer getParameterToInt(String name, Integer defaultValue) {
return Convert.toInt(getRequest().getParameter(name), defaultValue);
}
public static HttpServletRequest getRequest() {
return getRequestAttributes().getRequest();
}
public static HttpServletResponse getResponse() {
return getRequestAttributes().getResponse();
}
public static HttpSession getSession() {
return getRequest().getSession();
}
public static ServletRequestAttributes getRequestAttributes() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes)attributes;
}
public static String renderString(HttpServletResponse response, String string) {
try {
response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
} catch (IOException var3) {
var3.printStackTrace();
}
return null;
}
public static boolean isAjaxRequest(HttpServletRequest request) {
String accept = request.getHeader("accept");
if (accept != null && accept.indexOf("application/json") != -1) {
return true;
} else {
String xRequestedWith = request.getHeader("X-Requested-With");
if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
return true;
} else {
String uri = request.getRequestURI();
if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) {
return true;
} else {
String ajax = request.getParameter("__ajax");
return StringUtils.inStringIgnoreCase(ajax, "json", "xml");
}
}
}
}
}
package com.wechat.common.utils;
import com.wechat.common.core.text.StrFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class StringUtils extends org.apache.commons.lang3.StringUtils {
private static final String NULLSTR = "";
private static final char SEPARATOR = '_';
public static <T> T nvl(T value, T defaultValue) {
return value != null ? value : defaultValue;
}
public static boolean isEmpty(Collection<?> coll) {
return isNull(coll) || coll.isEmpty();
}
public static boolean isNotEmpty(Collection<?> coll) {
return !isEmpty(coll);
}
public static boolean isEmpty(Object[] objects) {
return isNull(objects) || objects.length == 0;
}
public static boolean isNotEmpty(Object[] objects) {
return !isEmpty(objects);
}
public static boolean isEmpty(Map<?, ?> map) {
return isNull(map) || map.isEmpty();
}
public static boolean isNotEmpty(Map<?, ?> map) {
return !isEmpty(map);
}
public static boolean isEmpty(String str) {
return isNull(str) || "".equals(str.trim());
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
public static boolean isNull(Object object) {
return object == null;
}
public static boolean isNotNull(Object object) {
return !isNull(object);
}
public static boolean isArray(Object object) {
return isNotNull(object) && object.getClass().isArray();
}
public static String trim(String str) {
return str == null ? "" : str.trim();
}
public static String substring(final String str, int start) {
if (str == null) {
return "";
} else {
if (start < 0) {
start += str.length();
}
if (start < 0) {
start = 0;
}
return start > str.length() ? "" : str.substring(start);
}
}
public static String substring(final String str, int start, int end) {
if (str == null) {
return "";
} else {
if (end < 0) {
end += str.length();
}
if (start < 0) {
start += str.length();
}
if (end > str.length()) {
end = str.length();
}
if (start > end) {
return "";
} else {
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
}
}
public static String format(String template, Object... params) {
return !isEmpty(params) && !isEmpty(template) ? StrFormatter.format(template, params) : template;
}
public static final Set<String> str2Set(String str, String sep) {
return new HashSet<>(str2List(str, sep, true, false));
}
public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
List<String> list = new ArrayList<>();
if (isEmpty(str)) {
return list;
} else if (filterBlank && isBlank(str)) {
return list;
} else {
String[] split = str.split(sep);
for (String string : split) {
if (!filterBlank || !isBlank(string)) {
if (trim) {
string = string.trim();
}
list.add(string);
}
}
return list;
}
}
public static String toUnderScoreCase(String str) {
if (str == null) {
return null;
} else {
StringBuilder sb = new StringBuilder();
boolean preCharIsUpperCase = true;
boolean curreCharIsUpperCase = true;
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i > 0) {
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
} else {
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c);
if (i < str.length() - 1) {
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
sb.append('_');
} else if (i != 0 && !preCharIsUpperCase && curreCharIsUpperCase) {
sb.append('_');
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
}
public static boolean inStringIgnoreCase(String str, String... strs) {
if (str != null && strs != null) {
for (String s : strs) {
if (str.equalsIgnoreCase(trim(s))) {
return true;
}
}
}
return false;
}
public static String convertToCamelCase(String name) {
StringBuilder result = new StringBuilder();
if (name != null && !name.isEmpty()) {
if (!name.contains("_")) {
return name.substring(0, 1).toUpperCase() + name.substring(1);
} else {
String[] camels = name.split("_");
for (String camel : camels) {
if (!camel.isEmpty()) {
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
}
return result.toString();
}
} else {
return "";
}
}
public static String toCamelCase(String s) {
if (s == null) {
return null;
} else {
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '_') {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
}
public static String trimJsonAndXmlSplitChar(String text) {
String regEx = "[\n`~!@#$%^&*()+=|{}':;'\"/\\s+/g,,\\[\\].<>/?~!@#¥%……&*()——+|{}':-]";
return text.replaceAll(regEx, "");
}
}
package com.wechat.common.utils;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Threads {
private static final Logger logger = LoggerFactory.getLogger(Threads.class);
public static void sleep(long milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException var3) {
}
}
public static void shutdownAndAwaitTermination(ExecutorService pool) {
if (pool != null && !pool.isShutdown()) {
pool.shutdown();
try {
if (!pool.awaitTermination(120L, TimeUnit.SECONDS)) {
pool.shutdownNow();
if (!pool.awaitTermination(120L, TimeUnit.SECONDS)) {
logger.info("Pool did not terminate");
}
}
} catch (InterruptedException var2) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
public static void printException(Runnable r, Throwable t) {
if (t == null && r instanceof Future) {
try {
Future<?> future = (Future<?>)r;
if (future.isDone()) {
future.get();
}
} catch (CancellationException var3) {
t = var3;
} catch (ExecutionException var4) {
t = var4.getCause();
} catch (InterruptedException var5) {
Thread.currentThread().interrupt();
}
}
if (t != null) {
logger.error(t.getMessage(), t);
}
}
}
package com.wechat.common.utils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
import javax.imageio.ImageIO;
public class VerifyCodeUtils {
public static final String VERIFY_CODES = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new SecureRandom();
public static String generateVerifyCode(int verifySize) {
return generateVerifyCode(verifySize, "123456789ABCDEFGHJKLMNPQRSTUVWXYZ");
}
public static String generateVerifyCode(int verifySize, String sources) {
if (sources == null || sources.length() == 0) {
sources = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++) {
verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, 1);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW};
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);
g2.fillRect(0, 2, w, h - 4);
float yawpRate = 0.05F;
int area = (int)(yawpRate * (float)w * (float)h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
g2.setColor(getRandColor(100, 160));
int fontSize = h - 4;
Font font = new Font("Algerian", 2, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++) {
AffineTransform affine = new AffineTransform();
g2.setTransform(affine);
g2.drawChars(chars, i, 1, (w - 10) / verifySize * i + 5, h / 2 + fontSize / 2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
private static Color getRandColor(int fc, int bc) {
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color <<= 8;
color |= c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double)(period >> 1) * Math.sin((double)i / (double)period + (Math.PI * 2) * (double)phase / (double)frames);
g.copyArea(0, i, w1, 1, (int)d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int)d, i, 0, i);
g.drawLine((int)d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double)(period >> 1) * Math.sin((double)i / (double)period + (Math.PI * 2) * (double)phase / (double)frames);
g.copyArea(i, 0, 1, h1, 0, (int)d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int)d, i, 0);
g.drawLine(i, (int)d + h1, i, h1);
}
}
}
}
package com.wechat.common.utils.bean;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BeanUtils extends org.springframework.beans.BeanUtils {
private static final int BEAN_METHOD_PROP_INDEX = 3;
private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)");
private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)");
public static void copyBeanProp(Object dest, Object src) {
try {
copyProperties(src, dest);
} catch (Exception var3) {
var3.printStackTrace();
}
}
public static List<Method> getSetterMethods(Object obj) {
List<Method> setterMethods = new ArrayList<>();
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
Matcher m = SET_PATTERN.matcher(method.getName());
if (m.matches() && method.getParameterTypes().length == 1) {
setterMethods.add(method);
}
}
return setterMethods;
}
public static List<Method> getGetterMethods(Object obj) {
List<Method> getterMethods = new ArrayList<>();
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
Matcher m = GET_PATTERN.matcher(method.getName());
if (m.matches() && method.getParameterTypes().length == 0) {
getterMethods.add(method);
}
}
return getterMethods;
}
public static boolean isMethodPropEquals(String m1, String m2) {
return m1.substring(3).equals(m2.substring(3));
}
}
package com.wechat.common.utils.file;
import com.wechat.common.exception.file.FileNameLengthLimitExceededException;
import com.wechat.common.exception.file.FileSizeLimitExceededException;
import com.wechat.common.exception.file.InvalidExtensionException;
import com.wechat.common.utils.DateUtils;
import com.wechat.common.utils.StringUtils;
import com.wechat.common.utils.security.Md5Utils;
import com.wechat.framework.config.WechatConfig;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileUploadUtils {
public static final long DEFAULT_MAX_SIZE = 52428800L;
public static final int DEFAULT_FILE_NAME_LENGTH = 100;
private static String defaultBaseDir = WechatConfig.getProfile();
private static int counter = 0;
public static void setDefaultBaseDir(String defaultBaseDir) {
FileUploadUtils.defaultBaseDir = defaultBaseDir;
}
public static String getDefaultBaseDir() {
return defaultBaseDir;
}
public static final String upload(MultipartFile file) throws IOException {
try {
return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
} catch (Exception var2) {
throw new IOException(var2.getMessage(), var2);
}
}
public static final String upload(String baseDir, MultipartFile file) throws IOException {
try {
return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
} catch (Exception var3) {
throw new IOException(var3.getMessage(), var3);
}
}
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException {
int fileNamelength = file.getOriginalFilename().length();
if (fileNamelength > 100) {
throw new FileNameLengthLimitExceededException(100);
} else {
assertAllowed(file, allowedExtension);
String fileName = extractFilename(file);
File desc = getAbsoluteFile(baseDir, fileName);
System.out.println(desc);
file.transferTo(desc);
return getPathFileName(baseDir, fileName);
}
}
public static final String extractFilename(MultipartFile file) {
String fileName = file.getOriginalFilename();
String extension = getExtension(file);
return DateUtils.datePath() + "/" + encodingFilename(fileName) + "." + extension;
}
private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
File desc = new File(uploadDir + File.separator + fileName);
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
if (!desc.exists()) {
desc.createNewFile();
}
return desc;
}
private static final String getPathFileName(String uploadDir, String fileName) throws IOException {
int dirLastIndex = WechatConfig.getProfile().length() + 1;
String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
return "/profile/" + currentDir + "/" + fileName;
}
private static final String encodingFilename(String fileName) {
fileName = fileName.replace("_", " ");
return Md5Utils.hash(fileName + System.nanoTime() + counter++);
}
public static final void assertAllowed(MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, InvalidExtensionException {
long size = file.getSize();
if (size > 52428800L) {
throw new FileSizeLimitExceededException(50L);
} else {
String fileName = file.getOriginalFilename();
String extension = getExtension(file);
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, fileName);
} else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, fileName);
} else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, fileName);
} else {
throw new InvalidExtensionException(allowedExtension, extension, fileName);
}
}
}
}
public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
for (String str : allowedExtension) {
if (str.equalsIgnoreCase(extension)) {
return true;
}
}
return false;
}
public static final String getExtension(MultipartFile file) {
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if (StringUtils.isEmpty(extension)) {
extension = MimeTypeUtils.getExtension(file.getContentType());
}
return extension;
}
}
package com.wechat.common.utils.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
public class FileUtils extends org.apache.commons.io.FileUtils {
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
public static void writeBytes(String filePath, OutputStream os) throws IOException {
FileInputStream fis = null;
try {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0) {
os.write(b, 0, length);
}
} catch (IOException var16) {
throw var16;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException var15) {
var15.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException var14) {
var14.printStackTrace();
}
}
}
}
public static boolean deleteFile(String filePath) {
boolean flag = false;
File file = new File(filePath);
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
public static boolean isValidFilename(String filename) {
return filename.matches(FILENAME_PATTERN);
}
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
String agent = request.getHeader("USER-AGENT");
String var4;
if (agent.contains("MSIE")) {
var4 = URLEncoder.encode(fileName, "utf-8");
var4 = var4.replace("+", " ");
} else if (agent.contains("Firefox")) {
var4 = new String(fileName.getBytes(), "ISO8859-1");
} else if (agent.contains("Chrome")) {
var4 = URLEncoder.encode(fileName, "utf-8");
} else {
var4 = URLEncoder.encode(fileName, "utf-8");
}
return var4;
}
}
package com.wechat.common.utils.file;
public class MimeTypeUtils {
public static final String IMAGE_PNG = "image/png";
public static final String IMAGE_JPG = "image/jpg";
public static final String IMAGE_JPEG = "image/jpeg";
public static final String IMAGE_BMP = "image/bmp";
public static final String IMAGE_GIF = "image/gif";
public static final String[] IMAGE_EXTENSION = new String[]{"bmp", "gif", "jpg", "jpeg", "png"};
public static final String[] FLASH_EXTENSION = new String[]{"swf", "flv"};
public static final String[] MEDIA_EXTENSION = new String[]{"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb"};
public static final String[] DEFAULT_ALLOWED_EXTENSION = new String[]{
"bmp", "gif", "jpg", "jpeg", "png", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt", "rar", "zip", "gz", "bz2", "pdf"
};
public static String getExtension(String prefix) {
switch (prefix) {
case "image/png":
return "png";
case "image/jpg":
return "jpg";
case "image/jpeg":
return "jpeg";
case "image/bmp":
return "bmp";
case "image/gif":
return "gif";
default:
return "";
}
}
}
package com.wechat.common.utils.html;
import com.wechat.common.utils.StringUtils;
public class EscapeUtil {
public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)";
private static final char[][] TEXT = new char[64][];
public static String escape(String text) {
return encode(text);
}
public static String unescape(String content) {
return decode(content);
}
public static String clean(String content) {
return content.replaceAll("(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)", "");
}
private static String encode(String text) {
int len;
if (text != null && (len = text.length()) != 0) {
StringBuilder buffer = new StringBuilder(len + (len >> 2));
for (int i = 0; i < len; i++) {
char c = text.charAt(i);
if (c < '@') {
buffer.append(TEXT[c]);
} else {
buffer.append(c);
}
}
return buffer.toString();
} else {
return "";
}
}
public static String decode(String content) {
if (StringUtils.isEmpty(content)) {
return content;
} else {
StringBuilder tmp = new StringBuilder(content.length());
int lastPos = 0;
int pos = 0;
while (lastPos < content.length()) {
pos = content.indexOf("%", lastPos);
if (pos == lastPos) {
if (content.charAt(pos + 1) == 'u') {
char ch = (char)Integer.parseInt(content.substring(pos + 2, pos + 6), 16);
tmp.append(ch);
lastPos = pos + 6;
} else {
char ch = (char)Integer.parseInt(content.substring(pos + 1, pos + 3), 16);
tmp.append(ch);
lastPos = pos + 3;
}
} else if (pos == -1) {
tmp.append(content.substring(lastPos));
lastPos = content.length();
} else {
tmp.append(content.substring(lastPos, pos));
lastPos = pos;
}
}
return tmp.toString();
}
}
public static void main(String[] args) {
String html = "<script>alert(1);</script>";
System.out.println(clean(html));
System.out.println(escape(html));
System.out.println(unescape(html));
}
static {
for (int i = 0; i < 64; i++) {
TEXT[i] = new char[]{(char)i};
}
TEXT[39] = "&#039;".toCharArray();
TEXT[34] = "&#34;".toCharArray();
TEXT[38] = "&#38;".toCharArray();
TEXT[60] = "&#60;".toCharArray();
TEXT[62] = "&#62;".toCharArray();
}
}
package com.wechat.common.utils.ip;
import com.alibaba.fastjson.JSONObject;
import com.wechat.common.utils.StringUtils;
import com.wechat.common.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AddressUtils {
private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";
public static String getRealAddressByIP(String ip) {
String address = "XX XX";
if (IpUtils.internalIp(ip)) {
return "内网IP";
} else {
String rspStr = HttpUtils.sendPost("http://ip.taobao.com/service/getIpInfo.php", "ip=" + ip);
if (StringUtils.isEmpty(rspStr)) {
log.error("获取地理位置异常 {}", ip);
return address;
} else {
JSONObject obj = JSONObject.parseObject(rspStr);
JSONObject data = (JSONObject)obj.getObject("data", JSONObject.class);
String region = data.getString("region");
String city = data.getString("city");
return region + " " + city;
}
}
}
}
package com.wechat.common.utils.ip;
import com.wechat.common.utils.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* 获取IP方法
*
* @author guopx
*/
public class IpUtils
{
public static String getIpAddr(HttpServletRequest request)
{
if (request == null)
{
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
public static boolean internalIp(String ip)
{
byte[] addr = textToNumericFormatV4(ip);
return internalIp(addr) || "127.0.0.1".equals(ip);
}
private static boolean internalIp(byte[] addr)
{
if (StringUtils.isNull(addr) || addr.length < 2)
{
return true;
}
final byte b0 = addr[0];
final byte b1 = addr[1];
// 10.x.x.x/8
final byte SECTION_1 = 0x0A;
// 172.16.x.x/12
final byte SECTION_2 = (byte) 0xAC;
final byte SECTION_3 = (byte) 0x10;
final byte SECTION_4 = (byte) 0x1F;
// 192.168.x.x/16
final byte SECTION_5 = (byte) 0xC0;
final byte SECTION_6 = (byte) 0xA8;
switch (b0)
{
case SECTION_1:
return true;
case SECTION_2:
if (b1 >= SECTION_3 && b1 <= SECTION_4)
{
return true;
}
case SECTION_5:
switch (b1)
{
case SECTION_6:
return true;
}
default:
return false;
}
}
/**
* 将IPv4地址转换成字节
*
* @param text IPv4地址
* @return byte 字节
*/
public static byte[] textToNumericFormatV4(String text)
{
if (text.length() == 0)
{
return null;
}
byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1);
try
{
long l;
int i;
switch (elements.length)
{
case 1:
l = Long.parseLong(elements[0]);
if ((l < 0L) || (l > 4294967295L))
return null;
bytes[0] = (byte) (int) (l >> 24 & 0xFF);
bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 2:
l = Integer.parseInt(elements[0]);
if ((l < 0L) || (l > 255L))
return null;
bytes[0] = (byte) (int) (l & 0xFF);
l = Integer.parseInt(elements[1]);
if ((l < 0L) || (l > 16777215L))
return null;
bytes[1] = (byte) (int) (l >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 3:
for (i = 0; i < 2; ++i)
{
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L))
return null;
bytes[i] = (byte) (int) (l & 0xFF);
}
l = Integer.parseInt(elements[2]);
if ((l < 0L) || (l > 65535L))
return null;
bytes[2] = (byte) (int) (l >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 4:
for (i = 0; i < 4; ++i)
{
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L))
return null;
bytes[i] = (byte) (int) (l & 0xFF);
}
break;
default:
return null;
}
}
catch (NumberFormatException e)
{
return null;
}
return bytes;
}
public static String getHostIp()
{
try
{
return InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException e)
{
}
return "127.0.0.1";
}
public static String getHostName()
{
try
{
return InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e)
{
}
return "未知";
}
}
\ No newline at end of file
package com.wechat.common.utils.job;
import com.wechat.common.utils.ExceptionUtil;
import com.wechat.common.utils.StringUtils;
import com.wechat.common.utils.bean.BeanUtils;
import com.wechat.common.utils.spring.SpringUtils;
import com.wechat.project.monitor.domain.SysJob;
import com.wechat.project.monitor.domain.SysJobLog;
import com.wechat.project.monitor.service.ISysJobLogService;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractQuartzJob implements Job {
private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);
private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();
public void execute(JobExecutionContext context) throws JobExecutionException {
SysJob sysJob = new SysJob();
BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get("TASK_PROPERTIES"));
try {
this.before(context, sysJob);
if (sysJob != null) {
this.doExecute(context, sysJob);
}
this.after(context, sysJob, null);
} catch (Exception var4) {
log.error("任务执行异常 - :", var4);
this.after(context, sysJob, var4);
}
}
protected void before(JobExecutionContext context, SysJob sysJob) {
threadLocal.set(new Date());
}
protected void after(JobExecutionContext context, SysJob sysJob, Exception e) {
Date startTime = threadLocal.get();
threadLocal.remove();
SysJobLog sysJobLog = new SysJobLog();
sysJobLog.setJobName(sysJob.getJobName());
sysJobLog.setJobGroup(sysJob.getJobGroup());
sysJobLog.setInvokeTarget(sysJob.getInvokeTarget());
sysJobLog.setStartTime(startTime);
sysJobLog.setStopTime(new Date());
long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒");
if (e != null) {
sysJobLog.setStatus("1");
String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
sysJobLog.setExceptionInfo(errorMsg);
} else {
sysJobLog.setStatus("0");
}
SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog);
}
protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception;
}
package com.wechat.common.utils.job;
import java.text.ParseException;
import java.util.Date;
import org.quartz.CronExpression;
public class CronUtils {
public static boolean isValid(String cronExpression) {
return CronExpression.isValidExpression(cronExpression);
}
public static String getInvalidMessage(String cronExpression) {
try {
new CronExpression(cronExpression);
return null;
} catch (ParseException var2) {
return var2.getMessage();
}
}
public static Date getNextExecution(String cronExpression) {
try {
CronExpression cron = new CronExpression(cronExpression);
return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis()));
} catch (ParseException var2) {
throw new IllegalArgumentException(var2.getMessage());
}
}
}
package com.wechat.common.utils.job;
import com.wechat.common.utils.StringUtils;
import com.wechat.common.utils.spring.SpringUtils;
import com.wechat.project.monitor.domain.SysJob;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
public class JobInvokeUtil {
public static void invokeMethod(SysJob sysJob) throws Exception {
String invokeTarget = sysJob.getInvokeTarget();
String beanName = getBeanName(invokeTarget);
String methodName = getMethodName(invokeTarget);
List<Object[]> methodParams = getMethodParams(invokeTarget);
if (!isValidClassName(beanName)) {
Object bean = SpringUtils.getBean(beanName);
invokeMethod(bean, methodName, methodParams);
} else {
Object bean = Class.forName(beanName).newInstance();
invokeMethod(bean, methodName, methodParams);
}
}
private static void invokeMethod(Object bean, String methodName, List<Object[]> methodParams) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (StringUtils.isNotNull(methodParams) && methodParams.size() > 0) {
Method method = bean.getClass().getDeclaredMethod(methodName, getMethodParamsType(methodParams));
method.invoke(bean, getMethodParamsValue(methodParams));
} else {
Method method = bean.getClass().getDeclaredMethod(methodName);
method.invoke(bean);
}
}
public static boolean isValidClassName(String invokeTarget) {
return StringUtils.countMatches(invokeTarget, ".") > 1;
}
public static String getBeanName(String invokeTarget) {
String beanName = StringUtils.substringBefore(invokeTarget, "(");
return StringUtils.substringBeforeLast(beanName, ".");
}
public static String getMethodName(String invokeTarget) {
String methodName = StringUtils.substringBefore(invokeTarget, "(");
return StringUtils.substringAfterLast(methodName, ".");
}
public static List<Object[]> getMethodParams(String invokeTarget) {
String methodStr = StringUtils.substringBetween(invokeTarget, "(", ")");
if (StringUtils.isEmpty(methodStr)) {
return null;
} else {
String[] methodParams = methodStr.split(",");
List<Object[]> classs = new LinkedList<>();
for (int i = 0; i < methodParams.length; i++) {
String str = StringUtils.trimToEmpty(methodParams[i]);
if (StringUtils.contains(str, "'")) {
classs.add(new Object[]{StringUtils.replace(str, "'", ""), String.class});
} else if (StringUtils.equals(str, "true") || StringUtils.equalsIgnoreCase(str, "false")) {
classs.add(new Object[]{Boolean.valueOf(str), Boolean.class});
} else if (StringUtils.containsIgnoreCase(str, "L")) {
classs.add(new Object[]{Long.valueOf(StringUtils.replaceIgnoreCase(str, "L", "")), Long.class});
} else if (StringUtils.containsIgnoreCase(str, "D")) {
classs.add(new Object[]{Double.valueOf(StringUtils.replaceIgnoreCase(str, "D", "")), Double.class});
} else {
classs.add(new Object[]{Integer.valueOf(str), Integer.class});
}
}
return classs;
}
}
public static Class<?>[] getMethodParamsType(List<Object[]> methodParams) {
Class<?>[] classs = new Class[methodParams.size()];
int index = 0;
for (Object[] os : methodParams) {
classs[index] = (Class<?>)os[1];
index++;
}
return classs;
}
public static Object[] getMethodParamsValue(List<Object[]> methodParams) {
Object[] classs = new Object[methodParams.size()];
int index = 0;
for (Object[] os : methodParams) {
classs[index] = os[0];
index++;
}
return classs;
}
}
package com.wechat.common.utils.job;
import com.wechat.project.monitor.domain.SysJob;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
@DisallowConcurrentExecution
public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob {
@Override
protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception {
JobInvokeUtil.invokeMethod(sysJob);
}
}
package com.wechat.common.utils.job;
import com.wechat.project.monitor.domain.SysJob;
import org.quartz.JobExecutionContext;
public class QuartzJobExecution extends AbstractQuartzJob {
@Override
protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception {
JobInvokeUtil.invokeMethod(sysJob);
}
}
package com.wechat.common.utils.job;
import com.wechat.common.constant.ScheduleConstants;
import com.wechat.common.exception.job.TaskException;
import com.wechat.project.monitor.domain.SysJob;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
public class ScheduleUtils {
private static Class<? extends Job> getQuartzJobClass(SysJob sysJob) {
boolean isConcurrent = "0".equals(sysJob.getConcurrent());
return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class;
}
public static TriggerKey getTriggerKey(Long jobId, String jobGroup) {
return TriggerKey.triggerKey("TASK_CLASS_NAME" + jobId, jobGroup);
}
public static JobKey getJobKey(Long jobId, String jobGroup) {
return JobKey.jobKey("TASK_CLASS_NAME" + jobId, jobGroup);
}
public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException {
Class<? extends Job> jobClass = getQuartzJobClass(job);
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobId, jobGroup)).build();
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder);
CronTrigger trigger = (CronTrigger)TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId, jobGroup)).withSchedule(cronScheduleBuilder).build();
jobDetail.getJobDataMap().put("TASK_PROPERTIES", job);
if (scheduler.checkExists(getJobKey(jobId, jobGroup))) {
scheduler.deleteJob(getJobKey(jobId, jobGroup));
}
scheduler.scheduleJob(jobDetail, trigger);
if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) {
scheduler.pauseJob(getJobKey(jobId, jobGroup));
}
}
public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb) throws TaskException {
String var2 = job.getMisfirePolicy();
switch (var2) {
case "0":
return cb;
case "1":
return cb.withMisfireHandlingInstructionIgnoreMisfires();
case "2":
return cb.withMisfireHandlingInstructionFireAndProceed();
case "3":
return cb.withMisfireHandlingInstructionDoNothing();
default:
throw new TaskException(
"The task misfire policy '" + job.getMisfirePolicy() + "' cannot be used in cron schedule tasks", TaskException.Code.CONFIG_ERROR
);
}
}
}
package com.wechat.common.utils.security;
import java.security.MessageDigest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Md5Utils {
private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
private static byte[] md5(String s) {
try {
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(s.getBytes("UTF-8"));
return algorithm.digest();
} catch (Exception var3) {
log.error("MD5 Error...", var3);
return null;
}
}
private static final String toHex(byte[] hash) {
if (hash == null) {
return null;
} else {
StringBuffer buf = new StringBuffer(hash.length * 2);
for (int i = 0; i < hash.length; i++) {
if ((hash[i] & 255) < 16) {
buf.append("0");
}
buf.append(Long.toString((long)(hash[i] & 255), 16));
}
return buf.toString();
}
}
public static String hash(String s) {
try {
return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
} catch (Exception var2) {
log.error("not supported charset...{}", var2);
return s;
}
}
}
package com.wechat.common.utils.sign;
public final class Base64 {
private static final int BASELENGTH = 128;
private static final int LOOKUPLENGTH = 64;
private static final int TWENTYFOURBITGROUP = 24;
private static final int EIGHTBIT = 8;
private static final int SIXTEENBIT = 16;
private static final int FOURBYTE = 4;
private static final int SIGN = -128;
private static final char PAD = '=';
private static final byte[] base64Alphabet = new byte[128];
private static final char[] lookUpBase64Alphabet = new char[64];
private static boolean isWhiteSpace(char octect) {
return octect == ' ' || octect == '\r' || octect == '\n' || octect == '\t';
}
private static boolean isPad(char octect) {
return octect == '=';
}
private static boolean isData(char octect) {
return octect < 128 && base64Alphabet[octect] != -1;
}
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
} else {
int lengthDataBits = binaryData.length * 8;
if (lengthDataBits == 0) {
return "";
} else {
int fewerThan24bits = lengthDataBits % 24;
int numberTriplets = lengthDataBits / 24;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
char[] encodedData = null;
encodedData = new char[numberQuartet * 4];
byte k = 0;
byte l = 0;
byte b1 = 0;
byte b2 = 0;
byte b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
l = (byte)(b2 & 15);
k = (byte)(b1 & 3);
byte val1 = (b1 & -128) == 0 ? (byte)(b1 >> 2) : (byte)(b1 >> 2 ^ 192);
byte val2 = (b2 & -128) == 0 ? (byte)(b2 >> 4) : (byte)(b2 >> 4 ^ 240);
byte val3 = (b3 & -128) == 0 ? (byte)(b3 >> 6) : (byte)(b3 >> 6 ^ 252);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | k << 4];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2 | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 63];
}
if (fewerThan24bits == 8) {
b1 = binaryData[dataIndex];
k = (byte)(b1 & 3);
byte val1 = (b1 & -128) == 0 ? (byte)(b1 >> 2) : (byte)(b1 >> 2 ^ 192);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = '=';
encodedData[encodedIndex++] = '=';
} else if (fewerThan24bits == 16) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte)(b2 & 15);
k = (byte)(b1 & 3);
byte val1 = (b1 & -128) == 0 ? (byte)(b1 >> 2) : (byte)(b1 >> 2 ^ 192);
byte val2 = (b2 & -128) == 0 ? (byte)(b2 >> 4) : (byte)(b2 >> 4 ^ 240);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | k << 4];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = '=';
}
return new String(encodedData);
}
}
}
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
} else {
char[] base64Data = encoded.toCharArray();
int len = removeWhiteSpace(base64Data);
if (len % 4 != 0) {
return null;
} else {
int numberQuadruple = len / 4;
if (numberQuadruple == 0) {
return new byte[0];
} else {
byte[] decodedData = null;
byte b1 = 0;
byte b2 = 0;
byte b3 = 0;
byte b4 = 0;
char d1 = '\u0000';
char d2 = '\u0000';
char d3 = '\u0000';
char d4 = '\u0000';
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
for (decodedData = new byte[numberQuadruple * 3]; i < numberQuadruple - 1; i++) {
if (!isData(d1 = base64Data[dataIndex++])
|| !isData(d2 = base64Data[dataIndex++])
|| !isData(d3 = base64Data[dataIndex++])
|| !isData(d4 = base64Data[dataIndex++])) {
return null;
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte)((b2 & 15) << 4 | b3 >> 2 & 15);
decodedData[encodedIndex++] = (byte)(b3 << 6 | b4);
}
if (isData(d1 = base64Data[dataIndex++]) && isData(d2 = base64Data[dataIndex++])) {
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (isData(d3) && isData(d4)) {
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte)((b2 & 15) << 4 | b3 >> 2 & 15);
decodedData[encodedIndex++] = (byte)(b3 << 6 | b4);
return decodedData;
} else if (isPad(d3) && isPad(d4)) {
if ((b2 & 15) != 0) {
return null;
} else {
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte)(b1 << 2 | b2 >> 4);
return tmp;
}
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 3) != 0) {
return null;
} else {
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte)((b2 & 15) << 4 | b3 >> 2 & 15);
return tmp;
}
} else {
return null;
}
} else {
return null;
}
}
}
}
}
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
} else {
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}
static {
for (int i = 0; i < 128; i++) {
base64Alphabet[i] = -1;
}
for (int i = 90; i >= 65; i--) {
base64Alphabet[i] = (byte)(i - 65);
}
for (int i = 122; i >= 97; i--) {
base64Alphabet[i] = (byte)(i - 97 + 26);
}
for (int i = 57; i >= 48; i--) {
base64Alphabet[i] = (byte)(i - 48 + 52);
}
base64Alphabet[43] = 62;
base64Alphabet[47] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char)(65 + i);
}
int i = 26;
for (int j = 0; i <= 51; j++) {
lookUpBase64Alphabet[i] = (char)(97 + j);
i++;
}
i = 52;
for (int j = 0; i <= 61; j++) {
lookUpBase64Alphabet[i] = (char)(48 + j);
i++;
}
lookUpBase64Alphabet[62] = '+';
lookUpBase64Alphabet[63] = '/';
}
}
package com.wechat.common.utils.spring;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
@Component
public final class SpringUtils implements BeanFactoryPostProcessor {
private static ConfigurableListableBeanFactory beanFactory;
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtils.beanFactory = beanFactory;
}
public static <T> T getBean(String name) throws BeansException {
return (T)beanFactory.getBean(name);
}
public static <T> T getBean(Class<T> clz) throws BeansException {
return (T)beanFactory.getBean(clz);
}
public static boolean containsBean(String name) {
return beanFactory.containsBean(name);
}
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return beanFactory.isSingleton(name);
}
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getType(name);
}
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getAliases(name);
}
public static <T> T getAopProxy(T invoker) {
return (T)AopContext.currentProxy();
}
}
package com.wechat.common.utils.sql;
import com.wechat.common.utils.StringUtils;
public class SqlUtil {
public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,]+";
public static String escapeOrderBySql(String value) {
return StringUtils.isNotEmpty(value) && !isValidOrderBySql(value) ? "" : value;
}
public static boolean isValidOrderBySql(String value) {
return value.matches(SQL_PATTERN);
}
}
package com.wechat.common.utils.xml;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
public class PropertiesUtil {
private Properties properties = null;
private static PropertiesUtil instance = null;
private static String FILE_PATH = "system.properties";
public static PropertiesUtil getInstance() {
if (instance == null) {
instance = new PropertiesUtil();
}
return instance;
}
public PropertiesUtil() {
this.properties = new Properties();
try {
InputStreamReader input = new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(FILE_PATH), "UTF-8");
this.properties.load(input);
input.close();
} catch (IOException var2) {
var2.printStackTrace();
}
}
public Properties getProperties() {
return this.properties;
}
public String get(String key) {
return this.properties.getProperty(key);
}
public String get(String key, String defaultValue) {
return this.properties.getProperty(key, defaultValue);
}
}
package com.wechat.common.webserviceClient;
import com.alibaba.fastjson.JSONObject;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class WebServiceClient {
protected final Logger logger = LoggerFactory.getLogger(WebServiceClient.class);
public static String subWebService(String json) throws Exception {
String requestXml = JSONObject.toJSON(json).toString();
System.out.println("调用发布数据集服务:" + requestXml);
try {
String endpoint = "http://10.0.10.18:8080/datacenter/rpc/webservice/SubscriptionService?wsdl";
String webServiceNameSpace = "http://server.webservice.rpc.win.org/";
String webServiceMethod = "saveDataSetJson";
Service service = new Service();
Call call = (Call)service.createCall();
call.setTargetEndpointAddress(endpoint);
call.setOperationName(new QName(webServiceNameSpace, webServiceMethod));
call.addParameter("a", XMLType.XSD_STRING, ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
String responseXml = (String)call.invoke(new Object[]{requestXml});
System.out.println(responseXml);
return responseXml;
} catch (ServiceException var8) {
var8.printStackTrace();
throw new ServiceException("调用发布数据集服务异常", var8);
}
}
public static void main(String[] args) {
String json = "{\"parameters\":{\"sourcetype\":\"I\",\"sourceid\":\"YJYY\"},\"D02023\":[{\"DE06.00.151.08\":\"3358230_06301002D\",\"DE01.00.008.00\":\"3358230\",\"DE02.01.039.65\":\"普国银\",\"DE06.00.151.01\":\"2020-11-23 00:00:00\",\"DE06.00.048.02\":\"2020-11-23 00:00:00\",\"DE06.00.048.05\":\"16:30-17:00\",\"DE08.10.055.04\":\"2020-11-23 16:30:00\",\"DE08.10.055.05\":\"2020-11-23 17:00:00\",\"DE06.00.151.07\":\"A00504\",\"DE06.00.151.04\":\"1\",\"DE06.00.151.06\":\"001212\",\"DE04.30.020.00\":\"心脏彩超+心功能测定+室壁运动分析(TVI)\",\"DE04.30.020.04\":\"心血管超声队列\",\"DE01.00.051.53\":\"A\",\"DE01.00.018.12\":\"门诊2楼\",\"DE08.10.025.20\":\"0313\",\"DE88.00.001.00\":\"1.请在预约时段开始前5-20分钟到超声检查室登记。(早于20分钟无法登记)\\n2.预约当日有效,当日过后检查需重新预约。\",\"DE06.00.048.06\":\"20\"}]}";
try {
new WebServiceClient();
subWebService(json);
} catch (Exception var3) {
var3.printStackTrace();
}
}
}
package com.wechat.common.webserviceClient;
import com.alibaba.fastjson.JSONObject;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class XhWebServiceClient {
protected final Logger logger = LoggerFactory.getLogger(XhWebServiceClient.class);
public static String SubWebService(String map) throws Exception {
String requestXml = JSONObject.toJSON(map).toString();
System.out.println("调用esb发布数据集服务:" + requestXml);
String responseXml = "";
try {
String endpoint = "http://10.0.10.18:8080/datacenter/rpc/webservice/SubscriptionService?wsdl";
String webServiceNameSpace = "http://webservice.rpc.win.org/";
String webServiceMethod = "saveDataSetJson";
Service service = new Service();
Call call = (Call)service.createCall();
call.setTargetEndpointAddress(endpoint);
call.setOperationName(new QName(webServiceNameSpace, webServiceMethod));
call.addParameter("arg0", XMLType.XSD_STRING, ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
return (String)call.invoke(new Object[]{requestXml});
} catch (ServiceException var8) {
var8.printStackTrace();
System.out.println("调用发布数据接口异常:" + var8.getMessage());
throw new ServiceException("请求webservice服务异常", var8);
}
}
public static String SubWebServiceBySSO(String map) throws Exception {
String requestXml = JSONObject.toJSON(map).toString();
System.out.println("调用单点登录服务:" + requestXml);
String responseXml = "";
try {
String endpoint = "http://10.0.10.7:8283/SSOWebService.asmx?wsdl";
String webServiceNameSpace = "http://tempuri.org/";
String webServiceMethod = "GetSSOToken";
Service service = new Service();
Call call = (Call)service.createCall();
call.setTargetEndpointAddress(endpoint);
call.setOperationName(new QName(webServiceNameSpace, webServiceMethod));
call.addParameter("arg0", XMLType.XSD_STRING, ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
responseXml = (String)call.invoke(new Object[]{requestXml});
System.out.println("调用单点登录数据结果:" + responseXml);
return responseXml;
} catch (ServiceException var8) {
var8.printStackTrace();
System.out.println("调用单点登录数据接口异常:" + var8.getMessage());
throw new ServiceException("调用单点登录服务异常", var8);
}
}
public static void main(String[] args) {
String xml = "{\"parameters\":{\"pagerecord\":\"9999\",\"sharedatacode\":\"S00014\",\"pageno\":\"1\",\"ORGCODE\":\"66\",\"Reservationid\":\"P00202007030311380926074\"}}";
try {
new XhWebServiceClient();
SubWebService(xml);
} catch (Exception var3) {
var3.printStackTrace();
}
}
}
package com.wechat.common.xss;
import com.wechat.common.utils.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class XssFilter implements Filter {
public List<String> excludes = new ArrayList<>();
public boolean enabled = false;
public void init(FilterConfig filterConfig) throws ServletException {
String tempExcludes = filterConfig.getInitParameter("excludes");
String tempEnabled = filterConfig.getInitParameter("enabled");
if (StringUtils.isNotEmpty(tempExcludes)) {
String[] url = tempExcludes.split(",");
for (int i = 0; url != null && i < url.length; i++) {
this.excludes.add(url[i]);
}
}
if (StringUtils.isNotEmpty(tempEnabled)) {
this.enabled = Boolean.valueOf(tempEnabled);
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
if (this.handleExcludeURL(req, resp)) {
chain.doFilter(request, response);
} else {
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest)request);
chain.doFilter(xssRequest, response);
}
}
private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
if (!this.enabled) {
return true;
} else if (this.excludes != null && !this.excludes.isEmpty()) {
String url = request.getServletPath();
for (String pattern : this.excludes) {
Pattern p = Pattern.compile("^" + pattern);
Matcher m = p.matcher(url);
if (m.find()) {
return true;
}
}
return false;
} else {
return false;
}
}
public void destroy() {
}
}
package com.wechat.common.xss;
import com.wechat.common.utils.StringUtils;
import com.wechat.common.utils.html.EscapeUtil;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.io.IOUtils;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if (values == null) {
return super.getParameterValues(name);
} else {
int length = values.length;
String[] escapseValues = new String[length];
for (int i = 0; i < length; i++) {
escapseValues[i] = EscapeUtil.clean(values[i]).trim();
}
return escapseValues;
}
}
public ServletInputStream getInputStream() throws IOException {
if (!this.isJsonRequest()) {
return super.getInputStream();
} else {
String json = IOUtils.toString(super.getInputStream(), "utf-8");
if (StringUtils.isEmpty(json)) {
return super.getInputStream();
} else {
json = EscapeUtil.clean(json).trim();
final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
return new ServletInputStream() {
public boolean isFinished() {
return true;
}
public boolean isReady() {
return true;
}
public void setReadListener(ReadListener readListener) {
}
public int read() throws IOException {
return bis.read();
}
};
}
}
}
public boolean isJsonRequest() {
String header = super.getHeader("Content-Type");
return "application/json".equalsIgnoreCase(header) || "application/json;charset=UTF-8".equalsIgnoreCase(header);
}
}
package com.wechat.framework.aspectj;
import com.wechat.common.utils.ServletUtils;
import com.wechat.common.utils.StringUtils;
import com.wechat.common.utils.spring.SpringUtils;
import com.wechat.framework.aspectj.lang.annotation.DataScope;
import com.wechat.framework.security.LoginUser;
import com.wechat.framework.security.service.TokenService;
import com.wechat.framework.web.domain.BaseEntity;
import com.wechat.project.system.domain.SysRole;
import com.wechat.project.system.domain.SysUser;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class DataScopeAspect {
public static final String DATA_SCOPE_ALL = "1";
public static final String DATA_SCOPE_CUSTOM = "2";
public static final String DATA_SCOPE_DEPT = "3";
public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";
public static final String DATA_SCOPE_SELF = "5";
@Pointcut("@annotation(com.wechat.framework.aspectj.lang.annotation.DataScope)")
public void dataScopePointCut() {
}
@Before("dataScopePointCut()")
public void doBefore(JoinPoint point) throws Throwable {
this.handleDataScope(point);
}
protected void handleDataScope(final JoinPoint joinPoint) {
DataScope controllerDataScope = this.getAnnotationLog(joinPoint);
if (controllerDataScope != null) {
LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
SysUser currentUser = loginUser.getUser();
if (currentUser != null && !currentUser.isAdmin()) {
dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), controllerDataScope.userAlias());
}
}
}
public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) {
StringBuilder sqlString = new StringBuilder();
for (SysRole role : user.getRoles()) {
String dataScope = role.getDataScope();
if ("1".equals(dataScope)) {
sqlString = new StringBuilder();
break;
}
if ("2".equals(dataScope)) {
sqlString.append(StringUtils.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, role.getRoleId()));
} else if ("3".equals(dataScope)) {
sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
} else if ("4".equals(dataScope)) {
sqlString.append(
StringUtils.format(
" OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
deptAlias,
user.getDeptId(),
user.getDeptId()
)
);
} else if ("5".equals(dataScope)) {
if (StringUtils.isNotBlank(userAlias)) {
sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
} else {
sqlString.append(" OR 1=0 ");
}
}
}
if (StringUtils.isNotBlank(sqlString.toString())) {
BaseEntity baseEntity = (BaseEntity)joinPoint.getArgs()[0];
baseEntity.setDataScope(" AND (" + sqlString.substring(4) + ")");
}
}
private DataScope getAnnotationLog(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature)signature;
Method method = methodSignature.getMethod();
return method != null ? method.getAnnotation(DataScope.class) : null;
}
}
package com.wechat.framework.aspectj;
import com.wechat.common.utils.StringUtils;
import com.wechat.framework.aspectj.lang.annotation.DataSource;
import com.wechat.framework.datasource.DynamicDataSourceContextHolder;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Aspect
@Order(1)
@Component
public class DataSourceAspect {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("@annotation(com.wechat.framework.aspectj.lang.annotation.DataSource)|| @within(com.wechat.framework.aspectj.lang.annotation.DataSource)")
public void dsPointCut() {
}
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
DataSource dataSource = this.getDataSource(point);
if (StringUtils.isNotNull(dataSource)) {
DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
}
Object var3;
try {
var3 = point.proceed();
} finally {
DynamicDataSourceContextHolder.clearDataSourceType();
}
return var3;
}
public DataSource getDataSource(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature)point.getSignature();
Class<? extends Object> targetClass = (Class<? extends Object>)point.getTarget().getClass();
DataSource targetDataSource = targetClass.getAnnotation(DataSource.class);
if (StringUtils.isNotNull(targetDataSource)) {
return targetDataSource;
} else {
Method method = signature.getMethod();
return method.getAnnotation(DataSource.class);
}
}
}
package com.wechat.framework.aspectj;
import com.alibaba.fastjson.JSON;
import com.wechat.common.enums.HttpMethod;
import com.wechat.common.utils.ServletUtils;
import com.wechat.common.utils.StringUtils;
import com.wechat.common.utils.ip.IpUtils;
import com.wechat.common.utils.spring.SpringUtils;
import com.wechat.framework.aspectj.lang.annotation.Log;
import com.wechat.framework.aspectj.lang.enums.BusinessStatus;
import com.wechat.framework.manager.AsyncManager;
import com.wechat.framework.manager.factory.AsyncFactory;
import com.wechat.framework.security.LoginUser;
import com.wechat.framework.security.service.TokenService;
import com.wechat.project.monitor.domain.SysOperLog;
import java.lang.reflect.Method;
import java.util.Map;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;
@Aspect
@Component
public class LogAspect {
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
@Pointcut("@annotation(com.wechat.framework.aspectj.lang.annotation.Log)")
public void logPointCut() {
}
@AfterReturning(
pointcut = "logPointCut()",
returning = "jsonResult"
)
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
this.handleLog(joinPoint, null, jsonResult);
}
@AfterThrowing(
value = "logPointCut()",
throwing = "e"
)
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
this.handleLog(joinPoint, e, null);
}
protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
try {
Log controllerLog = this.getAnnotationLog(joinPoint);
if (controllerLog == null) {
return;
}
LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
SysOperLog operLog = new SysOperLog();
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
operLog.setOperIp(ip);
operLog.setJsonResult(JSON.toJSONString(jsonResult));
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
if (loginUser != null) {
operLog.setOperName(loginUser.getUsername());
}
if (e != null) {
operLog.setStatus(BusinessStatus.FAIL.ordinal());
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
this.getControllerMethodDescription(joinPoint, controllerLog, operLog);
AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
} catch (Exception var10) {
log.error("==前置通知异常==");
log.error("异常信息:{}", var10.getMessage());
var10.printStackTrace();
}
}
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog) throws Exception {
operLog.setBusinessType(log.businessType().ordinal());
operLog.setTitle(log.title());
operLog.setOperatorType(log.operatorType().ordinal());
if (log.isSaveRequestData()) {
this.setRequestValue(joinPoint, operLog);
}
}
private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception {
String requestMethod = operLog.getRequestMethod();
if (!HttpMethod.PUT.name().equals(requestMethod) && !HttpMethod.POST.name().equals(requestMethod)) {
Map<?, ?> paramsMap = (Map<?, ?>)ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
} else {
String params = this.argsArrayToString(joinPoint.getArgs());
operLog.setOperParam(StringUtils.substring(params, 0, 2000));
}
}
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature)signature;
Method method = methodSignature.getMethod();
return method != null ? method.getAnnotation(Log.class) : null;
}
private String argsArrayToString(Object[] paramsArray) {
String params = "";
if (paramsArray != null && paramsArray.length > 0) {
for (int i = 0; i < paramsArray.length; i++) {
if (!(paramsArray[i] instanceof MultipartFile)) {
Object jsonObj = JSON.toJSON(paramsArray[i]);
params = params + jsonObj.toString() + " ";
}
}
}
return params.trim();
}
}
package com.wechat.framework.aspectj.lang.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataScope {
String deptAlias() default "";
String userAlias() default "";
}
package com.wechat.framework.aspectj.lang.annotation;
import com.wechat.framework.aspectj.lang.enums.DataSourceType;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource {
DataSourceType value() default DataSourceType.MASTER;
}
package com.wechat.framework.aspectj.lang.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Excel {
String name() default "";
String dateFormat() default "";
String readConverterExp() default "";
Excel.ColumnType cellType() default Excel.ColumnType.STRING;
double height() default 14.0;
double width() default 16.0;
String suffix() default "";
String defaultValue() default "";
String prompt() default "";
String[] combo() default {};
boolean isExport() default true;
String targetAttr() default "";
Excel.Type type() default Excel.Type.ALL;
public static enum ColumnType {
NUMERIC(0),
STRING(1);
private final int value;
private ColumnType(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
public static enum Type {
ALL(0),
EXPORT(1),
IMPORT(2);
private final int value;
private Type(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
}
package com.wechat.framework.aspectj.lang.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Excels {
Excel[] value();
}
package com.wechat.framework.aspectj.lang.annotation;
import com.wechat.framework.aspectj.lang.enums.BusinessType;
import com.wechat.framework.aspectj.lang.enums.OperatorType;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
String title() default "";
BusinessType businessType() default BusinessType.OTHER;
OperatorType operatorType() default OperatorType.MANAGE;
boolean isSaveRequestData() default true;
}
package com.wechat.framework.aspectj.lang.enums;
public enum BusinessStatus {
SUCCESS,
FAIL;
}
package com.wechat.framework.aspectj.lang.enums;
public enum BusinessType {
OTHER,
INSERT,
UPDATE,
DELETE,
GRANT,
EXPORT,
IMPORT,
FORCE,
GENCODE,
CLEAN;
}
package com.wechat.framework.aspectj.lang.enums;
public enum DataSourceType {
MASTER,
SLAVE;
}
package com.wechat.framework.aspectj.lang.enums;
public enum OperatorType {
OTHER,
MANAGE,
MOBILE;
}
package com.wechat.framework.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties("zfbchat")
@Component
public class ALiChatOAuthConfig {
private String aLiPayPiblicKey;
private String chartSet;
private String appId;
private String privateKey;
private String appPrivateKey;
private String grantType;
private String appALiPayPiblicKey;
private String appletsId;
public String getALiPayPiblicKey() {
return this.aLiPayPiblicKey;
}
public String getChartSet() {
return this.chartSet;
}
public String getAppId() {
return this.appId;
}
public String getPrivateKey() {
return this.privateKey;
}
public String getAppPrivateKey() {
return this.appPrivateKey;
}
public String getGrantType() {
return this.grantType;
}
public String getAppALiPayPiblicKey() {
return this.appALiPayPiblicKey;
}
public String getAppletsId() {
return this.appletsId;
}
public void setALiPayPiblicKey(final String aLiPayPiblicKey) {
this.aLiPayPiblicKey = aLiPayPiblicKey;
}
public void setChartSet(final String chartSet) {
this.chartSet = chartSet;
}
public void setAppId(final String appId) {
this.appId = appId;
}
public void setPrivateKey(final String privateKey) {
this.privateKey = privateKey;
}
public void setAppPrivateKey(final String appPrivateKey) {
this.appPrivateKey = appPrivateKey;
}
public void setGrantType(final String grantType) {
this.grantType = grantType;
}
public void setAppALiPayPiblicKey(final String appALiPayPiblicKey) {
this.appALiPayPiblicKey = appALiPayPiblicKey;
}
public void setAppletsId(final String appletsId) {
this.appletsId = appletsId;
}
@Override
public boolean equals(final Object o) {
if (o == this) {
return true;
} else if (!(o instanceof ALiChatOAuthConfig)) {
return false;
} else {
ALiChatOAuthConfig other = (ALiChatOAuthConfig)o;
if (!other.canEqual(this)) {
return false;
} else {
Object this$aLiPayPiblicKey = this.getALiPayPiblicKey();
Object other$aLiPayPiblicKey = other.getALiPayPiblicKey();
if (this$aLiPayPiblicKey == null ? other$aLiPayPiblicKey == null : this$aLiPayPiblicKey.equals(other$aLiPayPiblicKey)) {
Object this$chartSet = this.getChartSet();
Object other$chartSet = other.getChartSet();
if (this$chartSet == null ? other$chartSet == null : this$chartSet.equals(other$chartSet)) {
Object this$appId = this.getAppId();
Object other$appId = other.getAppId();
if (this$appId == null ? other$appId == null : this$appId.equals(other$appId)) {
Object this$privateKey = this.getPrivateKey();
Object other$privateKey = other.getPrivateKey();
if (this$privateKey == null ? other$privateKey == null : this$privateKey.equals(other$privateKey)) {
Object this$appPrivateKey = this.getAppPrivateKey();
Object other$appPrivateKey = other.getAppPrivateKey();
if (this$appPrivateKey == null ? other$appPrivateKey == null : this$appPrivateKey.equals(other$appPrivateKey)) {
Object this$grantType = this.getGrantType();
Object other$grantType = other.getGrantType();
if (this$grantType == null ? other$grantType == null : this$grantType.equals(other$grantType)) {
Object this$appALiPayPiblicKey = this.getAppALiPayPiblicKey();
Object other$appALiPayPiblicKey = other.getAppALiPayPiblicKey();
if (this$appALiPayPiblicKey == null ? other$appALiPayPiblicKey == null : this$appALiPayPiblicKey.equals(other$appALiPayPiblicKey)
)
{
Object this$appletsId = this.getAppletsId();
Object other$appletsId = other.getAppletsId();
return this$appletsId == null ? other$appletsId == null : this$appletsId.equals(other$appletsId);
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
}
}
protected boolean canEqual(final Object other) {
return other instanceof ALiChatOAuthConfig;
}
@Override
public int hashCode() {
int PRIME = 59;
int result = 1;
Object $aLiPayPiblicKey = this.getALiPayPiblicKey();
result = result * 59 + ($aLiPayPiblicKey == null ? 43 : $aLiPayPiblicKey.hashCode());
Object $chartSet = this.getChartSet();
result = result * 59 + ($chartSet == null ? 43 : $chartSet.hashCode());
Object $appId = this.getAppId();
result = result * 59 + ($appId == null ? 43 : $appId.hashCode());
Object $privateKey = this.getPrivateKey();
result = result * 59 + ($privateKey == null ? 43 : $privateKey.hashCode());
Object $appPrivateKey = this.getAppPrivateKey();
result = result * 59 + ($appPrivateKey == null ? 43 : $appPrivateKey.hashCode());
Object $grantType = this.getGrantType();
result = result * 59 + ($grantType == null ? 43 : $grantType.hashCode());
Object $appALiPayPiblicKey = this.getAppALiPayPiblicKey();
result = result * 59 + ($appALiPayPiblicKey == null ? 43 : $appALiPayPiblicKey.hashCode());
Object $appletsId = this.getAppletsId();
return result * 59 + ($appletsId == null ? 43 : $appletsId.hashCode());
}
@Override
public String toString() {
return "ALiChatOAuthConfig(aLiPayPiblicKey="
+ this.getALiPayPiblicKey()
+ ", chartSet="
+ this.getChartSet()
+ ", appId="
+ this.getAppId()
+ ", privateKey="
+ this.getPrivateKey()
+ ", appPrivateKey="
+ this.getAppPrivateKey()
+ ", grantType="
+ this.getGrantType()
+ ", appALiPayPiblicKey="
+ this.getAppALiPayPiblicKey()
+ ", appletsId="
+ this.getAppletsId()
+ ")";
}
}
package com.wechat.framework.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy(
exposeProxy = true
)
@MapperScan({"com.wechat.project.**.mapper"})
public class ApplicationConfig {
}
package com.wechat.framework.config;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", this.buildConfig());
return new CorsFilter(source);
}
@Bean
public ServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory fa = new TomcatServletWebServerFactory();
fa.addConnectorCustomizers(new TomcatConnectorCustomizer[]{connector -> connector.setProperty("relaxedQueryChars", "[]{}")});
return fa;
}
}
package com.wechat.framework.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties.StatViewServlet;
import com.alibaba.druid.util.Utils;
import com.wechat.framework.aspectj.lang.enums.DataSourceType;
import com.wechat.framework.config.properties.DruidProperties;
import com.wechat.framework.datasource.DynamicDataSource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid.master")
public DataSource masterDataSource(DruidProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slave")
@ConditionalOnProperty(
prefix = "spring.datasource.druid.slave",
name = {"enabled"},
havingValue = "true"
)
public DataSource slaveDataSource(DruidProperties druidProperties) {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(
name = {"dynamicDataSource"}
)
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource);
return new DynamicDataSource(masterDataSource, targetDataSources);
}
@Bean
@ConditionalOnProperty(
name = {"spring.datasource.druid.statViewServlet.enabled"},
havingValue = "true"
)
public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) {
StatViewServlet config = properties.getStatViewServlet();
String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
String filePath = "support/http/resources/js/common.js";
Filter filter = new Filter() {
public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
response.resetBuffer();
String text = Utils.readFromResource("support/http/resources/js/common.js");
text = text.replaceAll("<a.*?banner\"></a><br/>", "");
text = text.replaceAll("powered.*?shrek.wang</a>", "");
response.getWriter().write(text);
}
public void destroy() {
}
};
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(filter);
registrationBean.addUrlPatterns(new String[]{commonJsPattern});
return registrationBean;
}
}
package com.wechat.framework.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import java.nio.charset.Charset;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
private ObjectMapper objectMapper = new ObjectMapper();
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJson2JsonRedisSerializer(Class<T> clazz) {
this.clazz = clazz;
}
public byte[] serialize(T t) throws SerializationException {
return t == null ? new byte[0] : JSON.toJSONString(t, new SerializerFeature[]{SerializerFeature.WriteClassName}).getBytes(DEFAULT_CHARSET);
}
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes != null && bytes.length > 0) {
String str = new String(bytes, DEFAULT_CHARSET);
return (T)JSON.parseObject(str, this.clazz);
} else {
return null;
}
}
public void setObjectMapper(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "'objectMapper' must not be null");
this.objectMapper = objectMapper;
}
protected JavaType getJavaType(Class<?> clazz) {
return TypeFactory.defaultInstance().constructType(clazz);
}
static {
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
}
package com.wechat.framework.config;
import com.wechat.common.utils.StringUtils;
import com.wechat.common.xss.XssFilter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.DispatcherType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterConfig {
@Value("${xss.enabled}")
private String enabled;
@Value("${xss.excludes}")
private String excludes;
@Value("${xss.urlPatterns}")
private String urlPatterns;
@Bean
public FilterRegistrationBean xssFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST, new DispatcherType[0]);
registration.setFilter(new XssFilter());
registration.addUrlPatterns(StringUtils.split(this.urlPatterns, ","));
registration.setName("xssFilter");
registration.setOrder(Integer.MAX_VALUE);
Map<String, String> initParameters = new HashMap<>();
initParameters.put("excludes", this.excludes);
initParameters.put("enabled", this.enabled);
registration.setInitParameters(initParameters);
return registration;
}
}
package com.wechat.framework.config;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import javax.sql.DataSource;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;
@Configuration
public class MyBatisConfig {
@Autowired
private Environment env;
static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
public static String setTypeAliasesPackage(String typeAliasesPackage) {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
List<String> allResult = new ArrayList<>();
try {
for (String aliasesPackage : typeAliasesPackage.split(",")) {
List<String> result = new ArrayList<>();
aliasesPackage = "classpath*:" + ClassUtils.convertClassNameToResourcePath(aliasesPackage.trim()) + "/" + "**/*.class";
Resource[] resources = resolver.getResources(aliasesPackage);
if (resources != null && resources.length > 0) {
MetadataReader metadataReader = null;
for (Resource resource : resources) {
if (resource.isReadable()) {
metadataReader = metadataReaderFactory.getMetadataReader(resource);
try {
result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
} catch (ClassNotFoundException var16) {
var16.printStackTrace();
}
}
}
}
if (result.size() > 0) {
HashSet<String> hashResult = new HashSet<>(result);
allResult.addAll(hashResult);
}
}
if (allResult.size() <= 0) {
throw new RuntimeException("mybatis typeAliasesPackage 路径扫描错误,参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包");
}
typeAliasesPackage = String.join(",", (String[])allResult.toArray(new String[0]));
} catch (IOException var17) {
var17.printStackTrace();
}
return typeAliasesPackage;
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
String typeAliasesPackage = this.env.getProperty("mybatis.typeAliasesPackage");
String mapperLocations = this.env.getProperty("mybatis.mapperLocations");
typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage);
VFS.addImplClass(SpringBootVFS.class);
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
return sessionFactory.getObject();
}
}
package com.wechat.framework.config;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer<>(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
mapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
package com.wechat.framework.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(new String[]{"/profile/**"}).addResourceLocations(new String[]{"file:" + WechatConfig.getProfile() + "/"});
registry.addResourceHandler(new String[]{"swagger-ui.html"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/"});
registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"});
}
}
package com.wechat.framework.config;
import com.wechat.framework.security.filter.JwtAuthenticationTokenFilter;
import com.wechat.framework.security.handle.AuthenticationEntryPointImpl;
import com.wechat.framework.security.handle.LogoutSuccessHandlerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer.AuthorizedUrl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private AuthenticationEntryPointImpl unauthorizedHandler;
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandler;
@Autowired
private JwtAuthenticationTokenFilter authenticationTokenFilter;
@Autowired
private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
protected void configure(HttpSecurity httpSecurity) throws Exception {
((HttpSecurity)((HttpSecurity)((FormLoginConfigurer)((FormLoginConfigurer)((HttpSecurity)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((AuthorizedUrl)((HttpSecurity)((HttpSecurity)httpSecurity.csrf()
.disable())
.exceptionHandling()
.authenticationEntryPoint(this.unauthorizedHandler)
.and())
.authorizeRequests()
.antMatchers(new String[]{"/login", "/captchaImage"}))
.anonymous()
.antMatchers(
HttpMethod.GET, new String[]{"/*.html", "/**/*.html", "/**/*.css", "/**/*.js"}
))
.permitAll()
.antMatchers(new String[]{"/websocket/**"}))
.permitAll()
.antMatchers(new String[]{"/mapi/**"}))
.permitAll()
.antMatchers(new String[]{"/system/dict/data/dictType/**"}))
.permitAll()
.antMatchers(new String[]{"/standard/paramInfo/title/**"}))
.permitAll()
.antMatchers(new String[]{"/webservice/**"}))
.permitAll()
.antMatchers(new String[]{"/xinhua/**"}))
.permitAll()
.antMatchers(new String[]{"/profile/**"}))
.permitAll()
.antMatchers(new String[]{"/common/download**"}))
.anonymous()
.antMatchers(new String[]{"/swagger-ui.html"}))
.permitAll()
.antMatchers(new String[]{"/swagger-resources/**"}))
.permitAll()
.antMatchers(new String[]{"/webjars/**"}))
.anonymous()
.antMatchers(new String[]{"/*/api-docs"}))
.permitAll()
.antMatchers(new String[]{"/druid/**"}))
.anonymous()
.anyRequest())
.authenticated()
.and())
.formLogin()
.loginProcessingUrl("/api/user/login"))
.permitAll())
.and())
.authorizeRequests()
.mvcMatchers(new String[]{"/mapi/user/**"})
.anonymous()
.and())
.headers()
.frameOptions()
.disable();
((HttpSecurity)((FormLoginConfigurer)((FormLoginConfigurer)((HttpSecurity)((AuthorizedUrl)((AuthorizedUrl)((HttpSecurity)((SmsCodeAuthenticationSecurityConfig)httpSecurity.apply(
this.smsCodeAuthenticationSecurityConfig
))
.and())
.authorizeRequests()
.antMatchers(new String[]{"/mapi/user/**"}))
.permitAll()
.anyRequest())
.authenticated()
.and())
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/"))
.permitAll())
.and())
.logout()
.permitAll();
httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(this.logoutSuccessHandler);
httpSecurity.addFilterBefore(this.authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(this.userDetailsService).passwordEncoder(this.bCryptPasswordEncoder());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment