重置密码用户注销+格式化代码

master
李永杰 2024-04-20 19:03:00 +08:00
parent 748266f8db
commit 1fb4c0f046
402 changed files with 11409 additions and 12564 deletions

View File

@ -17,10 +17,15 @@
* 后端采用Spring Boot、Spring Cloud & Alibaba。
* 注册中心、配置中心选型Nacos权限认证使用Redis。
* 流量控制框架选型Sentinel分布式事务选型Seata。
* 提供了技术栈([Vue3](https://v3.cn.vuejs.org) [Element Plus](https://element-plus.org/zh-CN) [Vite](https://cn.vitejs.dev))版本[RuoYi-Cloud-Vue3](https://github.com/yangzongzhuan/RuoYi-Cloud-Vue3),保持同步更新。
* 如需不分离应用,请移步 [RuoYi](https://gitee.com/y_project/RuoYi),如需分离应用,请移步 [RuoYi-Vue](https://gitee.com/y_project/RuoYi-Vue)
*
提供了技术栈([Vue3](https://v3.cn.vuejs.org) [Element Plus](https://element-plus.org/zh-CN) [Vite](https://cn.vitejs.dev)
)版本[RuoYi-Cloud-Vue3](https://github.com/yangzongzhuan/RuoYi-Cloud-Vue3),保持同步更新。
* 如需不分离应用,请移步 [RuoYi](https://gitee.com/y_project/RuoYi)
,如需分离应用,请移步 [RuoYi-Vue](https://gitee.com/y_project/RuoYi-Vue)
* 阿里云折扣场:[点我进入](http://aly.muyu.vip),腾讯云秒杀场:[点我进入](http://txy.muyu.vip)  
* 阿里云优惠券:[点我领取](https://www.aliyun.com/minisite/goods?userCode=brki8iof&share_source=copy_link),腾讯云优惠券:[点我领取](https://cloud.tencent.com/redirect.php?redirect=1025&cps_key=198c8df2ed259157187173bc7f4f32fd&from=console)  
* 阿里云优惠券:[点我领取](https://www.aliyun.com/minisite/goods?userCode=brki8iof&share_source=copy_link)
,腾讯云优惠券:[点我领取](https://cloud.tencent.com/redirect.php?redirect=1025&cps_key=198c8df2ed259157187173bc7f4f32fd&from=console)
  
#### 友情链接 [若依/RuoYi-Cloud](https://gitee.com/zhangmrit/muyu-cloud) Ant Design版本。
@ -58,15 +63,15 @@ com.muyu
## 内置功能
1. 用户管理:用户是系统操作者,该功能主要完成系统用户配置。
2. 部门管理:配置系统组织机构(公司、部门、小组),树结构展现支持数据权限。
3. 岗位管理:配置系统用户所属担任职务。
4. 菜单管理:配置系统菜单,操作权限,按钮权限标识等。
5. 角色管理:角色菜单权限分配、设置角色按机构进行数据范围权限划分。
6. 字典管理:对系统中经常使用的一些较为固定的数据进行维护。
7. 参数管理:对系统动态配置常用参数。
8. 通知公告:系统通知公告信息发布维护。
9. 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。
1. 用户管理:用户是系统操作者,该功能主要完成系统用户配置。
2. 部门管理:配置系统组织机构(公司、部门、小组),树结构展现支持数据权限。
3. 岗位管理:配置系统用户所属担任职务。
4. 菜单管理:配置系统菜单,操作权限,按钮权限标识等。
5. 角色管理:角色菜单权限分配、设置角色按机构进行数据范围权限划分。
6. 字典管理:对系统中经常使用的一些较为固定的数据进行维护。
7. 参数管理:对系统动态配置常用参数。
8. 通知公告:系统通知公告信息发布维护。
9. 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。
10. 登录日志:系统登录日志记录查询包含登录异常。
11. 在线用户:当前系统中活跃用户状态监控。
12. 定时任务:在线(添加、修改、删除)任务调度包含执行结果日志。
@ -78,7 +83,7 @@ com.muyu
## 在线体验
- admin/admin123
- admin/admin123
- 陆陆续续收到一些打赏,为了更好的体验已用于演示服务器升级。谢谢各位小伙伴。
演示地址http://muyu.vip
@ -125,7 +130,7 @@ com.muyu
</tr>
</table>
## 若依微服务交流群
QQ群 [![加入QQ群](https://img.shields.io/badge/已满-42799195-blue.svg)](https://jq.qq.com/?_wv=1027&k=yqInfq0S) [![加入QQ群](https://img.shields.io/badge/已满-170157040-blue.svg)](https://jq.qq.com/?_wv=1027&k=Oy1mb3p8) [![加入QQ群](https://img.shields.io/badge/已满-130643120-blue.svg)](https://jq.qq.com/?_wv=1027&k=rvxkJtXK) [![加入QQ群](https://img.shields.io/badge/已满-225920371-blue.svg)](https://jq.qq.com/?_wv=1027&k=0Ck3PvTe) [![加入QQ群](https://img.shields.io/badge/已满-201705537-blue.svg)](https://jq.qq.com/?_wv=1027&k=FnHHP4TT) [![加入QQ群](https://img.shields.io/badge/已满-236543183-blue.svg)](https://jq.qq.com/?_wv=1027&k=qdT1Ojpz) [![加入QQ群](https://img.shields.io/badge/已满-213618602-blue.svg)](https://jq.qq.com/?_wv=1027&k=nw3OiyXs) [![加入QQ群](https://img.shields.io/badge/已满-148794840-blue.svg)](https://jq.qq.com/?_wv=1027&k=kiU5WDls) [![加入QQ群](https://img.shields.io/badge/已满-118752664-blue.svg)](https://jq.qq.com/?_wv=1027&k=MtBy6YfT) [![加入QQ群](https://img.shields.io/badge/已满-101038945-blue.svg)](https://jq.qq.com/?_wv=1027&k=FqImHgH2) [![加入QQ群](https://img.shields.io/badge/已满-128355254-blue.svg)](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=G4jZ4EtdT50PhnMBudTnEwgonxkXOscJ&authKey=FkGHYfoTKlGE6wHdKdjH9bVoOgQjtLP9WM%2Fj7pqGY1msoqw9uxDiBo39E2mLgzYg&noverify=0&group_code=128355254) [![加入QQ群](https://img.shields.io/badge/179219821-blue.svg)](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=irnwcXhbLOQEv1g-TwGifjNTA_f4wZiA&authKey=4bpzEwhcUY%2FvsPDHvzYn6xfoS%2FtOArvZ%2BGXzfr7O0%2FEqLfkKA%2BuCDXlzHIFg8t93&noverify=0&group_code=179219821) 点击按钮入群。
QQ群 [![加入QQ群](https://img.shields.io/badge/已满-42799195-blue.svg)](https://jq.qq.com/?_wv=1027&k=yqInfq0S) [![加入QQ群](https://img.shields.io/badge/已满-170157040-blue.svg)](https://jq.qq.com/?_wv=1027&k=Oy1mb3p8) [![加入QQ群](https://img.shields.io/badge/已满-130643120-blue.svg)](https://jq.qq.com/?_wv=1027&k=rvxkJtXK) [![加入QQ群](https://img.shields.io/badge/已满-225920371-blue.svg)](https://jq.qq.com/?_wv=1027&k=0Ck3PvTe) [![加入QQ群](https://img.shields.io/badge/已满-201705537-blue.svg)](https://jq.qq.com/?_wv=1027&k=FnHHP4TT) [![加入QQ群](https://img.shields.io/badge/已满-236543183-blue.svg)](https://jq.qq.com/?_wv=1027&k=qdT1Ojpz) [![加入QQ群](https://img.shields.io/badge/已满-213618602-blue.svg)](https://jq.qq.com/?_wv=1027&k=nw3OiyXs) [![加入QQ群](https://img.shields.io/badge/已满-148794840-blue.svg)](https://jq.qq.com/?_wv=1027&k=kiU5WDls) [![加入QQ群](https://img.shields.io/badge/已满-118752664-blue.svg)](https://jq.qq.com/?_wv=1027&k=MtBy6YfT) [![加入QQ群](https://img.shields.io/badge/已满-101038945-blue.svg)](https://jq.qq.com/?_wv=1027&k=FqImHgH2) [![加入QQ群](https://img.shields.io/badge/已满-128355254-blue.svg)](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=G4jZ4EtdT50PhnMBudTnEwgonxkXOscJ&authKey=FkGHYfoTKlGE6wHdKdjH9bVoOgQjtLP9WM%2Fj7pqGY1msoqw9uxDiBo39E2mLgzYg&noverify=0&group_code=128355254) [![加入QQ群](https://img.shields.io/badge/179219821-blue.svg)](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=irnwcXhbLOQEv1g-TwGifjNTA_f4wZiA&authKey=4bpzEwhcUY%2FvsPDHvzYn6xfoS%2FtOArvZ%2BGXzfr7O0%2FEqLfkKA%2BuCDXlzHIFg8t93&noverify=0&group_code=179219821)
点击按钮入群。

View File

@ -1,4 +1,4 @@
version : '3.8'
version: '3.8'
services:
muyu-nacos:
container_name: muyu-nacos
@ -28,13 +28,13 @@ services:
- ./mysql/logs:/logs
- ./mysql/data:/var/lib/mysql
command: [
'mysqld',
'--innodb-buffer-pool-size=80M',
'--character-set-server=utf8mb4',
'--collation-server=utf8mb4_unicode_ci',
'--default-time-zone=+8:00',
'--lower-case-table-names=1'
]
'mysqld',
'--innodb-buffer-pool-size=80M',
'--character-set-server=utf8mb4',
'--collation-server=utf8mb4_unicode_ci',
'--default-time-zone=+8:00',
'--lower-case-table-names=1'
]
environment:
MYSQL_DATABASE: 'ry-cloud'
MYSQL_ROOT_PASSWORD: password
@ -130,7 +130,7 @@ services:
ports:
- "9300:9300"
volumes:
- ./muyu/uploadPath:/home/muyu/uploadPath
- ./muyu/uploadPath:/home/muyu/uploadPath
muyu-visual-monitor:
container_name: muyu-visual-monitor
build:

View File

@ -3,23 +3,16 @@ db.num=1
db.url.0=jdbc:mysql://muyu-mysql:3306/ry-config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user=root
db.password=password
nacos.naming.empty-service.auto-clean=true
nacos.naming.empty-service.clean.initial-delay-ms=50000
nacos.naming.empty-service.clean.period-time-ms=30000
management.endpoints.web.exposure.include=*
management.metrics.export.elastic.enabled=false
management.metrics.export.influx.enabled=false
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i
server.tomcat.basedir=/home/muyu/nacos/tomcat/logs
nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**
nacos.core.auth.system.type=nacos
nacos.core.auth.enabled=false
nacos.core.auth.default.token.expire.seconds=18000
@ -28,5 +21,4 @@ nacos.core.auth.caching.enabled=true
nacos.core.auth.enable.userAgentAuthWhite=false
nacos.core.auth.server.identity.key=serverIdentity
nacos.core.auth.server.identity.value=security
nacos.istio.mcp.server.enabled=false

View File

@ -8,6 +8,7 @@ import com.aliyun.teautil.*;
/**
* ECS
*
* @Author LiYonJie
* @Date 2024/4/12
*/
@ -32,7 +33,7 @@ public class CreateEsc {
// 地域Id
String regionId = "cn-zhangjiakou";
// 镜像 ID启动实例时选择的镜像资源。
String imageId ="m-8vb2cpmwwggxp598kjue";
String imageId = "m-8vb2cpmwwggxp598kjue";
// 实例规格
String instanceType = "ecs.t6-c1m1.large";
// 新创建实例所属于的安全组 ID。
@ -63,7 +64,7 @@ public class CreateEsc {
com.aliyun.teaconsole.Client.log(instanceType);
com.aliyun.teaconsole.Client.log(securityGroupId);
com.aliyun.teaconsole.Client.log(vSwitchId);
com.aliyun.teaconsole.Client.log(""+internetMaxBandwidthOut);
com.aliyun.teaconsole.Client.log("" + internetMaxBandwidthOut);
com.aliyun.teaconsole.Client.log(size);
com.aliyun.teaconsole.Client.log(category);
com.aliyun.teaconsole.Client.log(instanceChargeType);

View File

@ -27,11 +27,11 @@
<artifactId>spring-kafka</artifactId>
<version>2.8.1</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.apache.kafka</groupId>-->
<!-- <artifactId>kafka-clients</artifactId>-->
<!-- <version>2.8.0</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.kafka</groupId>-->
<!-- <artifactId>kafka-clients</artifactId>-->
<!-- <version>2.8.0</version>-->
<!-- </dependency>-->
<!-- SpringCloud Alibaba Nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>

View File

@ -17,10 +17,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@EnableRyFeignClients
@SpringBootApplication
@EnableScheduling
public class MuYuAnalyzeApplication
{
public static void main(String[] args)
{
public class MuYuAnalyzeApplication {
public static void main(String[] args) {
SpringApplication.run(MuYuAnalyzeApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 系统模块启动成功 ლ(´ڡ`ლ)゙ \n" +
" .-------. ____ __ \n" +

View File

@ -10,6 +10,7 @@ import org.springframework.stereotype.Component;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@Configuration
public class KafkaConfig {
@ -22,20 +23,20 @@ public class KafkaConfig {
public static final String DEFAULT_KEY = "10001";
public static Properties properties1(){
public static Properties properties1() {
// 1构建 Properties 对象 存放 kafka 生产者配置信息
Properties properties1 = new Properties();
// 设置 kafka 连接地址(从配置文件/环境变量获取)
properties1.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KafkaConfig.BOOTSTRAP_SERVERS);
// 设置 键值 序列化
properties1.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer .class.getName());
// 设置 键值 序列化
properties1.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties1.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
return properties1;
}
public static Properties properties2(){
public static Properties properties2() {
Properties properties2 = new Properties();
properties2.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.10.26.4:9092");
properties2.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());

View File

@ -16,7 +16,7 @@ public class TutConfig {
@Bean
public Queue fault() {
return new Queue(MQQueueConstants.ALARM_QUEUE,true);
return new Queue(MQQueueConstants.ALARM_QUEUE, true);
}
@Bean

View File

@ -37,6 +37,7 @@ public class Consumer {
/**
* kafka-- kafka test
*
* @param msg
*/
// @KafkaListener(topics = "test", groupId = "group", properties = {"bootstrap.servers = 10.10.26.4:9092"})
@ -58,8 +59,6 @@ public class Consumer {
}
// @RabbitHandler
// public void take(String msg, Channel channel, Message message) throws IOException {
//// String messageId = message.getMessageProperties().getMessageId();

View File

@ -51,5 +51,4 @@ public class RealTimeDataController {
}
}

View File

@ -17,7 +17,7 @@ import java.util.List;
* @Version 1.0
*/
@Mapper
public interface VehicleMapper{
public interface VehicleMapper {
Boolean addVehicleStoredEvent(ArrayList<VehicleData> list);

View File

@ -12,11 +12,9 @@ import com.muyu.system.common.domain.VehicleData;
* @Date 2024/4/4 09:30
* @Version 1.0
*/
public interface VehicleService {
public interface VehicleService {
void eventResolution(VehicleData analyze);
}

View File

@ -31,7 +31,7 @@ import java.util.concurrent.TimeUnit;
*/
@Service("breakdown")
@Slf4j
public class BreakdownImpl implements VehicleService{
public class BreakdownImpl implements VehicleService {
@Autowired
@ -52,7 +52,6 @@ public class BreakdownImpl implements VehicleService{
public void eventResolution(VehicleData vehicleData) {
//判断故障
if (StateConstant.VEHICLE_STATUS != vehicleData.getVehicleStatus()
|| StateConstant.CHARGING_STATUS != vehicleData.getChgStatus()
@ -71,7 +70,7 @@ public class BreakdownImpl implements VehicleService{
|| StateConstant.DCDC_STATUS != vehicleData.getDcdcStatus()
|| StateConstant.CHG_STATUS != vehicleData.getChgStatus()) {
log.info("车辆VIN:"+vehicleData.getVin()+"发生故障,故障事件解析");
log.info("车辆VIN:" + vehicleData.getVin() + "发生故障,故障事件解析");
FaultLogs faultLogsAddReq = new FaultLogs();
@ -235,16 +234,14 @@ public class BreakdownImpl implements VehicleService{
return message;
});
log.info("车辆VIN:"+vehicleData.getVin()+"故障事件已记录");
log.info("车辆VIN:" + vehicleData.getVin() + "故障事件已记录");
log.info("故障事件结束");
}else{
log.info("车辆VIN:"+vehicleData.getVin()+"没有故障,状态正常");
} else {
log.info("车辆VIN:" + vehicleData.getVin() + "没有故障,状态正常");
}
}
}

View File

@ -45,7 +45,6 @@ public class FenceAlarmImpl implements VehicleService {
private RabbitTemplate rabbitTemplate;
@Override
public void eventResolution(VehicleData analyze) {
Fence fence = new Fence();
@ -60,7 +59,7 @@ public class FenceAlarmImpl implements VehicleService {
//这里修改为1对多的 电子围栏 目前是一对一
Car car =vehicleMapper.selectCarList(vin);
Car car = vehicleMapper.selectCarList(vin);
String carFenceId = car.getCarFenceId();
@ -70,44 +69,43 @@ public class FenceAlarmImpl implements VehicleService {
Map<String, Object> fence1 = redisService.getCacheMap("fence");
for (Map.Entry<String, Object> entry : fence1.entrySet()) {
for (String s : split1) {
String key = entry.getKey();
if (s.equals(key)){
String value = (String) entry.getValue();
String key = entry.getKey();
if (s.equals(key)) {
String value = (String) entry.getValue();
String[] split = value.split(";");
String[] split = value.split(";");
boolean withinFence = isWithinFence(pointLat, pointLng, Arrays.asList(split));
boolean withinFence = isWithinFence(pointLat, pointLng, Arrays.asList(split));
if (withinFence){
log.info("车辆vin:"+vin+"------在电子围栏"+key+"---正常行驶---");
}else {
log.info("车辆vin:"+vin+"------驶出电子围栏"+key+"---报警---");
if (withinFence) {
log.info("车辆vin:" + vin + "------在电子围栏" + key + "---正常行驶---");
} else {
log.info("车辆vin:" + vin + "------驶出电子围栏" + key + "---报警---");
String key1 = "fenceType1";
String key1 = "fenceType1";
HashSet<Fence> hashSet = new HashSet<>();
fence.setCarVin(vin);
fence.setFenceType("驶出");
fence.setFenceId(Integer.valueOf(key));
HashSet<Fence> hashSet = new HashSet<>();
fence.setCarVin(vin);
fence.setFenceType("驶出");
fence.setFenceId(Integer.valueOf(key));
hashSet.add(fence);
redisService.setCacheSet(key1,hashSet);
redisService.expire(key1, 20, TimeUnit.MINUTES); // 设置过期时间
hashSet.add(fence);
redisService.setCacheSet(key1, hashSet);
redisService.expire(key1, 20, TimeUnit.MINUTES); // 设置过期时间
FaultLogs faultLogs = new FaultLogs();
faultLogs.setCarVin(vin);
faultLogs.setFaultCode("GTX007");
faultLogs.setStartAlarmTime(DateUtils.getNowDate());
faultLogs.setAlarmFlag("Y");
faultLogs.setDisposeStatus("1");
rabbitTemplate.convertAndSend(MQQueueConstants.ALARM_QUEUE, faultLogs ,message -> {
message.getMessageProperties().setMessageId(IdUtils.fastSimpleUUID());
return message;
});
}
FaultLogs faultLogs = new FaultLogs();
faultLogs.setCarVin(vin);
faultLogs.setFaultCode("GTX007");
faultLogs.setStartAlarmTime(DateUtils.getNowDate());
faultLogs.setAlarmFlag("Y");
faultLogs.setDisposeStatus("1");
rabbitTemplate.convertAndSend(MQQueueConstants.ALARM_QUEUE, faultLogs, message -> {
message.getMessageProperties().setMessageId(IdUtils.fastSimpleUUID());
return message;
});
}
// if (withinFence){
// log.info("车辆vin:"+vin+"------驶入禁行区----报警");

View File

@ -16,7 +16,7 @@ import org.springframework.stereotype.Service;
*/
@Service("realTime")
@Slf4j
public class RealTimeDataEventImpl implements VehicleService {
public class RealTimeDataEventImpl implements VehicleService {
private VehicleData realTimeData; // 存储实时数据的变量
@ -43,13 +43,13 @@ public class RealTimeDataEventImpl implements VehicleService {
public VehicleData getRealTimeDataByVin(String vin) {
if (realTimeData==null || realTimeData.getVin()==null){
if (realTimeData == null || realTimeData.getVin() == null) {
return null;
}
String dataVin = realTimeData.getVin();
if (dataVin.equals(vin)){
if (dataVin.equals(vin)) {
return realTimeData;
}else{
} else {
return null;
}
}

View File

@ -27,31 +27,31 @@ import java.util.List;
@Slf4j
public class StoredEventImpl implements VehicleService {
@Autowired
private VehicleMapper vehicleMapper;
@Autowired
private RedisService redisService;
@Autowired
private VehicleMapper vehicleMapper;
@Autowired
private RedisService redisService;
private final ArrayList<VehicleData> list = new ArrayList<>();
private final ArrayList<VehicleData> list = new ArrayList<>();
@Override
public void eventResolution(VehicleData analyze) {
Integer id = (Integer)redisService.getCacheObject("records:info:" + analyze.getVin());
Integer id = (Integer) redisService.getCacheObject("records:info:" + analyze.getVin());
analyze.setRecordsId(id);
list.add(analyze);
if (list.size() >= 50) {
log.info("集合满50,存储事件开始");
Boolean i= vehicleMapper.addVehicleStoredEvent(list);
Boolean i = vehicleMapper.addVehicleStoredEvent(list);
if (i) {
list.clear();
log.info("存储事件结束");
}
if (i) {
list.clear();
log.info("存储事件结束");
}
}
}
}

View File

@ -1,7 +1,6 @@
package com.muyu.analyze.utils;
import com.muyu.system.common.domain.VehicleData;
import java.math.BigDecimal;
@ -106,30 +105,29 @@ public class AnalyzeUtils {
* private String brakePedal;
*/
String brakePedal =aa.substring(91,93);
String brakePedal = aa.substring(91, 93);
vehicleData.setBrakePedal(brakePedal);
/**
* private String fuelConsumptionRate;
*/
String fuelConsumptionRate =aa.substring(93,98);
String fuelConsumptionRate = aa.substring(93, 98);
vehicleData.setFuelConsumptionRate(fuelConsumptionRate);
/**
* private String motorControllerTemperature;
*/
String motorControllerTemperature =aa.substring(98,104);
String motorControllerTemperature = aa.substring(98, 104);
vehicleData.setMotorControllerTemperature(motorControllerTemperature);
/**
* private String motorSpeed;
*/
String motorSpeed =aa.substring(104,109);
String motorSpeed = aa.substring(104, 109);
vehicleData.setMotorSpeed(motorSpeed);
@ -247,7 +245,6 @@ public class AnalyzeUtils {
vehicleData.setAvailableBatteryCapacity(availableBatteryCapacity);
// 车辆状态: 0
String vehicleStatus = aa.substring(189, 190);
vehicleData.setVehicleStatus(Integer.parseInt(vehicleStatus));

View File

@ -13,7 +13,7 @@ public class StateConstant {
/**
*
*/
public static final Integer VEHICLE_STATUS = 1;
public static final Integer VEHICLE_STATUS = 1;
/**
*
@ -26,7 +26,7 @@ public class StateConstant {
public static final Integer OPERATING_STATUS = 1;
/**
* soc
* soc
*/
public static final Integer SOC_STATUS = 1;
@ -38,12 +38,12 @@ public class StateConstant {
/**
*
*/
public static final Integer DRIVE_MOTOR_STATUS = 1;
public static final Integer DRIVE_MOTOR_STATUS = 1;
/**
*
*/
public static final Integer POSITION_STATUS = 1;
public static final Integer POSITION_STATUS = 1;
/**
* EAS()
@ -56,7 +56,7 @@ public class StateConstant {
public static final Integer PTC_STATUS = 1;
/**
* ABS()
* ABS()
*/
public static final Integer ABS_STATUS = 1;
@ -69,7 +69,7 @@ public class StateConstant {
*/
public static final Integer HEATING_STATUS = 1;
/**
*
*
*/
public static final Integer BATTERY_STATUS = 1;
/**

View File

@ -6,17 +6,28 @@
<mapper namespace="com.muyu.analyze.mapper.VehicleMapper">
<insert id="addVehicleStoredEvent">
INSERT INTO vehicle_data (vin, date_time, speed, longitude, latitude, single_battery_min_voltage, motor_voltage, motor_speed, self_check_counter, voltage, gear, remaining_battery, motor_current, brake_pedal, current, single_battery_max_voltage, fuel_consumption_rate, resistance, maximum_feedback_power, single_battery_max_temperature,records_id)
INSERT INTO vehicle_data (vin, date_time, speed, longitude, latitude, single_battery_min_voltage, motor_voltage,
motor_speed, self_check_counter, voltage, gear, remaining_battery, motor_current, brake_pedal, current,
single_battery_max_voltage, fuel_consumption_rate, resistance, maximum_feedback_power,
single_battery_max_temperature,records_id)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.vin}, #{item.dateTime}, #{item.speed}, #{item.longitude}, #{item.latitude}, #{item.singleBatteryMinVoltage}, #{item.motorVoltage}, #{item.motorSpeed}, #{item.selfCheckCounter}, #{item.voltage}, #{item.gear}, #{item.remainingBattery}, #{item.motorCurrent}, #{item.brakePedal}, #{item.current}, #{item.singleBatteryMaxVoltage}, #{item.fuelConsumptionRate}, #{item.resistance}, #{item.maximumFeedbackPower}, #{item.singleBatteryMaxTemperature},#{item.recordsId})
(#{item.vin}, #{item.dateTime}, #{item.speed}, #{item.longitude}, #{item.latitude},
#{item.singleBatteryMinVoltage}, #{item.motorVoltage}, #{item.motorSpeed}, #{item.selfCheckCounter},
#{item.voltage}, #{item.gear}, #{item.remainingBattery}, #{item.motorCurrent}, #{item.brakePedal},
#{item.current}, #{item.singleBatteryMaxVoltage}, #{item.fuelConsumptionRate}, #{item.resistance},
#{item.maximumFeedbackPower}, #{item.singleBatteryMaxTemperature},#{item.recordsId})
</foreach>
</insert>
<select id="selectFenceList" resultType="com.muyu.business.domain.Fence">
select car_vin,fence_encoding,fence_id,fence_type,fence_radius from car left join fence on car.car_fence_id=fence.fence_id
select car_vin, fence_encoding, fence_id, fence_type, fence_radius
from car
left join fence on car.car_fence_id = fence.fence_id
</select>
<select id="selectCarList" resultType="com.muyu.system.common.domain.Car">
select car_fence_id from car where car_vin=#{vin}
select car_fence_id
from car
where car_vin = #{vin}
</select>
</mapper>

View File

@ -5,7 +5,7 @@
* @Version 1.0
*/
public class LoadTest {
public void load(){
public void load() {
}
}

View File

@ -11,11 +11,9 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
* @author muyu
*/
@EnableRyFeignClients
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class MuYuAuthApplication
{
public static void main(String[] args)
{
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MuYuAuthApplication {
public static void main(String[] args) {
SpringApplication.run(MuYuAuthApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 认证授权中心启动成功 ლ(´ڡ`ლ)゙ \n" +
" .-------. ____ __ \n" +

View File

@ -27,8 +27,7 @@ import static com.muyu.common.core.domain.Result.success;
* @author muyu
*/
@RestController
public class TokenController
{
public class TokenController {
@Autowired
private TokenService tokenService;
@ -36,8 +35,7 @@ public class TokenController
private SysLoginService sysLoginService;
@PostMapping("login")
public Result<?> login(@RequestBody LoginBody form)
{
public Result<?> login(@RequestBody LoginBody form) {
// 用户登录
LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
// 获取登录token
@ -45,11 +43,9 @@ public class TokenController
}
@DeleteMapping("logout")
public Result<?> logout(HttpServletRequest request)
{
public Result<?> logout(HttpServletRequest request) {
String token = SecurityUtils.getToken(request);
if (StringUtils.isNotEmpty(token))
{
if (StringUtils.isNotEmpty(token)) {
String username = JwtUtils.getUserName(token);
// 删除用户缓存记录
AuthUtil.logoutByToken(token);
@ -60,11 +56,9 @@ public class TokenController
}
@PostMapping("refresh")
public Result<?> refresh(HttpServletRequest request)
{
public Result<?> refresh(HttpServletRequest request) {
LoginUser loginUser = tokenService.getLoginUser(request);
if (StringUtils.isNotNull(loginUser))
{
if (StringUtils.isNotNull(loginUser)) {
// 刷新令牌有效期
tokenService.refreshToken(loginUser);
return success();
@ -73,8 +67,7 @@ public class TokenController
}
@PostMapping("register")
public Result<?> register(@RequestBody RegisterBody registerBody)
{
public Result<?> register(@RequestBody RegisterBody registerBody) {
// 用户注册
sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
return success();

View File

@ -5,7 +5,6 @@ package com.muyu.auth.form;
*
* @author muyu
*/
public class RegisterBody extends LoginBody
{
public class RegisterBody extends LoginBody {
}

View File

@ -27,8 +27,7 @@ import java.util.regex.*;
* @author muyu
*/
@Component
public class SysLoginService
{
public class SysLoginService {
@Autowired
private RemoteUserService remoteUserService;
@ -44,44 +43,38 @@ public class SysLoginService
/**
*
*/
public LoginUser login(String username, String password)
{
public LoginUser login(String username, String password) {
// 用户名或密码为空 错误
if (StringUtils.isAnyBlank(username, password))
{
if (StringUtils.isAnyBlank(username, password)) {
recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
throw new ServiceException("用户/密码必须填写");
}
// 密码如果不在指定范围内 错误
if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH)
{
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
throw new ServiceException("用户密码不在指定范围");
}
// 用户名不在指定范围内 错误
if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|| username.length() > UserConstants.USERNAME_MAX_LENGTH)
{
|| username.length() > UserConstants.USERNAME_MAX_LENGTH) {
recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
throw new ServiceException("用户名不在指定范围");
}
// IP黑名单校验
String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
{
if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾访问IP已被列入系统黑名单");
throw new ServiceException("很遗憾访问IP已被列入系统黑名单");
}
// 查询用户信息
Result<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
{
if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
String emailRegex = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
Pattern pattern = Pattern.compile(emailRegex);
Matcher matcher = pattern.matcher(username);
if(!matcher.matches()){
if (!matcher.matches()) {
recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "邮箱错误,请检查");
throw new ServiceException("邮箱错误,请检查:" + username);
}
@ -89,20 +82,17 @@ public class SysLoginService
throw new ServiceException("登录用户:" + username + " 不存在");
}
if (Result.FAIL == userResult.getCode())
{
if (Result.FAIL == userResult.getCode()) {
throw new ServiceException(userResult.getMsg());
}
LoginUser userInfo = userResult.getData();
SysUser user = userResult.getData().getSysUser();
if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
{
if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起,您的账号已被删除");
throw new ServiceException("对不起,您的账号:" + username + " 已被删除");
}
if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
{
if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用,请联系管理员");
throw new ServiceException("对不起,您的账号:" + username + " 已停用");
}
@ -111,29 +101,24 @@ public class SysLoginService
return userInfo;
}
public void logout(String loginName)
{
public void logout(String loginName) {
recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
}
/**
*
*/
public void register(String username, String password)
{
public void register(String username, String password) {
// 用户名或密码为空 错误
if (StringUtils.isAnyBlank(username, password))
{
if (StringUtils.isAnyBlank(username, password)) {
throw new ServiceException("用户/密码必须填写");
}
if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|| username.length() > UserConstants.USERNAME_MAX_LENGTH)
{
|| username.length() > UserConstants.USERNAME_MAX_LENGTH) {
throw new ServiceException("账户长度必须在2到20个字符之间");
}
if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH)
{
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
throw new ServiceException("密码长度必须在5到20个字符之间");
}
@ -144,8 +129,7 @@ public class SysLoginService
sysUser.setPassword(SecurityUtils.encryptPassword(password));
Result<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);
if (Result.FAIL == registerResult.getCode())
{
if (Result.FAIL == registerResult.getCode()) {
throw new ServiceException(registerResult.getMsg());
}
recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");

View File

@ -18,8 +18,7 @@ import java.util.concurrent.TimeUnit;
* @author muyu
*/
@Component
public class SysPasswordService
{
public class SysPasswordService {
@Autowired
private RedisService redisService;
@ -36,51 +35,41 @@ public class SysPasswordService
* @param username
* @return key
*/
private String getCacheKey(String username)
{
private String getCacheKey(String username) {
return CacheConstants.PWD_ERR_CNT_KEY + username;
}
public void validate(SysUser user, String password)
{
public void validate(SysUser user, String password) {
String username = user.getUserName();
Integer retryCount = redisService.getCacheObject(getCacheKey(username));
if (retryCount == null)
{
if (retryCount == null) {
retryCount = 0;
}
if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
{
if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
String errMsg = String.format("密码输入错误%s次帐户锁定%s分钟", maxRetryCount, lockTime);
recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL,errMsg);
recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, errMsg);
throw new ServiceException(errMsg);
}
if (!matches(user, password))
{
if (!matches(user, password)) {
retryCount = retryCount + 1;
recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, String.format("密码输入错误%s次", retryCount));
redisService.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
throw new ServiceException("用户不存在/密码错误");
}
else
{
} else {
clearLoginRecordCache(username);
}
}
public boolean matches(SysUser user, String rawPassword)
{
public boolean matches(SysUser user, String rawPassword) {
return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
}
public void clearLoginRecordCache(String loginName)
{
if (redisService.hasKey(getCacheKey(loginName)))
{
public void clearLoginRecordCache(String loginName) {
if (redisService.hasKey(getCacheKey(loginName))) {
redisService.deleteObject(getCacheKey(loginName));
}
}

View File

@ -16,8 +16,7 @@ import org.springframework.stereotype.Component;
* @author muyu
*/
@Component
public class SysRecordLogService
{
public class SysRecordLogService {
@Autowired
private RemoteLogService remoteLogService;
@ -25,23 +24,19 @@ public class SysRecordLogService
*
*
* @param username
* @param status
* @param message
* @param status
* @param message
* @return
*/
public void recordLogininfor(String username, String status, String message)
{
public void recordLogininfor(String username, String status, String message) {
SysLogininfor logininfor = new SysLogininfor();
logininfor.setUserName(username);
logininfor.setIpaddr(IpUtils.getIpAddr());
logininfor.setMsg(message);
// 日志状态
if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
{
if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
logininfor.setStatus(Constants.LOGIN_SUCCESS_STATUS);
}
else if (Constants.LOGIN_FAIL.equals(status))
{
} else if (Constants.LOGIN_FAIL.equals(status)) {
logininfor.setStatus(Constants.LOGIN_FAIL_STATUS);
}
remoteLogService.saveLogininfor(logininfor, SecurityConstants.INNER);

View File

@ -1,31 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 日志存放路径 -->
<property name="log.path" value="logs/muyu-auth" />
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
<property name="log.path" value="logs/muyu-auth"/>
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n"/>
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/info.log</file>
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
@ -33,16 +33,16 @@
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/error.log</file>
<file>${log.path}/error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
@ -50,25 +50,25 @@
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.muyu" level="info" />
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn" />
<logger name="com.muyu" level="info"/>
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn"/>
<root level="info">
<appender-ref ref="console" />
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info" />
<appender-ref ref="file_error" />
<appender-ref ref="console"/>
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info"/>
<appender-ref ref="file_error"/>
</root>
</configuration>

View File

@ -17,8 +17,7 @@ import java.math.BigDecimal;
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel
{
public @interface Excel {
/**
* excel
*/
@ -149,34 +148,28 @@ public @interface Excel
*/
Type type() default Type.ALL;
public enum Type
{
public enum Type {
ALL(0), EXPORT(1), IMPORT(2);
private final int value;
Type(int value)
{
Type(int value) {
this.value = value;
}
public int value()
{
public int value() {
return this.value;
}
}
public enum ColumnType
{
public enum ColumnType {
NUMERIC(0), STRING(1), IMAGE(2);
private final int value;
ColumnType(int value)
{
ColumnType(int value) {
this.value = value;
}
public int value()
{
public int value() {
return this.value;
}
}

View File

@ -12,7 +12,6 @@ import java.lang.annotation.Target;
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Excels
{
public @interface Excels {
Excel[] value();
}

View File

@ -5,8 +5,7 @@ package com.muyu.common.core.constant;
*
* @author muyu
*/
public class CacheConstants
{
public class CacheConstants {
/**
* 720
*/

View File

@ -5,8 +5,7 @@ package com.muyu.common.core.constant;
*
* @author muyu
*/
public class Constants
{
public class Constants {
/**
* UTF-8
*/
@ -120,16 +119,16 @@ public class Constants
/**
* json
*/
public static final String[] JSON_WHITELIST_STR = { "org.springframework", "com.muyu" };
public static final String[] JSON_WHITELIST_STR = {"org.springframework", "com.muyu"};
/**
* 访
*/
public static final String[] JOB_WHITELIST_STR = { "com.muyu" };
public static final String[] JOB_WHITELIST_STR = {"com.muyu"};
/**
*
*/
public static final String[] JOB_ERROR_STR = { "java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml",
"org.springframework", "org.apache", "com.muyu.common.core.utils.file" };
public static final String[] JOB_ERROR_STR = {"java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml",
"org.springframework", "org.apache", "com.muyu.common.core.utils.file"};
}

View File

@ -5,113 +5,182 @@ package com.muyu.common.core.constant;
*
* @author muyu
*/
public class GenConstants
{
/** 单表(增删改查) */
public class GenConstants {
/**
*
*/
public static final String TPL_CRUD = "crud";
/** 树表(增删改查) */
/**
*
*/
public static final String TPL_TREE = "tree";
/** 主子表(增删改查) */
/**
*
*/
public static final String TPL_SUB = "sub";
/** 树编码字段 */
/**
*
*/
public static final String TREE_CODE = "treeCode";
/** 树父编码字段 */
/**
*
*/
public static final String TREE_PARENT_CODE = "treeParentCode";
/** 树名称字段 */
/**
*
*/
public static final String TREE_NAME = "treeName";
/** 上级菜单ID字段 */
/**
* ID
*/
public static final String PARENT_MENU_ID = "parentMenuId";
/** 上级菜单名称字段 */
/**
*
*/
public static final String PARENT_MENU_NAME = "parentMenuName";
/** 数据库字符串类型 */
public static final String[] COLUMNTYPE_STR = { "char", "varchar", "nvarchar", "varchar2" };
/**
*
*/
public static final String[] COLUMNTYPE_STR = {"char", "varchar", "nvarchar", "varchar2"};
/** 数据库文本类型 */
public static final String[] COLUMNTYPE_TEXT = { "tinytext", "text", "mediumtext", "longtext" };
/**
*
*/
public static final String[] COLUMNTYPE_TEXT = {"tinytext", "text", "mediumtext", "longtext"};
/** 数据库时间类型 */
public static final String[] COLUMNTYPE_TIME = { "datetime", "time", "date", "timestamp" };
/**
*
*/
public static final String[] COLUMNTYPE_TIME = {"datetime", "time", "date", "timestamp"};
/** 数据库数字类型 */
public static final String[] COLUMNTYPE_NUMBER = { "tinyint", "smallint", "mediumint", "int", "number", "integer",
"bigint", "float", "double", "decimal" };
/**
*
*/
public static final String[] COLUMNTYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "number", "integer",
"bigint", "float", "double", "decimal"};
/** 页面不需要编辑字段 */
public static final String[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "del_flag" };
/**
*
*/
public static final String[] COLUMNNAME_NOT_EDIT = {"id", "create_by", "create_time", "del_flag"};
/** 页面不需要显示的列表字段 */
public static final String[] COLUMNNAME_NOT_LIST = { "id", "create_by", "create_time", "del_flag", "update_by",
"update_time" };
/**
*
*/
public static final String[] COLUMNNAME_NOT_LIST = {"id", "create_by", "create_time", "del_flag", "update_by",
"update_time"};
/** 页面不需要查询字段 */
public static final String[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "del_flag", "update_by",
"update_time", "remark" };
/**
*
*/
public static final String[] COLUMNNAME_NOT_QUERY = {"id", "create_by", "create_time", "del_flag", "update_by",
"update_time", "remark"};
/** Entity基类字段 */
public static final String[] BASE_ENTITY = { "createBy", "createTime", "updateBy", "updateTime", "remark" };
/**
* Entity
*/
public static final String[] BASE_ENTITY = {"createBy", "createTime", "updateBy", "updateTime", "remark"};
/** Tree基类字段 */
public static final String[] TREE_ENTITY = { "parentName", "parentId", "orderNum", "ancestors" };
/**
* Tree
*/
public static final String[] TREE_ENTITY = {"parentName", "parentId", "orderNum", "ancestors"};
/** 文本框 */
/**
*
*/
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_IMAGE_UPLOAD = "imageUpload";
/** 文件上传控件 */
/**
*
*/
public static final String HTML_FILE_UPLOAD = "fileUpload";
/** 富文本控件 */
/**
*
*/
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 QUERY_EQ = "EQ";
/** 需要 */
/**
*
*/
public static final String REQUIRE = "1";
}

View File

@ -5,8 +5,7 @@ package com.muyu.common.core.constant;
*
* @author muyu
*/
public class HttpStatus
{
public class HttpStatus {
/**
*
*/

View File

@ -5,6 +5,7 @@ import org.springframework.stereotype.*;
/**
* MQ
*
* @author LiYongJie
* @date 2024/4/9
*/

View File

@ -5,27 +5,35 @@ package com.muyu.common.core.constant;
*
* @author muyu
*/
public class ScheduleConstants
{
public class ScheduleConstants {
public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME";
/** 执行目标key */
/**
* key
*/
public static final String TASK_PROPERTIES = "TASK_PROPERTIES";
/** 默认 */
/**
*
*/
public static final String MISFIRE_DEFAULT = "0";
/** 立即触发执行 */
/**
*
*/
public static final String MISFIRE_IGNORE_MISFIRES = "1";
/** 触发一次执行 */
/**
*
*/
public static final String MISFIRE_FIRE_AND_PROCEED = "2";
/** 不触发立即执行 */
/**
*
*/
public static final String MISFIRE_DO_NOTHING = "3";
public enum Status
{
public enum Status {
/**
*
*/
@ -37,13 +45,11 @@ public class ScheduleConstants
private String value;
private Status(String value)
{
private Status(String value) {
this.value = value;
}
public String getValue()
{
public String getValue() {
return value;
}
}

View File

@ -5,8 +5,7 @@ package com.muyu.common.core.constant;
*
* @author muyu
*/
public class SecurityConstants
{
public class SecurityConstants {
/**
* ID
*/

View File

@ -5,8 +5,7 @@ package com.muyu.common.core.constant;
*
* @author muyu
*/
public class ServiceNameConstants
{
public class ServiceNameConstants {
/**
* serviceid
*/

View File

@ -5,8 +5,7 @@ package com.muyu.common.core.constant;
*
* @author muyu
*/
public class TokenConstants
{
public class TokenConstants {
/**
*
*/

View File

@ -5,62 +5,95 @@ package com.muyu.common.core.constant;
*
* @author muyu
*/
public class UserConstants
{
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_DISABLE = "1";
/** 角色封禁状态 */
/**
*
*/
public static final String ROLE_DISABLE = "1";
/** 部门正常状态 */
/**
*
*/
public static final String DEPT_NORMAL = "0";
/** 部门停用状态 */
/**
*
*/
public static final String DEPT_DISABLE = "1";
/** 字典正常状态 */
/**
*
*/
public static final String DICT_NORMAL = "0";
/** 是否为系统默认(是) */
/**
*
*/
public static final String YES = "Y";
/** 是否菜单外链(是) */
/**
*
*/
public static final String YES_FRAME = "0";
/** 是否菜单外链(否) */
/**
*
*/
public static final String NO_FRAME = "1";
/** 菜单类型(目录) */
/**
*
*/
public static final String TYPE_DIR = "M";
/** 菜单类型(菜单) */
/**
*
*/
public static final String TYPE_MENU = "C";
/** 菜单类型(按钮) */
/**
*
*/
public static final String TYPE_BUTTON = "F";
/** Layout组件标识 */
/**
* Layout
*/
public final static String LAYOUT = "Layout";
/** ParentView组件标识 */
/**
* ParentView
*/
public final static String PARENT_VIEW = "ParentView";
/** InnerLink组件标识 */
/**
* InnerLink
*/
public final static String INNER_LINK = "InnerLink";
/** 校验是否唯一的返回标识 */
/**
*
*/
public final static boolean UNIQUE = true;
public final static boolean NOT_UNIQUE = false;

View File

@ -14,86 +14,70 @@ import java.util.concurrent.ConcurrentHashMap;
*
* @author muyu
*/
public class SecurityContextHolder
{
public class SecurityContextHolder {
private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();
public static void set(String key, Object value)
{
public static void set(String key, Object value) {
Map<String, Object> map = getLocalMap();
map.put(key, value == null ? StringUtils.EMPTY : value);
}
public static String get(String key)
{
public static String get(String key) {
Map<String, Object> map = getLocalMap();
return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY));
}
public static <T> T get(String key, Class<T> clazz)
{
public static <T> T get(String key, Class<T> clazz) {
Map<String, Object> map = getLocalMap();
return StringUtils.cast(map.getOrDefault(key, null));
}
public static Map<String, Object> getLocalMap()
{
public static Map<String, Object> getLocalMap() {
Map<String, Object> map = THREAD_LOCAL.get();
if (map == null)
{
if (map == null) {
map = new ConcurrentHashMap<String, Object>();
THREAD_LOCAL.set(map);
}
return map;
}
public static void setLocalMap(Map<String, Object> threadLocalMap)
{
public static void setLocalMap(Map<String, Object> threadLocalMap) {
THREAD_LOCAL.set(threadLocalMap);
}
public static Long getUserId()
{
public static Long getUserId() {
return Convert.toLong(get(SecurityConstants.DETAILS_USER_ID), 0L);
}
public static void setUserId(String account)
{
public static void setUserId(String account) {
set(SecurityConstants.DETAILS_USER_ID, account);
}
public static String getUserName()
{
public static String getUserName() {
return get(SecurityConstants.DETAILS_USERNAME);
}
public static void setUserName(String username)
{
public static void setUserName(String username) {
set(SecurityConstants.DETAILS_USERNAME, username);
}
public static String getUserKey()
{
public static String getUserKey() {
return get(SecurityConstants.USER_KEY);
}
public static void setUserKey(String userKey)
{
public static void setUserKey(String userKey) {
set(SecurityConstants.USER_KEY, userKey);
}
public static String getPermission()
{
public static String getPermission() {
return get(SecurityConstants.ROLE_PERMISSION);
}
public static void setPermission(String permissions)
{
public static void setPermission(String permissions) {
set(SecurityConstants.ROLE_PERMISSION, permissions);
}
public static void remove()
{
public static void remove() {
THREAD_LOCAL.remove();
}
}

View File

@ -7,6 +7,7 @@ import java.util.List;
/**
*
*
* @author XiaoFan
* @description:
*/
@ -20,16 +21,20 @@ public class PageResult<T> implements Serializable {
*
*/
private List<T> list;
public PageResult() {
}
public PageResult(long total, List<T> list) {
this.total = total;
this.list = list;
}
public static <T> PageResult<T> toPageResult(long total, List<T> list){
return new PageResult(total , list);
public static <T> PageResult<T> toPageResult(long total, List<T> list) {
return new PageResult(total, list);
}
public static <T> Result<PageResult<T>> toResult(long total, List<T> list){
return Result.success(PageResult.toPageResult(total,list));
public static <T> Result<PageResult<T>> toResult(long total, List<T> list) {
return Result.success(PageResult.toPageResult(total, list));
}
}

View File

@ -10,14 +10,17 @@ import java.io.Serializable;
*
* @author coderjacky
*/
public class Result<T> implements Serializable
{
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
/** 成功 */
/**
*
*/
public static final int SUCCESS = Constants.SUCCESS;
/** 失败 */
/**
*
*/
public static final int FAIL = Constants.FAIL;
private int code;
@ -26,48 +29,39 @@ public class Result<T> implements Serializable
private T data;
public static <T> Result<T> success()
{
public static <T> Result<T> success() {
return restResult(null, SUCCESS, null);
}
public static <T> Result<T> success(T data)
{
public static <T> Result<T> success(T data) {
return restResult(data, SUCCESS, null);
}
public static <T> Result<T> success(T data, String msg)
{
public static <T> Result<T> success(T data, String msg) {
return restResult(data, SUCCESS, msg);
}
public static <T> Result<T> error()
{
public static <T> Result<T> error() {
return restResult(null, FAIL, null);
}
public static <T> Result<T> error(String msg)
{
public static <T> Result<T> error(String msg) {
return restResult(null, FAIL, msg);
}
public static <T> Result<T> error(T data)
{
public static <T> Result<T> error(T data) {
return restResult(data, FAIL, null);
}
public static <T> Result<T> error(T data, String msg)
{
public static <T> Result<T> error(T data, String msg) {
return restResult(data, FAIL, msg);
}
public static <T> Result<T> error(int code, String msg)
{
public static <T> Result<T> error(int code, String msg) {
return restResult(null, code, msg);
}
private static <T> Result<T> restResult(T data, int code, String msg)
{
private static <T> Result<T> restResult(T data, int code, String msg) {
Result<T> apiResult = new Result<>();
apiResult.setCode(code);
apiResult.setData(data);
@ -75,43 +69,35 @@ public class Result<T> implements Serializable
return apiResult;
}
public int getCode()
{
public int getCode() {
return code;
}
public void setCode(int code)
{
public void setCode(int code) {
this.code = code;
}
public String getMsg()
{
public String getMsg() {
return msg;
}
public void setMsg(String msg)
{
public void setMsg(String msg) {
this.msg = msg;
}
public T getData()
{
public T getData() {
return data;
}
public void setData(T data)
{
public void setData(T data) {
this.data = data;
}
public static <T> Boolean isError(Result<T> ret)
{
public static <T> Boolean isError(Result<T> ret) {
return !isSuccess(ret);
}
public static <T> Boolean isSuccess(Result<T> ret)
{
public static <T> Boolean isSuccess(Result<T> ret) {
return Result.SUCCESS == ret.getCode();
}
}

View File

@ -5,26 +5,22 @@ package com.muyu.common.core.enums;
*
* @author muyu
*/
public enum UserStatus
{
public enum UserStatus {
OK("0", "正常"), DISABLE("1", "停用"), DELETED("2", "删除");
private final String code;
private final String info;
UserStatus(String code, String info)
{
UserStatus(String code, String info) {
this.code = code;
this.info = info;
}
public String getCode()
{
public String getCode() {
return code;
}
public String getInfo()
{
public String getInfo() {
return info;
}
}

View File

@ -5,12 +5,10 @@ package com.muyu.common.core.exception;
*
* @author muyu
*/
public class CaptchaException extends RuntimeException
{
public class CaptchaException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CaptchaException(String msg)
{
public CaptchaException(String msg) {
super(msg);
}
}

View File

@ -5,27 +5,22 @@ package com.muyu.common.core.exception;
*
* @author muyu
*/
public class CheckedException extends RuntimeException
{
public class CheckedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CheckedException(String message)
{
public CheckedException(String message) {
super(message);
}
public CheckedException(Throwable cause)
{
public CheckedException(Throwable cause) {
super(cause);
}
public CheckedException(String message, Throwable cause)
{
public CheckedException(String message, Throwable cause) {
super(message, cause);
}
public CheckedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
{
public CheckedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -5,11 +5,9 @@ package com.muyu.common.core.exception;
*
* @author muyu
*/
public class DemoModeException extends RuntimeException
{
public class DemoModeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public DemoModeException()
{
public DemoModeException() {
}
}

View File

@ -5,8 +5,7 @@ package com.muyu.common.core.exception;
*
* @author muyu
*/
public class GlobalException extends RuntimeException
{
public class GlobalException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
@ -16,7 +15,7 @@ public class GlobalException extends RuntimeException
/**
*
*
* <p>
* {@link CommonResult#getDetailMessage()}
*/
private String detailMessage;
@ -24,34 +23,28 @@ public class GlobalException extends RuntimeException
/**
*
*/
public GlobalException()
{
public GlobalException() {
}
public GlobalException(String message)
{
public GlobalException(String message) {
this.message = message;
}
public String getDetailMessage()
{
public String getDetailMessage() {
return detailMessage;
}
public GlobalException setDetailMessage(String detailMessage)
{
public GlobalException setDetailMessage(String detailMessage) {
this.detailMessage = detailMessage;
return this;
}
@Override
public String getMessage()
{
public String getMessage() {
return message;
}
public GlobalException setMessage(String message)
{
public GlobalException setMessage(String message) {
this.message = message;
return this;
}

View File

@ -5,12 +5,10 @@ package com.muyu.common.core.exception;
*
* @author muyu
*/
public class InnerAuthException extends RuntimeException
{
public class InnerAuthException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InnerAuthException(String message)
{
public InnerAuthException(String message) {
super(message);
}
}

View File

@ -5,11 +5,9 @@ package com.muyu.common.core.exception;
*
* @author muyu
*/
public class PreAuthorizeException extends RuntimeException
{
public class PreAuthorizeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public PreAuthorizeException()
{
public PreAuthorizeException() {
}
}

View File

@ -5,8 +5,7 @@ package com.muyu.common.core.exception;
*
* @author muyu
*/
public final class ServiceException extends RuntimeException
{
public final class ServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
@ -21,7 +20,7 @@ public final class ServiceException extends RuntimeException
/**
*
*
* <p>
* {@link CommonResult#getDetailMessage()}
*/
private String detailMessage;
@ -29,45 +28,37 @@ public final class ServiceException extends RuntimeException
/**
*
*/
public ServiceException()
{
public ServiceException() {
}
public ServiceException(String message)
{
public ServiceException(String message) {
this.message = message;
}
public ServiceException(String message, Integer code)
{
public ServiceException(String message, Integer code) {
this.message = message;
this.code = code;
}
public String getDetailMessage()
{
public String getDetailMessage() {
return detailMessage;
}
@Override
public String getMessage()
{
public String getMessage() {
return message;
}
public Integer getCode()
{
public Integer getCode() {
return code;
}
public ServiceException setMessage(String message)
{
public ServiceException setMessage(String message) {
this.message = message;
return this;
}
public ServiceException setDetailMessage(String detailMessage)
{
public ServiceException setDetailMessage(String detailMessage) {
this.detailMessage = detailMessage;
return this;
}

View File

@ -5,22 +5,18 @@ package com.muyu.common.core.exception;
*
* @author muyu
*/
public class UtilException extends RuntimeException
{
public class UtilException extends RuntimeException {
private static final long serialVersionUID = 8247610319171014183L;
public UtilException(Throwable e)
{
public UtilException(Throwable e) {
super(e.getMessage(), e);
}
public UtilException(String message)
{
public UtilException(String message) {
super(message);
}
public UtilException(String message, Throwable throwable)
{
public UtilException(String message, Throwable throwable) {
super(message, throwable);
}
}

View File

@ -5,12 +5,10 @@ package com.muyu.common.core.exception.auth;
*
* @author muyu
*/
public class NotLoginException extends RuntimeException
{
public class NotLoginException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NotLoginException(String message)
{
public NotLoginException(String message) {
super(message);
}
}

View File

@ -7,17 +7,14 @@ import org.apache.commons.lang3.StringUtils;
*
* @author muyu
*/
public class NotPermissionException extends RuntimeException
{
public class NotPermissionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NotPermissionException(String permission)
{
public NotPermissionException(String permission) {
super(permission);
}
public NotPermissionException(String[] permissions)
{
public NotPermissionException(String[] permissions) {
super(StringUtils.join(permissions, ","));
}
}

View File

@ -7,17 +7,14 @@ import org.apache.commons.lang3.StringUtils;
*
* @author muyu
*/
public class NotRoleException extends RuntimeException
{
public class NotRoleException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NotRoleException(String role)
{
public NotRoleException(String role) {
super(role);
}
public NotRoleException(String[] roles)
{
public NotRoleException(String[] roles) {
super(StringUtils.join(roles, ","));
}
}

View File

@ -5,8 +5,7 @@ package com.muyu.common.core.exception.base;
*
* @author muyu
*/
public class BaseException extends RuntimeException
{
public class BaseException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
@ -29,51 +28,42 @@ public class BaseException extends RuntimeException
*/
private String defaultMessage;
public BaseException(String module, String code, Object[] args, 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)
{
public BaseException(String module, String code, Object[] args) {
this(module, code, args, null);
}
public BaseException(String module, String defaultMessage)
{
public BaseException(String module, String defaultMessage) {
this(module, null, null, defaultMessage);
}
public BaseException(String code, Object[] args)
{
public BaseException(String code, Object[] args) {
this(null, code, args, null);
}
public BaseException(String defaultMessage)
{
public BaseException(String defaultMessage) {
this(null, null, null, defaultMessage);
}
public String getModule()
{
public String getModule() {
return module;
}
public String getCode()
{
public String getCode() {
return code;
}
public Object[] getArgs()
{
public Object[] getArgs() {
return args;
}
public String getDefaultMessage()
{
public String getDefaultMessage() {
return defaultMessage;
}
}

View File

@ -7,12 +7,10 @@ import com.muyu.common.core.exception.base.BaseException;
*
* @author muyu
*/
public class FileException extends BaseException
{
public class FileException extends BaseException {
private static final long serialVersionUID = 1L;
public FileException(String code, Object[] args, String msg)
{
public FileException(String code, Object[] args, String msg) {
super("file", code, args, msg);
}

View File

@ -5,12 +5,10 @@ package com.muyu.common.core.exception.file;
*
* @author muyu
*/
public class FileNameLengthLimitExceededException extends FileException
{
public class FileNameLengthLimitExceededException extends FileException {
private static final long serialVersionUID = 1L;
public FileNameLengthLimitExceededException(int defaultFileNameLength)
{
super("upload.filename.exceed.length", new Object[] { defaultFileNameLength }, "the filename is too long");
public FileNameLengthLimitExceededException(int defaultFileNameLength) {
super("upload.filename.exceed.length", new Object[]{defaultFileNameLength}, "the filename is too long");
}
}

View File

@ -5,12 +5,10 @@ package com.muyu.common.core.exception.file;
*
* @author muyu
*/
public class FileSizeLimitExceededException extends FileException
{
public class FileSizeLimitExceededException extends FileException {
private static final long serialVersionUID = 1L;
public FileSizeLimitExceededException(long defaultMaxSize)
{
super("upload.exceed.maxSize", new Object[] { defaultMaxSize }, "the filesize is too large");
public FileSizeLimitExceededException(long defaultMaxSize) {
super("upload.exceed.maxSize", new Object[]{defaultMaxSize}, "the filesize is too large");
}
}

View File

@ -8,54 +8,45 @@ import java.io.PrintWriter;
*
* @author muyu
*/
public class FileUploadException extends Exception
{
public class FileUploadException extends Exception {
private static final long serialVersionUID = 1L;
private final Throwable cause;
public FileUploadException()
{
public FileUploadException() {
this(null, null);
}
public FileUploadException(final String msg)
{
public FileUploadException(final String msg) {
this(msg, null);
}
public FileUploadException(String msg, Throwable cause)
{
public FileUploadException(String msg, Throwable cause) {
super(msg);
this.cause = cause;
}
@Override
public void printStackTrace(PrintStream stream)
{
public void printStackTrace(PrintStream stream) {
super.printStackTrace(stream);
if (cause != null)
{
if (cause != null) {
stream.println("Caused by:");
cause.printStackTrace(stream);
}
}
@Override
public void printStackTrace(PrintWriter writer)
{
public void printStackTrace(PrintWriter writer) {
super.printStackTrace(writer);
if (cause != null)
{
if (cause != null) {
writer.println("Caused by:");
cause.printStackTrace(writer);
}
}
@Override
public Throwable getCause()
{
public Throwable getCause() {
return cause;
}
}

View File

@ -7,73 +7,60 @@ import java.util.Arrays;
*
* @author muyu
*/
public class InvalidExtensionException extends 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)
{
public InvalidExtensionException(String[] allowedExtension, String extension, String filename) {
super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
this.allowedExtension = allowedExtension;
this.extension = extension;
this.filename = filename;
}
public String[] getAllowedExtension()
{
public String[] getAllowedExtension() {
return allowedExtension;
}
public String getExtension()
{
public String getExtension() {
return extension;
}
public String getFilename()
{
public String getFilename() {
return filename;
}
public static class InvalidImageExtensionException extends InvalidExtensionException
{
public static class InvalidImageExtensionException extends InvalidExtensionException {
private static final long serialVersionUID = 1L;
public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename)
{
public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) {
super(allowedExtension, extension, filename);
}
}
public static class InvalidFlashExtensionException extends InvalidExtensionException
{
public static class InvalidFlashExtensionException extends InvalidExtensionException {
private static final long serialVersionUID = 1L;
public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename)
{
public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) {
super(allowedExtension, extension, filename);
}
}
public static class InvalidMediaExtensionException extends InvalidExtensionException
{
public static class InvalidMediaExtensionException extends InvalidExtensionException {
private static final long serialVersionUID = 1L;
public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename)
{
public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) {
super(allowedExtension, extension, filename);
}
}
public static class InvalidVideoExtensionException extends InvalidExtensionException
{
public static class InvalidVideoExtensionException extends InvalidExtensionException {
private static final long serialVersionUID = 1L;
public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename)
{
public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename) {
super(allowedExtension, extension, filename);
}
}

View File

@ -5,30 +5,25 @@ package com.muyu.common.core.exception.job;
*
* @author muyu
*/
public class TaskException extends Exception
{
public class TaskException extends Exception {
private static final long serialVersionUID = 1L;
private Code code;
public TaskException(String msg, Code code)
{
public TaskException(String msg, Code code) {
this(msg, code, null);
}
public TaskException(String msg, Code code, Exception nestedEx)
{
public TaskException(String msg, Code code, Exception nestedEx) {
super(msg, nestedEx);
this.code = code;
}
public Code getCode()
{
public Code getCode() {
return code;
}
public enum Code
{
public enum Code {
TASK_EXISTS, NO_TASK_EXISTS, TASK_ALREADY_STARTED, UNKNOWN, CONFIG_ERROR, TASK_NODE_NOT_AVAILABLE
}
}

View File

@ -5,12 +5,10 @@ package com.muyu.common.core.exception.user;
*
* @author muyu
*/
public class CaptchaExpireException extends UserException
{
public class CaptchaExpireException extends UserException {
private static final long serialVersionUID = 1L;
public CaptchaExpireException()
{
public CaptchaExpireException() {
super("user.jcaptcha.expire", null);
}
}

View File

@ -4,15 +4,13 @@ import com.muyu.common.core.exception.base.BaseException;
/**
*
*
*
* @author muyu
*/
public class UserException extends BaseException
{
public class UserException extends BaseException {
private static final long serialVersionUID = 1L;
public UserException(String code, Object[] args)
{
public UserException(String code, Object[] args) {
super("user", code, args, null);
}
}

View File

@ -5,12 +5,10 @@ package com.muyu.common.core.exception.user;
*
* @author muyu
*/
public class UserPasswordNotMatchException extends UserException
{
public class UserPasswordNotMatchException extends UserException {
private static final long serialVersionUID = 1L;
public UserPasswordNotMatchException()
{
public UserPasswordNotMatchException() {
super("user.password.not.match", null);
}
}

View File

@ -10,20 +10,31 @@ import java.nio.charset.StandardCharsets;
*
* @author muyu
*/
public class CharsetKit
{
/** ISO-8859-1 */
public class CharsetKit {
/**
* ISO-8859-1
*/
public static final String ISO_8859_1 = "ISO-8859-1";
/** UTF-8 */
/**
* UTF-8
*/
public static final String UTF_8 = "UTF-8";
/** GBK */
/**
* GBK
*/
public static final String GBK = "GBK";
/** ISO-8859-1 */
/**
* ISO-8859-1
*/
public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1);
/** UTF-8 */
/**
* UTF-8
*/
public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8);
/** GBK */
/**
* GBK
*/
public static final Charset CHARSET_GBK = Charset.forName(GBK);
/**
@ -32,46 +43,40 @@ public class CharsetKit
* @param charset
* @return Charset
*/
public static Charset charset(String charset)
{
public static Charset charset(String charset) {
return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset);
}
/**
*
*
* @param source
* @param srcCharset ISO-8859-1
* @param source
* @param srcCharset ISO-8859-1
* @param destCharset UTF-8
* @return
*/
public static String convert(String source, String srcCharset, String destCharset)
{
public static String convert(String source, String srcCharset, String destCharset) {
return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset));
}
/**
*
*
* @param source
* @param srcCharset ISO-8859-1
* @param source
* @param srcCharset ISO-8859-1
* @param destCharset UTF-8
* @return
*/
public static String convert(String source, Charset srcCharset, Charset destCharset)
{
if (null == srcCharset)
{
public static String convert(String source, Charset srcCharset, Charset destCharset) {
if (null == srcCharset) {
srcCharset = StandardCharsets.ISO_8859_1;
}
if (null == destCharset)
{
if (null == destCharset) {
destCharset = StandardCharsets.UTF_8;
}
if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset))
{
if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) {
return source;
}
return new String(source.getBytes(srcCharset), destCharset);
@ -80,8 +85,7 @@ public class CharsetKit
/**
* @return
*/
public static String systemCharset()
{
public static String systemCharset() {
return Charset.defaultCharset().name();
}
}

View File

@ -7,8 +7,7 @@ import com.muyu.common.core.utils.StringUtils;
*
* @author muyu
*/
public class StrFormatter
{
public class StrFormatter {
public static final String EMPTY_JSON = "{}";
public static final char C_BACKSLASH = '\\';
public static final char C_DELIM_START = '{';
@ -24,13 +23,11 @@ public class StrFormatter
* \ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param strPattern
* @param argArray
* @param argArray
* @return
*/
public static String format(final String strPattern, final Object... argArray)
{
if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray))
{
public static String format(final String strPattern, final Object... argArray) {
if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray)) {
return strPattern;
}
final int strPatternLength = strPattern.length();
@ -40,43 +37,30 @@ public class StrFormatter
int handledPosition = 0;
int delimIndex;// 占位符所在位置
for (int argIndex = 0; argIndex < argArray.length; argIndex++)
{
for (int argIndex = 0; argIndex < argArray.length; argIndex++) {
delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
if (delimIndex == -1)
{
if (handledPosition == 0)
{
if (delimIndex == -1) {
if (handledPosition == 0) {
return strPattern;
}
else
{ // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
} else { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
sbuf.append(strPattern, handledPosition, strPatternLength);
return sbuf.toString();
}
}
else
{
if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH)
{
if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH)
{
} else {
if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) {
if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) {
// 转义符之前还有一个转义符,占位符依旧有效
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
}
else
{
} else {
// 占位符被转义
argIndex--;
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(C_DELIM_START);
handledPosition = delimIndex + 1;
}
}
else
{
} else {
// 正常占位符
sbuf.append(strPattern, handledPosition, delimIndex);
sbuf.append(Convert.utf8Str(argArray[argIndex]));

View File

@ -13,8 +13,7 @@ import java.util.Date;
*
* @author muyu
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
@ -35,8 +34,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
*
* @return Date()
*/
public static Date getNowDate()
{
public static Date getNowDate() {
return new Date();
}
@ -45,44 +43,34 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
*
* @return String
*/
public static String getDate()
{
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime()
{
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow()
{
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format)
{
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date 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)
{
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
{
public static final Date dateTime(final String format, final String ts) {
try {
return new SimpleDateFormat(format).parse(ts);
}
catch (ParseException e)
{
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
@ -90,8 +78,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/**
* // 2018/08/08
*/
public static final String datePath()
{
public static final String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
@ -99,8 +86,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/**
* // 20180808
*/
public static final String dateTime()
{
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
@ -108,18 +94,13 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/**
*
*/
public static Date parseDate(Object str)
{
if (str == null)
{
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try
{
try {
return parseDate(str.toString(), parsePatterns);
}
catch (ParseException e)
{
} catch (ParseException e) {
return null;
}
}
@ -127,8 +108,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/**
*
*/
public static Date getServerStartDate()
{
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
@ -136,12 +116,11 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/**
*
*
* @param endDate
* @param endDate
* @param startTime
* @return //
*/
public static String timeDistance(Date endDate, Date startTime)
{
public static String timeDistance(Date endDate, Date startTime) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
@ -162,8 +141,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/**
* LocalDateTime ==> Date
*/
public static Date toDate(LocalDateTime temporalAccessor)
{
public static Date toDate(LocalDateTime temporalAccessor) {
ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant());
}
@ -171,8 +149,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils
/**
* LocalDate ==> Date
*/
public static Date toDate(LocalDate temporalAccessor)
{
public static Date toDate(LocalDate temporalAccessor) {
LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant());

View File

@ -10,29 +10,24 @@ import java.io.StringWriter;
*
* @author muyu
*/
public class ExceptionUtil
{
public class ExceptionUtil {
/**
* exception
*/
public static String getExceptionMessage(Throwable e)
{
public static String getExceptionMessage(Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
return sw.toString();
}
public static String getRootErrorMessage(Exception e)
{
public static String getRootErrorMessage(Exception e) {
Throwable root = ExceptionUtils.getRootCause(e);
root = (root == null ? e : root);
if (root == null)
{
if (root == null) {
return "";
}
String msg = root.getMessage();
if (msg == null)
{
if (msg == null) {
return "null";
}
return StringUtils.defaultString(msg);

View File

@ -14,8 +14,7 @@ import java.util.Map;
*
* @author muyu
*/
public class JwtUtils
{
public class JwtUtils {
public static String secret = TokenConstants.SECRET;
/**
@ -24,8 +23,7 @@ public class JwtUtils
* @param claims
* @return
*/
public static String createToken(Map<String, Object> claims)
{
public static String createToken(Map<String, Object> claims) {
String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
return token;
}
@ -36,8 +34,7 @@ public class JwtUtils
* @param token
* @return
*/
public static Claims parseToken(String token)
{
public static Claims parseToken(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}
@ -47,8 +44,7 @@ public class JwtUtils
* @param token
* @return ID
*/
public static String getUserKey(String token)
{
public static String getUserKey(String token) {
Claims claims = parseToken(token);
return getValue(claims, SecurityConstants.USER_KEY);
}
@ -59,8 +55,7 @@ public class JwtUtils
* @param claims
* @return ID
*/
public static String getUserKey(Claims claims)
{
public static String getUserKey(Claims claims) {
return getValue(claims, SecurityConstants.USER_KEY);
}
@ -70,8 +65,7 @@ public class JwtUtils
* @param token
* @return ID
*/
public static String getUserId(String token)
{
public static String getUserId(String token) {
Claims claims = parseToken(token);
return getValue(claims, SecurityConstants.DETAILS_USER_ID);
}
@ -82,8 +76,7 @@ public class JwtUtils
* @param claims
* @return ID
*/
public static String getUserId(Claims claims)
{
public static String getUserId(Claims claims) {
return getValue(claims, SecurityConstants.DETAILS_USER_ID);
}
@ -93,8 +86,7 @@ public class JwtUtils
* @param token
* @return
*/
public static String getUserName(String token)
{
public static String getUserName(String token) {
Claims claims = parseToken(token);
return getValue(claims, SecurityConstants.DETAILS_USERNAME);
}
@ -105,8 +97,7 @@ public class JwtUtils
* @param claims
* @return
*/
public static String getUserName(Claims claims)
{
public static String getUserName(Claims claims) {
return getValue(claims, SecurityConstants.DETAILS_USERNAME);
}
@ -114,11 +105,10 @@ public class JwtUtils
*
*
* @param claims
* @param key
* @param key
* @return
*/
public static String getValue(Claims claims, String key)
{
public static String getValue(Claims claims, String key) {
return Convert.toStr(claims.get(key), "");
}
}

View File

@ -10,13 +10,11 @@ import com.github.pagehelper.PageHelper;
*
* @author muyu
*/
public class PageUtils extends PageHelper
{
public class PageUtils extends PageHelper {
/**
*
*/
public static void startPage()
{
public static void startPage() {
PageDomain pageDomain = TableSupport.buildPageRequest();
Integer pageNum = pageDomain.getPageNum();
Integer pageSize = pageDomain.getPageSize();
@ -28,8 +26,7 @@ public class PageUtils extends PageHelper
/**
* 线
*/
public static void clearPage()
{
public static void clearPage() {
PageHelper.clearPage();
}
}

View File

@ -33,53 +33,46 @@ import java.util.Map;
*
* @author muyu
*/
public class ServletUtils
{
public class ServletUtils {
/**
* String
*/
public static String getParameter(String name)
{
public static String getParameter(String name) {
return getRequest().getParameter(name);
}
/**
* String
*/
public static String getParameter(String name, String defaultValue)
{
public static String getParameter(String name, String defaultValue) {
return Convert.toStr(getRequest().getParameter(name), defaultValue);
}
/**
* Integer
*/
public static Integer getParameterToInt(String name)
{
public static Integer getParameterToInt(String name) {
return Convert.toInt(getRequest().getParameter(name));
}
/**
* Integer
*/
public static Integer getParameterToInt(String name, Integer defaultValue)
{
public static Integer getParameterToInt(String name, Integer defaultValue) {
return Convert.toInt(getRequest().getParameter(name), defaultValue);
}
/**
* Boolean
*/
public static Boolean getParameterToBool(String name)
{
public static Boolean getParameterToBool(String name) {
return Convert.toBool(getRequest().getParameter(name));
}
/**
* Boolean
*/
public static Boolean getParameterToBool(String name, Boolean defaultValue)
{
public static Boolean getParameterToBool(String name, Boolean defaultValue) {
return Convert.toBool(getRequest().getParameter(name), defaultValue);
}
@ -89,8 +82,7 @@ public class ServletUtils
* @param request {@link ServletRequest}
* @return Map
*/
public static Map<String, String[]> getParams(ServletRequest request)
{
public static Map<String, String[]> getParams(ServletRequest request) {
final Map<String, String[]> map = request.getParameterMap();
return Collections.unmodifiableMap(map);
}
@ -101,11 +93,9 @@ public class ServletUtils
* @param request {@link ServletRequest}
* @return Map
*/
public static Map<String, String> getParamMap(ServletRequest request)
{
public static Map<String, String> getParamMap(ServletRequest request) {
Map<String, String> params = new HashMap<>();
for (Map.Entry<String, String[]> entry : getParams(request).entrySet())
{
for (Map.Entry<String, String[]> entry : getParams(request).entrySet()) {
params.put(entry.getKey(), StringUtils.join(entry.getValue(), ","));
}
return params;
@ -114,14 +104,10 @@ public class ServletUtils
/**
* request
*/
public static HttpServletRequest getRequest()
{
try
{
public static HttpServletRequest getRequest() {
try {
return getRequestAttributes().getRequest();
}
catch (Exception e)
{
} catch (Exception e) {
return null;
}
}
@ -129,14 +115,10 @@ public class ServletUtils
/**
* response
*/
public static HttpServletResponse getResponse()
{
try
{
public static HttpServletResponse getResponse() {
try {
return getRequestAttributes().getResponse();
}
catch (Exception e)
{
} catch (Exception e) {
return null;
}
}
@ -144,42 +126,32 @@ public class ServletUtils
/**
* session
*/
public static HttpSession getSession()
{
public static HttpSession getSession() {
return getRequest().getSession();
}
public static ServletRequestAttributes getRequestAttributes()
{
try
{
public static ServletRequestAttributes getRequestAttributes() {
try {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes;
}
catch (Exception e)
{
} catch (Exception e) {
return null;
}
}
public static String getHeader(HttpServletRequest request, String name)
{
public static String getHeader(HttpServletRequest request, String name) {
String value = request.getHeader(name);
if (StringUtils.isEmpty(value))
{
if (StringUtils.isEmpty(value)) {
return StringUtils.EMPTY;
}
return urlDecode(value);
}
public static Map<String, String> getHeaders(HttpServletRequest request)
{
public static Map<String, String> getHeaders(HttpServletRequest request) {
Map<String, String> map = new LinkedCaseInsensitiveMap<>();
Enumeration<String> enumeration = request.getHeaderNames();
if (enumeration != null)
{
while (enumeration.hasMoreElements())
{
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement();
String value = request.getHeader(key);
map.put(key, value);
@ -192,19 +164,15 @@ public class ServletUtils
*
*
* @param response
* @param string
* @param string
*/
public static void renderString(HttpServletResponse response, String string)
{
try
{
public static void renderString(HttpServletResponse response, String string) {
try {
response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
}
catch (IOException e)
{
} catch (IOException e) {
e.printStackTrace();
}
}
@ -214,23 +182,19 @@ public class ServletUtils
*
* @param request
*/
public static boolean isAjaxRequest(HttpServletRequest request)
{
public static boolean isAjaxRequest(HttpServletRequest request) {
String accept = request.getHeader("accept");
if (accept != null && accept.contains("application/json"))
{
if (accept != null && accept.contains("application/json")) {
return true;
}
String xRequestedWith = request.getHeader("X-Requested-With");
if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest"))
{
if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) {
return true;
}
String uri = request.getRequestURI();
if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml"))
{
if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) {
return true;
}
@ -244,14 +208,10 @@ public class ServletUtils
* @param str
* @return
*/
public static String urlEncode(String str)
{
try
{
public static String urlEncode(String str) {
try {
return URLEncoder.encode(str, Constants.UTF8);
}
catch (UnsupportedEncodingException e)
{
} catch (UnsupportedEncodingException e) {
return StringUtils.EMPTY;
}
}
@ -262,14 +222,10 @@ public class ServletUtils
* @param str
* @return
*/
public static String urlDecode(String str)
{
try
{
public static String urlDecode(String str) {
try {
return URLDecoder.decode(str, Constants.UTF8);
}
catch (UnsupportedEncodingException e)
{
} catch (UnsupportedEncodingException e) {
return StringUtils.EMPTY;
}
}
@ -278,11 +234,10 @@ public class ServletUtils
* webflux
*
* @param response ServerHttpResponse
* @param value
* @param value
* @return Mono<Void>
*/
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value)
{
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value) {
return webFluxResponseWriter(response, HttpStatus.OK, value, Result.FAIL);
}
@ -290,12 +245,11 @@ public class ServletUtils
* webflux
*
* @param response ServerHttpResponse
* @param code
* @param value
* @param code
* @param value
* @return Mono<Void>
*/
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value, int code)
{
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value, int code) {
return webFluxResponseWriter(response, HttpStatus.OK, value, code);
}
@ -303,28 +257,26 @@ public class ServletUtils
* webflux
*
* @param response ServerHttpResponse
* @param status http
* @param code
* @param value
* @param status http
* @param code
* @param value
* @return Mono<Void>
*/
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, HttpStatus status, Object value, int code)
{
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, HttpStatus status, Object value, int code) {
return webFluxResponseWriter(response, MediaType.APPLICATION_JSON_VALUE, status, value, code);
}
/**
* webflux
*
* @param response ServerHttpResponse
* @param response ServerHttpResponse
* @param contentType content-type
* @param status http
* @param code
* @param value
* @param status http
* @param code
* @param value
* @return Mono<Void>
*/
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status, Object value, int code)
{
public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, HttpStatus status, Object value, int code) {
response.setStatusCode(status);
response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
Result<?> result = Result.error(code, value.toString());

View File

@ -13,14 +13,14 @@ import org.springframework.stereotype.Component;
* @author muyu
*/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor
{
/** Spring应用上下文环境 */
public final class SpringUtils implements BeanFactoryPostProcessor {
/**
* Spring
*/
private static ConfigurableListableBeanFactory beanFactory;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtils.beanFactory = beanFactory;
}
@ -30,11 +30,9 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param name
* @return Object bean
* @throws BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException
{
public static <T> T getBean(String name) throws BeansException {
return (T) beanFactory.getBean(name);
}
@ -44,10 +42,8 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param clz
* @return
* @throws BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException
{
public static <T> T getBean(Class<T> clz) throws BeansException {
T result = (T) beanFactory.getBean(clz);
return result;
}
@ -58,8 +54,7 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param name
* @return boolean
*/
public static boolean containsBean(String name)
{
public static boolean containsBean(String name) {
return beanFactory.containsBean(name);
}
@ -69,10 +64,8 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param name
* @return boolean
* @throws NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
{
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return beanFactory.isSingleton(name);
}
@ -80,10 +73,8 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param name
* @return Class
* @throws NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
{
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getType(name);
}
@ -93,10 +84,8 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @param name
* @return
* @throws NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
{
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getAliases(name);
}
@ -107,8 +96,7 @@ public final class SpringUtils implements BeanFactoryPostProcessor
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getAopProxy(T invoker)
{
public static <T> T getAopProxy(T invoker) {
return (T) AopContext.currentProxy();
}
}

View File

@ -13,12 +13,15 @@ import java.util.Map;
*
* @author muyu
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils
{
/** 空字符串 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
*
*/
private static final String NULLSTR = "";
/** 下划线 */
/**
* 线
*/
private static final char SEPARATOR = '_';
/**
@ -27,8 +30,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param value defaultValue value
* @return value
*/
public static <T> T nvl(T value, T defaultValue)
{
public static <T> T nvl(T value, T defaultValue) {
return value != null ? value : defaultValue;
}
@ -38,8 +40,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param coll Collection
* @return true false
*/
public static boolean isEmpty(Collection<?> coll)
{
public static boolean isEmpty(Collection<?> coll) {
return isNull(coll) || coll.isEmpty();
}
@ -49,8 +50,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param coll Collection
* @return true false
*/
public static boolean isNotEmpty(Collection<?> coll)
{
public static boolean isNotEmpty(Collection<?> coll) {
return !isEmpty(coll);
}
@ -58,10 +58,9 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* *
*
* @param objects
** @return true false
* * @return true false
*/
public static boolean isEmpty(Object[] objects)
{
public static boolean isEmpty(Object[] objects) {
return isNull(objects) || (objects.length == 0);
}
@ -71,8 +70,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param objects
* @return true false
*/
public static boolean isNotEmpty(Object[] objects)
{
public static boolean isNotEmpty(Object[] objects) {
return !isEmpty(objects);
}
@ -82,8 +80,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param map Map
* @return true false
*/
public static boolean isEmpty(Map<?, ?> map)
{
public static boolean isEmpty(Map<?, ?> map) {
return isNull(map) || map.isEmpty();
}
@ -93,8 +90,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param map Map
* @return true false
*/
public static boolean isNotEmpty(Map<?, ?> map)
{
public static boolean isNotEmpty(Map<?, ?> map) {
return !isEmpty(map);
}
@ -104,8 +100,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param str String
* @return true false
*/
public static boolean isEmpty(String str)
{
public static boolean isEmpty(String str) {
return isNull(str) || NULLSTR.equals(str.trim());
}
@ -115,8 +110,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param str String
* @return true false
*/
public static boolean isNotEmpty(String str)
{
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
@ -126,8 +120,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param object Object
* @return true false
*/
public static boolean isNull(Object object)
{
public static boolean isNull(Object object) {
return object == null;
}
@ -137,8 +130,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param object Object
* @return true false
*/
public static boolean isNotNull(Object object)
{
public static boolean isNotNull(Object object) {
return !isNull(object);
}
@ -148,44 +140,37 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param object
* @return true false
*/
public static boolean isArray(Object object)
{
public static boolean isArray(Object object) {
return isNotNull(object) && object.getClass().isArray();
}
/**
*
*/
public static String trim(String str)
{
public static String trim(String str) {
return (str == null ? "" : str.trim());
}
/**
*
*
* @param str
* @param str
* @param start
* @return
*/
public static String substring(final String str, int start)
{
if (str == null)
{
public static String substring(final String str, int start) {
if (str == null) {
return NULLSTR;
}
if (start < 0)
{
if (start < 0) {
start = str.length() + start;
}
if (start < 0)
{
if (start < 0) {
start = 0;
}
if (start > str.length())
{
if (start > str.length()) {
return NULLSTR;
}
@ -195,43 +180,35 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/**
*
*
* @param str
* @param str
* @param start
* @param end
* @param end
* @return
*/
public static String substring(final String str, int start, int end)
{
if (str == null)
{
public static String substring(final String str, int start, int end) {
if (str == null) {
return NULLSTR;
}
if (end < 0)
{
if (end < 0) {
end = str.length() + end;
}
if (start < 0)
{
if (start < 0) {
start = str.length() + start;
}
if (end > str.length())
{
if (end > str.length()) {
end = str.length();
}
if (start > end)
{
if (start > end) {
return NULLSTR;
}
if (start < 0)
{
if (start < 0) {
start = 0;
}
if (end < 0)
{
if (end < 0) {
end = 0;
}
@ -244,18 +221,14 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param str value
* @return
*/
public static boolean hasText(String str)
{
public static boolean hasText(String str) {
return (str != null && !str.isEmpty() && containsText(str));
}
private static boolean containsText(CharSequence str)
{
private static boolean containsText(CharSequence str) {
int strLen = str.length();
for (int i = 0; i < strLen; i++)
{
if (!Character.isWhitespace(str.charAt(i)))
{
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
@ -272,13 +245,11 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* \ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param template {}
* @param params
* @param params
* @return
*/
public static String format(String template, Object... params)
{
if (isEmpty(params) || isEmpty(template))
{
public static String format(String template, Object... params) {
if (isEmpty(params) || isEmpty(template)) {
return template;
}
return StrFormatter.format(template, params);
@ -290,8 +261,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param link
* @return
*/
public static boolean ishttp(String link)
{
public static boolean ishttp(String link) {
return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS);
}
@ -299,21 +269,15 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* collectionarray arrayvalue
*
* @param collection
* @param array
* @param array
* @return boolean
*/
public static boolean containsAny(Collection<String> collection, String... array)
{
if (isEmpty(collection) || isEmpty(array))
{
public static boolean containsAny(Collection<String> collection, String... array) {
if (isEmpty(collection) || isEmpty(array)) {
return false;
}
else
{
for (String str : array)
{
if (collection.contains(str))
{
} else {
for (String str : array) {
if (collection.contains(str)) {
return true;
}
}
@ -324,10 +288,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/**
* 线
*/
public static String toUnderScoreCase(String str)
{
if (str == null)
{
public static String toUnderScoreCase(String str) {
if (str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
@ -337,31 +299,23 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
boolean curreCharIsUpperCase = true;
// 下一字符是否大写
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++)
{
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i > 0)
{
if (i > 0) {
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
}
else
{
} else {
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1))
{
if (i < (str.length() - 1)) {
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase)
{
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
sb.append(SEPARATOR);
}
else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
{
} else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
sb.append(SEPARATOR);
}
sb.append(Character.toLowerCase(c));
@ -373,18 +327,14 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/**
*
*
* @param str
* @param str
* @param strs
* @return true
*/
public static boolean inStringIgnoreCase(String str, String... strs)
{
if (str != null && strs != null)
{
for (String s : strs)
{
if (str.equalsIgnoreCase(trim(s)))
{
public static boolean inStringIgnoreCase(String str, String... strs) {
if (str != null && strs != null) {
for (String s : strs) {
if (str.equalsIgnoreCase(trim(s))) {
return true;
}
}
@ -398,27 +348,21 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* @param name 线
* @return
*/
public static String convertToCamelCase(String name)
{
public static String convertToCamelCase(String name) {
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty())
{
if (name == null || name.isEmpty()) {
// 没必要转换
return "";
}
else if (!name.contains("_"))
{
} else if (!name.contains("_")) {
// 不含下划线,仅将首字母大写
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
// 用下划线将原始字符串分割
String[] camels = name.split("_");
for (String camel : camels)
{
for (String camel : camels) {
// 跳过原始字符串中开头、结尾的下换线或双重下划线
if (camel.isEmpty())
{
if (camel.isEmpty()) {
continue;
}
// 首字母大写
@ -432,34 +376,25 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
*
* user_name->userName
*/
public static String toCamelCase(String s)
{
if (s == null)
{
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
if (s.indexOf(SEPARATOR) == -1)
{
if (s.indexOf(SEPARATOR) == -1) {
return s;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++)
{
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == SEPARATOR)
{
if (c == SEPARATOR) {
upperCase = true;
}
else if (upperCase)
{
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
}
else
{
} else {
sb.append(c);
}
}
@ -469,20 +404,16 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/**
*
*
* @param str
* @param str
* @param strs
* @return
*/
public static boolean matches(String str, List<String> strs)
{
if (isEmpty(str) || isEmpty(strs))
{
public static boolean matches(String str, List<String> strs) {
if (isEmpty(str) || isEmpty(strs)) {
return false;
}
for (String pattern : strs)
{
if (isMatch(pattern, str))
{
for (String pattern : strs) {
if (isMatch(pattern, str)) {
return true;
}
}
@ -496,64 +427,52 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
* ** ;
*
* @param pattern
* @param url url
* @param url url
* @return
*/
public static boolean isMatch(String pattern, String url)
{
public static boolean isMatch(String pattern, String url) {
AntPathMatcher matcher = new AntPathMatcher();
return matcher.match(pattern, url);
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj)
{
public static <T> T cast(Object obj) {
return (T) obj;
}
/**
* 0使size size
*
* @param num
* @param num
* @param size
* @return
*/
public static final String padl(final Number num, final int size)
{
public static final String padl(final Number num, final int size) {
return padl(num.toString(), size, '0');
}
/**
* ssizesize
*
* @param s
* @param s
* @param size
* @param c
* @param c
* @return
*/
public static final String padl(final String s, final int size, final char c)
{
public static final String padl(final String s, final int size, final char c) {
final StringBuilder sb = new StringBuilder(size);
if (s != null)
{
if (s != null) {
final int len = s.length();
if (s.length() <= size)
{
for (int i = size - len; i > 0; i--)
{
if (s.length() <= size) {
for (int i = size - len; i > 0; i--) {
sb.append(c);
}
sb.append(s);
}
else
{
} else {
return s.substring(len - size, len);
}
}
else
{
for (int i = size; i > 0; i--)
{
} else {
for (int i = size; i > 0; i--) {
sb.append(c);
}
}

View File

@ -11,31 +11,32 @@ import java.util.regex.Pattern;
*
* @author muyu
*/
public class BeanUtils extends org.springframework.beans.BeanUtils
{
/** Bean方法名中属性名开始的下标 */
public class BeanUtils extends org.springframework.beans.BeanUtils {
/**
* Bean
*/
private static final int BEAN_METHOD_PROP_INDEX = 3;
/** * 匹配getter方法的正则表达式 */
/**
* getter
*/
private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)");
/** * 匹配setter方法的正则表达式 */
/**
* setter
*/
private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)");
/**
* Bean
*
* @param dest
* @param src
* @param src
*/
public static void copyBeanProp(Object dest, Object src)
{
try
{
public static void copyBeanProp(Object dest, Object src) {
try {
copyProperties(src, dest);
}
catch (Exception e)
{
} catch (Exception e) {
e.printStackTrace();
}
}
@ -46,8 +47,7 @@ public class BeanUtils extends org.springframework.beans.BeanUtils
* @param obj
* @return setter
*/
public static List<Method> getSetterMethods(Object obj)
{
public static List<Method> getSetterMethods(Object obj) {
// setter方法列表
List<Method> setterMethods = new ArrayList<Method>();
@ -56,11 +56,9 @@ public class BeanUtils extends org.springframework.beans.BeanUtils
// 查找setter方法
for (Method method : methods)
{
for (Method method : methods) {
Matcher m = SET_PATTERN.matcher(method.getName());
if (m.matches() && (method.getParameterTypes().length == 1))
{
if (m.matches() && (method.getParameterTypes().length == 1)) {
setterMethods.add(method);
}
}
@ -75,18 +73,15 @@ public class BeanUtils extends org.springframework.beans.BeanUtils
* @return getter
*/
public static List<Method> getGetterMethods(Object obj)
{
public static List<Method> getGetterMethods(Object obj) {
// getter方法列表
List<Method> getterMethods = new ArrayList<Method>();
// 获取所有方法
Method[] methods = obj.getClass().getMethods();
// 查找getter方法
for (Method method : methods)
{
for (Method method : methods) {
Matcher m = GET_PATTERN.matcher(method.getName());
if (m.matches() && (method.getParameterTypes().length == 0))
{
if (m.matches() && (method.getParameterTypes().length == 0)) {
getterMethods.add(method);
}
}
@ -103,8 +98,7 @@ public class BeanUtils extends org.springframework.beans.BeanUtils
* @return truefalse
*/
public static boolean isMethodPropEquals(String m1, String m2)
{
public static boolean isMethodPropEquals(String m1, String m2) {
return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX));
}
}

View File

@ -10,14 +10,11 @@ import java.util.Set;
*
* @author muyu
*/
public class BeanValidators
{
public class BeanValidators {
public static void validateWithException(Validator validator, Object object, Class<?>... groups)
throws ConstraintViolationException
{
throws ConstraintViolationException {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
if (!constraintViolations.isEmpty())
{
if (!constraintViolations.isEmpty()) {
throw new ConstraintViolationException(constraintViolations);
}
}

View File

@ -12,8 +12,7 @@ import java.util.Objects;
*
* @author muyu
*/
public class FileTypeUtils
{
public class FileTypeUtils {
/**
*
* <p>
@ -22,10 +21,8 @@ public class FileTypeUtils
* @param file
* @return ".")
*/
public static String getFileType(File file)
{
if (null == file)
{
public static String getFileType(File file) {
if (null == file) {
return StringUtils.EMPTY;
}
return getFileType(file.getName());
@ -39,11 +36,9 @@ public class FileTypeUtils
* @param fileName
* @return ".")
*/
public static String getFileType(String fileName)
{
public static String getFileType(String fileName) {
int separatorIndex = fileName.lastIndexOf(".");
if (separatorIndex < 0)
{
if (separatorIndex < 0) {
return "";
}
return fileName.substring(separatorIndex + 1).toLowerCase();
@ -55,11 +50,9 @@ public class FileTypeUtils
* @param file
* @return
*/
public static final String getExtension(MultipartFile file)
{
public static final String getExtension(MultipartFile file) {
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if (StringUtils.isEmpty(extension))
{
if (StringUtils.isEmpty(extension)) {
extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
}
return extension;
@ -71,24 +64,16 @@ public class FileTypeUtils
* @param photoByte
* @return ".")
*/
public static String getFileExtendName(byte[] photoByte)
{
public static String getFileExtendName(byte[] photoByte) {
String strFileExtendName = "JPG";
if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
&& ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97))
{
&& ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) {
strFileExtendName = "GIF";
}
else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70))
{
} else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) {
strFileExtendName = "JPG";
}
else if ((photoByte[0] == 66) && (photoByte[1] == 77))
{
} else if ((photoByte[0] == 66) && (photoByte[1] == 77)) {
strFileExtendName = "BMP";
}
else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
{
} else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) {
strFileExtendName = "PNG";
}
return strFileExtendName;

View File

@ -14,12 +14,15 @@ import java.nio.charset.StandardCharsets;
*
* @author muyu
*/
public class FileUtils
{
/** 字符常量:斜杠 {@code '/'} */
public class FileUtils {
/**
* {@code '/'}
*/
public static final char SLASH = '/';
/** 字符常量:反斜杠 {@code '\\'} */
/**
* {@code '\\'}
*/
public static final char BACKSLASH = '\\';
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
@ -28,52 +31,36 @@ public class FileUtils
* byte
*
* @param filePath
* @param os
* @param os
* @return
*/
public static void writeBytes(String filePath, OutputStream os) throws IOException
{
public static void writeBytes(String filePath, OutputStream os) throws IOException {
FileInputStream fis = null;
try
{
try {
File file = new File(filePath);
if (!file.exists())
{
if (!file.exists()) {
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0)
{
while ((length = fis.read(b)) > 0) {
os.write(b, 0, length);
}
}
catch (IOException e)
{
} catch (IOException e) {
throw e;
}
finally
{
if (os != null)
{
try
{
} finally {
if (os != null) {
try {
os.close();
}
catch (IOException e1)
{
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fis != null)
{
try
{
if (fis != null) {
try {
fis.close();
}
catch (IOException e1)
{
} catch (IOException e1) {
e1.printStackTrace();
}
}
@ -86,13 +73,11 @@ public class FileUtils
* @param filePath
* @return
*/
public static boolean deleteFile(String filePath)
{
public static boolean deleteFile(String filePath) {
boolean flag = false;
File file = new File(filePath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists())
{
if (file.isFile() && file.exists()) {
flag = file.delete();
}
return flag;
@ -104,8 +89,7 @@ public class FileUtils
* @param filename
* @return true false
*/
public static boolean isValidFilename(String filename)
{
public static boolean isValidFilename(String filename) {
return filename.matches(FILENAME_PATTERN);
}
@ -115,11 +99,9 @@ public class FileUtils
* @param resource
* @return true false
*/
public static boolean checkAllowDownload(String resource)
{
public static boolean checkAllowDownload(String resource) {
// 禁止目录上跳级别
if (StringUtils.contains(resource, ".."))
{
if (StringUtils.contains(resource, "..")) {
return false;
}
// 判断是否在允许下载的文件规则内
@ -129,32 +111,24 @@ public class FileUtils
/**
*
*
* @param request
* @param request
* @param fileName
* @return
*/
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
{
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
final String agent = request.getHeader("USER-AGENT");
String filename = fileName;
if (agent.contains("MSIE"))
{
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
}
else if (agent.contains("Firefox"))
{
} else if (agent.contains("Firefox")) {
// 火狐浏览器
filename = new String(fileName.getBytes(), "ISO8859-1");
}
else if (agent.contains("Chrome"))
{
} else if (agent.contains("Chrome")) {
// google浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
else
{
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
@ -167,30 +141,24 @@ public class FileUtils
* @param filePath
* @return
*/
public static String getName(String filePath)
{
if (null == filePath)
{
public static String getName(String filePath) {
if (null == filePath) {
return null;
}
int len = filePath.length();
if (0 == len)
{
if (0 == len) {
return filePath;
}
if (isFileSeparator(filePath.charAt(len - 1)))
{
if (isFileSeparator(filePath.charAt(len - 1))) {
// 以分隔符结尾的去掉结尾分隔符
len--;
}
int begin = 0;
char c;
for (int i = len - 1; i > -1; i--)
{
for (int i = len - 1; i > -1; i--) {
c = filePath.charAt(i);
if (isFileSeparator(c))
{
if (isFileSeparator(c)) {
// 查找最后一个路径分隔符(/或者\
begin = i + 1;
break;
@ -207,20 +175,18 @@ public class FileUtils
* @param c
* @return WindowsLinuxUnix
*/
public static boolean isFileSeparator(char c)
{
public static boolean isFileSeparator(char c) {
return SLASH == c || BACKSLASH == c;
}
/**
*
*
* @param response
* @param response
* @param realFileName
* @return
*/
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
{
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
@ -241,8 +207,7 @@ public class FileUtils
* @param s
* @return
*/
public static String percentEncode(String s) throws UnsupportedEncodingException
{
public static String percentEncode(String s) throws UnsupportedEncodingException {
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20");
}

View File

@ -15,38 +15,27 @@ import java.util.Arrays;
*
* @author muyu
*/
public class ImageUtils
{
public class ImageUtils {
private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
public static byte[] getImage(String imagePath)
{
public static byte[] getImage(String imagePath) {
InputStream is = getFile(imagePath);
try
{
try {
return IOUtils.toByteArray(is);
}
catch (Exception e)
{
} catch (Exception e) {
log.error("图片加载异常 {}", e);
return null;
}
finally
{
} finally {
IOUtils.closeQuietly(is);
}
}
public static InputStream getFile(String imagePath)
{
try
{
public static InputStream getFile(String imagePath) {
try {
byte[] result = readFile(imagePath);
result = Arrays.copyOf(result, result.length);
return new ByteArrayInputStream(result);
}
catch (Exception e)
{
} catch (Exception e) {
log.error("获取图片异常 {}", e);
}
return null;
@ -58,11 +47,9 @@ public class ImageUtils
* @param url
* @return
*/
public static byte[] readFile(String url)
{
public static byte[] readFile(String url) {
InputStream in = null;
try
{
try {
// 网络地址
URL urlObj = new URL(url);
URLConnection urlConnection = urlObj.openConnection();
@ -71,14 +58,10 @@ public class ImageUtils
urlConnection.setDoInput(true);
in = urlConnection.getInputStream();
return IOUtils.toByteArray(in);
}
catch (Exception e)
{
} catch (Exception e) {
log.error("访问文件异常 {}", e);
return null;
}
finally
{
} finally {
IOUtils.closeQuietly(in);
}
}

View File

@ -5,8 +5,7 @@ package com.muyu.common.core.utils.file;
*
* @author muyu
*/
public class MimeTypeUtils
{
public class MimeTypeUtils {
public static final String IMAGE_PNG = "image/png";
public static final String IMAGE_JPG = "image/jpg";
@ -17,14 +16,14 @@ public class MimeTypeUtils
public static final String IMAGE_GIF = "image/gif";
public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" };
public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};
public static final String[] FLASH_EXTENSION = { "swf", "flv" };
public static final String[] FLASH_EXTENSION = {"swf", "flv"};
public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
"asf", "rm", "rmvb" };
public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
"asf", "rm", "rmvb"};
public static final String[] VIDEO_EXTENSION = { "mp4", "avi", "rmvb" };
public static final String[] VIDEO_EXTENSION = {"mp4", "avi", "rmvb"};
public static final String[] DEFAULT_ALLOWED_EXTENSION = {
// 图片
@ -36,12 +35,10 @@ public class MimeTypeUtils
// 视频格式
"mp4", "avi", "rmvb",
// pdf
"pdf" };
"pdf"};
public static String getExtension(String prefix)
{
switch (prefix)
{
public static String getExtension(String prefix) {
switch (prefix) {
case IMAGE_PNG:
return "png";
case IMAGE_JPG:

View File

@ -7,17 +7,14 @@ import com.muyu.common.core.utils.StringUtils;
*
* @author muyu
*/
public class EscapeUtil
{
public class EscapeUtil {
public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)";
private static final char[][] TEXT = new char[64][];
static
{
for (int i = 0; i < 64; i++)
{
TEXT[i] = new char[] { (char) i };
static {
for (int i = 0; i < 64; i++) {
TEXT[i] = new char[]{(char) i};
}
// special HTML characters
@ -34,8 +31,7 @@ public class EscapeUtil
* @param text
* @return
*/
public static String escape(String text)
{
public static String escape(String text) {
return encode(text);
}
@ -45,8 +41,7 @@ public class EscapeUtil
* @param content HTML
* @return
*/
public static String unescape(String content)
{
public static String unescape(String content) {
return decode(content);
}
@ -56,8 +51,7 @@ public class EscapeUtil
* @param content
* @return
*/
public static String clean(String content)
{
public static String clean(String content) {
return new HTMLFilter().filter(content);
}
@ -67,32 +61,24 @@ public class EscapeUtil
* @param text
* @return
*/
private static String encode(String text)
{
if (StringUtils.isEmpty(text))
{
private static String encode(String text) {
if (StringUtils.isEmpty(text)) {
return StringUtils.EMPTY;
}
final StringBuilder tmp = new StringBuilder(text.length() * 6);
char c;
for (int i = 0; i < text.length(); i++)
{
for (int i = 0; i < text.length(); i++) {
c = text.charAt(i);
if (c < 256)
{
if (c < 256) {
tmp.append("%");
if (c < 16)
{
if (c < 16) {
tmp.append("0");
}
tmp.append(Integer.toString(c, 16));
}
else
{
} else {
tmp.append("%u");
if (c <= 0xfff)
{
if (c <= 0xfff) {
// issue#I49JU8@Gitee
tmp.append("0");
}
@ -108,43 +94,31 @@ public class EscapeUtil
* @param content
* @return
*/
public static String decode(String content)
{
if (StringUtils.isEmpty(content))
{
public static String decode(String content) {
if (StringUtils.isEmpty(content)) {
return content;
}
StringBuilder tmp = new StringBuilder(content.length());
int lastPos = 0, pos = 0;
char ch;
while (lastPos < content.length())
{
while (lastPos < content.length()) {
pos = content.indexOf("%", lastPos);
if (pos == lastPos)
{
if (content.charAt(pos + 1) == 'u')
{
if (pos == lastPos) {
if (content.charAt(pos + 1) == 'u') {
ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16);
tmp.append(ch);
lastPos = pos + 6;
}
else
{
} else {
ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16);
tmp.append(ch);
lastPos = pos + 3;
}
}
else
{
if (pos == -1)
{
} else {
if (pos == -1) {
tmp.append(content.substring(lastPos));
lastPos = content.length();
}
else
{
} else {
tmp.append(content.substring(lastPos, pos));
lastPos = pos;
}
@ -153,8 +127,7 @@ public class EscapeUtil
return tmp.toString();
}
public static void main(String[] args)
{
public static void main(String[] args) {
String html = "<script>alert(1);</script>";
String escape = EscapeUtil.escape(html);
// String html = "<scr<script>ipt>alert(\"XSS\")</scr<script>ipt>";

View File

@ -11,8 +11,7 @@ import java.util.regex.Pattern;
*
* @author muyu
*/
public final class HTMLFilter
{
public final class HTMLFilter {
/**
* regex flag union representing /si modifiers in php
**/
@ -96,8 +95,7 @@ public final class HTMLFilter
/**
* Default constructor.
*/
public HTMLFilter()
{
public HTMLFilter() {
vAllowed = new HashMap<>();
final ArrayList<String> a_atts = new ArrayList<>();
@ -118,13 +116,13 @@ public final class HTMLFilter
vAllowed.put("i", no_atts);
vAllowed.put("em", no_atts);
vSelfClosingTags = new String[] { "img" };
vNeedClosingTags = new String[] { "a", "b", "strong", "i", "em" };
vDisallowed = new String[] {};
vAllowedProtocols = new String[] { "http", "mailto", "https" }; // no ftp.
vProtocolAtts = new String[] { "src", "href" };
vRemoveBlanks = new String[] { "a", "b", "strong", "i", "em" };
vAllowedEntities = new String[] { "amp", "gt", "lt", "quot" };
vSelfClosingTags = new String[]{"img"};
vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"};
vDisallowed = new String[]{};
vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp.
vProtocolAtts = new String[]{"src", "href"};
vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"};
vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"};
stripComment = true;
encodeQuotes = true;
alwaysMakeTags = false;
@ -136,8 +134,7 @@ public final class HTMLFilter
* @param conf map containing configuration. keys match field names.
*/
@SuppressWarnings("unchecked")
public HTMLFilter(final Map<String, Object> conf)
{
public HTMLFilter(final Map<String, Object> conf) {
assert conf.containsKey("vAllowed") : "configuration requires vAllowed";
assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags";
@ -161,20 +158,17 @@ public final class HTMLFilter
alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true;
}
private void reset()
{
private void reset() {
vTagCounts.clear();
}
// ---------------------------------------------------------------
// my versions of some PHP library functions
public static String chr(final int decimal)
{
public static String chr(final int decimal) {
return String.valueOf((char) decimal);
}
public static String htmlSpecialChars(final String s)
{
public static String htmlSpecialChars(final String s) {
String result = s;
result = regexReplace(P_AMP, "&amp;", result);
result = regexReplace(P_QUOTE, "&quot;", result);
@ -191,8 +185,7 @@ public final class HTMLFilter
* @param input text (i.e. submitted by a user) than may contain html
* @return "clean" version of input, with only valid, whitelisted html elements allowed
*/
public String filter(final String input)
{
public String filter(final String input) {
reset();
String s = input;
@ -209,22 +202,18 @@ public final class HTMLFilter
return s;
}
public boolean isAlwaysMakeTags()
{
public boolean isAlwaysMakeTags() {
return alwaysMakeTags;
}
public boolean isStripComments()
{
public boolean isStripComments() {
return stripComment;
}
private String escapeComments(final String s)
{
private String escapeComments(final String s) {
final Matcher m = P_COMMENTS.matcher(s);
final StringBuffer buf = new StringBuffer();
if (m.find())
{
if (m.find()) {
final String match = m.group(1); // (.*?)
m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->"));
}
@ -233,10 +222,8 @@ public final class HTMLFilter
return buf.toString();
}
private String balanceHTML(String s)
{
if (alwaysMakeTags)
{
private String balanceHTML(String s) {
if (alwaysMakeTags) {
//
// try and form html
//
@ -245,9 +232,7 @@ public final class HTMLFilter
s = regexReplace(P_BODY_TO_END, "<$1>", s);
s = regexReplace(P_XML_CONTENT, "$1<$2", s);
}
else
{
} else {
//
// escape stray brackets
//
@ -265,13 +250,11 @@ public final class HTMLFilter
return s;
}
private String checkTags(String s)
{
private String checkTags(String s) {
Matcher m = P_TAGS.matcher(s);
final StringBuffer buf = new StringBuffer();
while (m.find())
{
while (m.find()) {
String replaceStr = m.group(1);
replaceStr = processTag(replaceStr);
m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr));
@ -281,10 +264,8 @@ public final class HTMLFilter
// these get tallied in processTag
// (remember to reset before subsequent calls to filter method)
final StringBuilder sBuilder = new StringBuilder(buf.toString());
for (String key : vTagCounts.keySet())
{
for (int ii = 0; ii < vTagCounts.get(key); ii++)
{
for (String key : vTagCounts.keySet()) {
for (int ii = 0; ii < vTagCounts.get(key); ii++) {
sBuilder.append("</").append(key).append(">");
}
}
@ -293,18 +274,14 @@ public final class HTMLFilter
return s;
}
private String processRemoveBlanks(final String s)
{
private String processRemoveBlanks(final String s) {
String result = s;
for (String tag : vRemoveBlanks)
{
if (!P_REMOVE_PAIR_BLANKS.containsKey(tag))
{
for (String tag : vRemoveBlanks) {
if (!P_REMOVE_PAIR_BLANKS.containsKey(tag)) {
P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
}
result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);
if (!P_REMOVE_SELF_BLANKS.containsKey(tag))
{
if (!P_REMOVE_SELF_BLANKS.containsKey(tag)) {
P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
}
result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);
@ -313,25 +290,19 @@ public final class HTMLFilter
return result;
}
private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s)
{
private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) {
Matcher m = regex_pattern.matcher(s);
return m.replaceAll(replacement);
}
private String processTag(final String s)
{
private String processTag(final String s) {
// ending tags
Matcher m = P_END_TAG.matcher(s);
if (m.find())
{
if (m.find()) {
final String name = m.group(1).toLowerCase();
if (allowed(name))
{
if (!inArray(name, vSelfClosingTags))
{
if (vTagCounts.containsKey(name))
{
if (allowed(name)) {
if (!inArray(name, vSelfClosingTags)) {
if (vTagCounts.containsKey(name)) {
vTagCounts.put(name, vTagCounts.get(name) - 1);
return "</" + name + ">";
}
@ -341,35 +312,30 @@ public final class HTMLFilter
// starting tags
m = P_START_TAG.matcher(s);
if (m.find())
{
if (m.find()) {
final String name = m.group(1).toLowerCase();
final String body = m.group(2);
String ending = m.group(3);
// debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" );
if (allowed(name))
{
if (allowed(name)) {
final StringBuilder params = new StringBuilder();
final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body);
final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body);
final List<String> paramNames = new ArrayList<>();
final List<String> paramValues = new ArrayList<>();
while (m2.find())
{
while (m2.find()) {
paramNames.add(m2.group(1)); // ([a-z0-9]+)
paramValues.add(m2.group(3)); // (.*?)
}
while (m3.find())
{
while (m3.find()) {
paramNames.add(m3.group(1)); // ([a-z0-9]+)
paramValues.add(m3.group(3)); // ([^\"\\s']+)
}
String paramName, paramValue;
for (int ii = 0; ii < paramNames.size(); ii++)
{
for (int ii = 0; ii < paramNames.size(); ii++) {
paramName = paramNames.get(ii).toLowerCase();
paramValue = paramValues.get(ii);
@ -377,72 +343,55 @@ public final class HTMLFilter
// debug( "paramValue='" + paramValue + "'" );
// debug( "allowed? " + vAllowed.get( name ).contains( paramName ) );
if (allowedAttribute(name, paramName))
{
if (inArray(paramName, vProtocolAtts))
{
if (allowedAttribute(name, paramName)) {
if (inArray(paramName, vProtocolAtts)) {
paramValue = processParamProtocol(paramValue);
}
params.append(' ').append(paramName).append("=\\\"").append(paramValue).append("\\\"");
}
}
if (inArray(name, vSelfClosingTags))
{
if (inArray(name, vSelfClosingTags)) {
ending = " /";
}
if (inArray(name, vNeedClosingTags))
{
if (inArray(name, vNeedClosingTags)) {
ending = "";
}
if (ending == null || ending.length() < 1)
{
if (vTagCounts.containsKey(name))
{
if (ending == null || ending.length() < 1) {
if (vTagCounts.containsKey(name)) {
vTagCounts.put(name, vTagCounts.get(name) + 1);
}
else
{
} else {
vTagCounts.put(name, 1);
}
}
else
{
} else {
ending = " /";
}
return "<" + name + params + ending + ">";
}
else
{
} else {
return "";
}
}
// comments
m = P_COMMENT.matcher(s);
if (!stripComment && m.find())
{
if (!stripComment && m.find()) {
return "<" + m.group() + ">";
}
return "";
}
private String processParamProtocol(String s)
{
private String processParamProtocol(String s) {
s = decodeEntities(s);
final Matcher m = P_PROTOCOL.matcher(s);
if (m.find())
{
if (m.find()) {
final String protocol = m.group(1);
if (!inArray(protocol, vAllowedProtocols))
{
if (!inArray(protocol, vAllowedProtocols)) {
// bad protocol, turn into local anchor link instead
s = "#" + s.substring(protocol.length() + 1);
if (s.startsWith("#//"))
{
if (s.startsWith("#//")) {
s = "#" + s.substring(3);
}
}
@ -451,13 +400,11 @@ public final class HTMLFilter
return s;
}
private String decodeEntities(String s)
{
private String decodeEntities(String s) {
StringBuffer buf = new StringBuffer();
Matcher m = P_ENTITY.matcher(s);
while (m.find())
{
while (m.find()) {
final String match = m.group(1);
final int decimal = Integer.decode(match).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
@ -467,8 +414,7 @@ public final class HTMLFilter
buf = new StringBuffer();
m = P_ENTITY_UNICODE.matcher(s);
while (m.find())
{
while (m.find()) {
final String match = m.group(1);
final int decimal = Integer.valueOf(match, 16).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
@ -478,8 +424,7 @@ public final class HTMLFilter
buf = new StringBuffer();
m = P_ENCODE.matcher(s);
while (m.find())
{
while (m.find()) {
final String match = m.group(1);
final int decimal = Integer.valueOf(match, 16).intValue();
m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
@ -491,14 +436,12 @@ public final class HTMLFilter
return s;
}
private String validateEntities(final String s)
{
private String validateEntities(final String s) {
StringBuffer buf = new StringBuffer();
// validate entities throughout the string
Matcher m = P_VALID_ENTITIES.matcher(s);
while (m.find())
{
while (m.find()) {
final String one = m.group(1); // ([^&;]*)
final String two = m.group(2); // (?=(;|&|$))
m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two)));
@ -508,14 +451,11 @@ public final class HTMLFilter
return encodeQuotes(buf.toString());
}
private String encodeQuotes(final String s)
{
if (encodeQuotes)
{
private String encodeQuotes(final String s) {
if (encodeQuotes) {
StringBuffer buf = new StringBuffer();
Matcher m = P_VALID_QUOTES.matcher(s);
while (m.find())
{
while (m.find()) {
final String one = m.group(1); // (>|^)
final String two = m.group(2); // ([^<]+?)
final String three = m.group(3); // (<|$)
@ -524,43 +464,34 @@ public final class HTMLFilter
}
m.appendTail(buf);
return buf.toString();
}
else
{
} else {
return s;
}
}
private String checkEntity(final String preamble, final String term)
{
private String checkEntity(final String preamble, final String term) {
return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&amp;" + preamble;
}
private boolean isValidEntity(final String entity)
{
private boolean isValidEntity(final String entity) {
return inArray(entity, vAllowedEntities);
}
private static boolean inArray(final String s, final String[] array)
{
for (String item : array)
{
if (item != null && item.equals(s))
{
private static boolean inArray(final String s, final String[] array) {
for (String item : array) {
if (item != null && item.equals(s)) {
return true;
}
}
return false;
}
private boolean allowed(final String name)
{
private boolean allowed(final String name) {
return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed);
}
private boolean allowedAttribute(final String name, final String paramName)
{
private boolean allowedAttribute(final String name, final String paramName) {
return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName));
}
}

View File

@ -12,8 +12,7 @@ import java.net.UnknownHostException;
*
* @author muyu
*/
public class IpUtils
{
public class IpUtils {
public final static String REGX_0_255 = "(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
// 匹配 ip
public final static String REGX_IP = "((" + REGX_0_255 + "\\.){3}" + REGX_0_255 + ")";
@ -26,8 +25,7 @@ public class IpUtils
*
* @return IP
*/
public static String getIpAddr()
{
public static String getIpAddr() {
return getIpAddr(ServletUtils.getRequest());
}
@ -37,32 +35,25 @@ public class IpUtils
* @param request
* @return IP
*/
public static String getIpAddr(HttpServletRequest request)
{
if (request == null)
{
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))
{
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(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))
{
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))
{
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
@ -75,8 +66,7 @@ public class IpUtils
* @param ip IP
* @return
*/
public static boolean internalIp(String ip)
{
public static boolean internalIp(String ip) {
byte[] addr = textToNumericFormatV4(ip);
return internalIp(addr) || "127.0.0.1".equals(ip);
}
@ -87,10 +77,8 @@ public class IpUtils
* @param addr byte
* @return
*/
private static boolean internalIp(byte[] addr)
{
if (StringUtils.isNull(addr) || addr.length < 2)
{
private static boolean internalIp(byte[] addr) {
if (StringUtils.isNull(addr) || addr.length < 2) {
return true;
}
final byte b0 = addr[0];
@ -104,18 +92,15 @@ public class IpUtils
// 192.168.x.x/16
final byte SECTION_5 = (byte) 0xC0;
final byte SECTION_6 = (byte) 0xA8;
switch (b0)
{
switch (b0) {
case SECTION_1:
return true;
case SECTION_2:
if (b1 >= SECTION_3 && b1 <= SECTION_4)
{
if (b1 >= SECTION_3 && b1 <= SECTION_4) {
return true;
}
case SECTION_5:
switch (b1)
{
switch (b1) {
case SECTION_6:
return true;
}
@ -130,25 +115,20 @@ public class IpUtils
* @param text IPv4
* @return byte
*/
public static byte[] textToNumericFormatV4(String text)
{
if (text.length() == 0)
{
public static byte[] textToNumericFormatV4(String text) {
if (text.length() == 0) {
return null;
}
byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1);
try
{
try {
long l;
int i;
switch (elements.length)
{
switch (elements.length) {
case 1:
l = Long.parseLong(elements[0]);
if ((l < 0L) || (l > 4294967295L))
{
if ((l < 0L) || (l > 4294967295L)) {
return null;
}
bytes[0] = (byte) (int) (l >> 24 & 0xFF);
@ -158,14 +138,12 @@ public class IpUtils
break;
case 2:
l = Integer.parseInt(elements[0]);
if ((l < 0L) || (l > 255L))
{
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[0] = (byte) (int) (l & 0xFF);
l = Integer.parseInt(elements[1]);
if ((l < 0L) || (l > 16777215L))
{
if ((l < 0L) || (l > 16777215L)) {
return null;
}
bytes[1] = (byte) (int) (l >> 16 & 0xFF);
@ -173,29 +151,24 @@ public class IpUtils
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 3:
for (i = 0; i < 2; ++i)
{
for (i = 0; i < 2; ++i) {
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L))
{
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
}
l = Integer.parseInt(elements[2]);
if ((l < 0L) || (l > 65535L))
{
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)
{
for (i = 0; i < 4; ++i) {
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L))
{
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
@ -204,9 +177,7 @@ public class IpUtils
default:
return null;
}
}
catch (NumberFormatException e)
{
} catch (NumberFormatException e) {
return null;
}
return bytes;
@ -217,14 +188,10 @@ public class IpUtils
*
* @return IP
*/
public static String getHostIp()
{
try
{
public static String getHostIp() {
try {
return InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException e)
{
} catch (UnknownHostException e) {
}
return "127.0.0.1";
}
@ -234,14 +201,10 @@ public class IpUtils
*
* @return
*/
public static String getHostName()
{
try
{
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e)
{
} catch (UnknownHostException e) {
}
return "未知";
}
@ -252,16 +215,12 @@ public class IpUtils
* @param ip IP
* @return unknown IP
*/
public static String getMultistageReverseProxyIp(String ip)
{
public static String getMultistageReverseProxyIp(String ip) {
// 多级反向代理检测
if (ip != null && ip.indexOf(",") > 0)
{
if (ip != null && ip.indexOf(",") > 0) {
final String[] ips = ip.trim().split(",");
for (String subIp : ips)
{
if (false == isUnknown(subIp))
{
for (String subIp : ips) {
if (false == isUnknown(subIp)) {
ip = subIp;
break;
}
@ -276,39 +235,33 @@ public class IpUtils
* @param checkString
* @return
*/
public static boolean isUnknown(String checkString)
{
public static boolean isUnknown(String checkString) {
return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
}
/**
* IP
*/
public static boolean isIP(String ip)
{
public static boolean isIP(String ip) {
return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP);
}
/**
* IP *
*/
public static boolean isIpWildCard(String ip)
{
public static boolean isIpWildCard(String ip) {
return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP_WILDCARD);
}
/**
* ip
*/
public static boolean ipIsInWildCardNoCheck(String ipWildCard, String ip)
{
public static boolean ipIsInWildCardNoCheck(String ipWildCard, String ip) {
String[] s1 = ipWildCard.split("\\.");
String[] s2 = ip.split("\\.");
boolean isMatchedSeg = true;
for (int i = 0; i < s1.length && !s1[i].equals("*"); i++)
{
if (!s1[i].equals(s2[i]))
{
for (int i = 0; i < s1.length && !s1[i].equals("*"); i++) {
if (!s1[i].equals(s2[i])) {
isMatchedSeg = false;
break;
}
@ -319,29 +272,25 @@ public class IpUtils
/**
* :10.10.10.1-10.10.10.99ip
*/
public static boolean isIPSegment(String ipSeg)
{
public static boolean isIPSegment(String ipSeg) {
return StringUtils.isNotBlank(ipSeg) && ipSeg.matches(REGX_IP_SEG);
}
/**
* ip
*/
public static boolean ipIsInNetNoCheck(String iparea, String ip)
{
public static boolean ipIsInNetNoCheck(String iparea, String ip) {
int idx = iparea.indexOf('-');
String[] sips = iparea.substring(0, idx).split("\\.");
String[] sipe = iparea.substring(idx + 1).split("\\.");
String[] sipt = ip.split("\\.");
long ips = 0L, ipe = 0L, ipt = 0L;
for (int i = 0; i < 4; ++i)
{
for (int i = 0; i < 4; ++i) {
ips = ips << 8 | Integer.parseInt(sips[i]);
ipe = ipe << 8 | Integer.parseInt(sipe[i]);
ipt = ipt << 8 | Integer.parseInt(sipt[i]);
}
if (ips > ipe)
{
if (ips > ipe) {
long t = ips;
ips = ipe;
ipe = t;
@ -353,28 +302,20 @@ public class IpUtils
* ip
*
* @param filter IP,'*',:`10.10.10.1-10.10.10.99`
* @param ip IP
* @param ip IP
* @return boolean
*/
public static boolean isMatchedIp(String filter, String ip)
{
if (StringUtils.isEmpty(filter) || StringUtils.isEmpty(ip))
{
public static boolean isMatchedIp(String filter, String ip) {
if (StringUtils.isEmpty(filter) || StringUtils.isEmpty(ip)) {
return false;
}
String[] ips = filter.split(";");
for (String iStr : ips)
{
if (isIP(iStr) && iStr.equals(ip))
{
for (String iStr : ips) {
if (isIP(iStr) && iStr.equals(ip)) {
return true;
}
else if (isIpWildCard(iStr) && ipIsInWildCardNoCheck(iStr, ip))
{
} else if (isIpWildCard(iStr) && ipIsInWildCardNoCheck(iStr, ip)) {
return true;
}
else if (isIPSegment(iStr) && ipIsInNetNoCheck(iStr, ip))
{
} else if (isIPSegment(iStr) && ipIsInNetNoCheck(iStr, ip)) {
return true;
}
}

View File

@ -8,16 +8,14 @@ import org.apache.poi.ss.usermodel.Workbook;
*
* @author muyu
*/
public interface ExcelHandlerAdapter
{
public interface ExcelHandlerAdapter {
/**
*
*
* @param value
* @param args excelargs
* @param cell
* @param wb 簿
*
* @param args excelargs
* @param cell
* @param wb 簿
* @return
*/
Object format(Object value, String[] args, Cell cell, Workbook wb);

View File

@ -17,8 +17,7 @@ import java.util.Date;
* @author muyu
*/
@SuppressWarnings("rawtypes")
public class ReflectUtils
{
public class ReflectUtils {
private static final String SETTER_PREFIX = "set";
private static final String GETTER_PREFIX = "get";
@ -32,13 +31,11 @@ public class ReflectUtils
* ..
*/
@SuppressWarnings("unchecked")
public static <E> E invokeGetter(Object obj, String propertyName)
{
public static <E> E invokeGetter(Object obj, String propertyName) {
Object object = obj;
for (String name : StringUtils.split(propertyName, "."))
{
for (String name : StringUtils.split(propertyName, ".")) {
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
}
return (E) object;
}
@ -47,21 +44,16 @@ public class ReflectUtils
* Setter,
* ..
*/
public static <E> void invokeSetter(Object obj, String propertyName, E value)
{
public static <E> void invokeSetter(Object obj, String propertyName, E value) {
Object object = obj;
String[] names = StringUtils.split(propertyName, ".");
for (int i = 0; i < names.length; i++)
{
if (i < names.length - 1)
{
for (int i = 0; i < names.length; i++) {
if (i < names.length - 1) {
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
}
else
{
object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
} else {
String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
invokeMethodByName(object, setterMethodName, new Object[] { value });
invokeMethodByName(object, setterMethodName, new Object[]{value});
}
}
}
@ -70,21 +62,16 @@ public class ReflectUtils
* , private/protected, getter.
*/
@SuppressWarnings("unchecked")
public static <E> E getFieldValue(final Object obj, final String fieldName)
{
public static <E> E getFieldValue(final Object obj, final String fieldName) {
Field field = getAccessibleField(obj, fieldName);
if (field == null)
{
if (field == null) {
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
return null;
}
E result = null;
try
{
try {
result = (E) field.get(obj);
}
catch (IllegalAccessException e)
{
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常{}", e.getMessage());
}
return result;
@ -93,21 +80,16 @@ public class ReflectUtils
/**
* , private/protected, setter.
*/
public static <E> void setFieldValue(final Object obj, final String fieldName, final E value)
{
public static <E> void setFieldValue(final Object obj, final String fieldName, final E value) {
Field field = getAccessibleField(obj, fieldName);
if (field == null)
{
if (field == null) {
// throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
return;
}
try
{
try {
field.set(obj, value);
}
catch (IllegalAccessException e)
{
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常: {}", e.getMessage());
}
}
@ -119,24 +101,18 @@ public class ReflectUtils
*/
@SuppressWarnings("unchecked")
public static <E> E invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
final Object[] args)
{
if (obj == null || methodName == null)
{
final Object[] args) {
if (obj == null || methodName == null) {
return null;
}
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null)
{
if (method == null) {
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
return null;
}
try
{
try {
return (E) method.invoke(obj, args);
}
catch (Exception e)
{
} catch (Exception e) {
String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
throw convertReflectionExceptionToUnchecked(msg, e);
}
@ -148,68 +124,44 @@ public class ReflectUtils
*
*/
@SuppressWarnings("unchecked")
public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args)
{
public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
Method method = getAccessibleMethodByName(obj, methodName, args.length);
if (method == null)
{
if (method == null) {
// 如果为空不报错,直接返回空。
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
return null;
}
try
{
try {
// 类型转换(将参数数据类型转换为目标方法参数类型)
Class<?>[] cs = method.getParameterTypes();
for (int i = 0; i < cs.length; i++)
{
if (args[i] != null && !args[i].getClass().equals(cs[i]))
{
if (cs[i] == String.class)
{
for (int i = 0; i < cs.length; i++) {
if (args[i] != null && !args[i].getClass().equals(cs[i])) {
if (cs[i] == String.class) {
args[i] = Convert.toStr(args[i]);
if (StringUtils.endsWith((String) args[i], ".0"))
{
if (StringUtils.endsWith((String) args[i], ".0")) {
args[i] = StringUtils.substringBefore((String) args[i], ".0");
}
}
else if (cs[i] == Integer.class)
{
} else if (cs[i] == Integer.class) {
args[i] = Convert.toInt(args[i]);
}
else if (cs[i] == Long.class)
{
} else if (cs[i] == Long.class) {
args[i] = Convert.toLong(args[i]);
}
else if (cs[i] == Double.class)
{
} else if (cs[i] == Double.class) {
args[i] = Convert.toDouble(args[i]);
}
else if (cs[i] == Float.class)
{
} else if (cs[i] == Float.class) {
args[i] = Convert.toFloat(args[i]);
}
else if (cs[i] == Date.class)
{
if (args[i] instanceof String)
{
} else if (cs[i] == Date.class) {
if (args[i] instanceof String) {
args[i] = DateUtils.parseDate(args[i]);
}
else
{
} else {
args[i] = DateUtil.getJavaDate((Double) args[i]);
}
}
else if (cs[i] == boolean.class || cs[i] == Boolean.class)
{
} else if (cs[i] == boolean.class || cs[i] == Boolean.class) {
args[i] = Convert.toBool(args[i]);
}
}
}
return (E) method.invoke(obj, args);
}
catch (Exception e)
{
} catch (Exception e) {
String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
throw convertReflectionExceptionToUnchecked(msg, e);
}
@ -219,24 +171,18 @@ public class ReflectUtils
* , DeclaredField, 访.
* Object, null.
*/
public static Field getAccessibleField(final Object obj, final String fieldName)
{
public static Field getAccessibleField(final Object obj, final String fieldName) {
// 为空不报错。直接返回 null
if (obj == null)
{
if (obj == null) {
return null;
}
Validate.notBlank(fieldName, "fieldName can't be blank");
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass())
{
try
{
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);
makeAccessible(field);
return field;
}
catch (NoSuchFieldException e)
{
} catch (NoSuchFieldException e) {
continue;
}
}
@ -250,24 +196,18 @@ public class ReflectUtils
* . 使Method,Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethod(final Object obj, final String methodName,
final Class<?>... parameterTypes)
{
final Class<?>... parameterTypes) {
// 为空不报错。直接返回 null
if (obj == null)
{
if (obj == null) {
return null;
}
Validate.notBlank(methodName, "methodName can't be blank");
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass())
{
try
{
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
try {
Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
makeAccessible(method);
return method;
}
catch (NoSuchMethodException e)
{
} catch (NoSuchMethodException e) {
continue;
}
}
@ -280,21 +220,16 @@ public class ReflectUtils
*
* . 使Method,Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum)
{
public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum) {
// 为空不报错。直接返回 null
if (obj == null)
{
if (obj == null) {
return null;
}
Validate.notBlank(methodName, "methodName can't be blank");
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass())
{
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
Method[] methods = searchType.getDeclaredMethods();
for (Method method : methods)
{
if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum)
{
for (Method method : methods) {
if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum) {
makeAccessible(method);
return method;
}
@ -306,11 +241,9 @@ public class ReflectUtils
/**
* private/protectedpublicJDKSecurityManager
*/
public static void makeAccessible(Method method)
{
public static void makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible())
{
&& !method.isAccessible()) {
method.setAccessible(true);
}
}
@ -318,11 +251,9 @@ public class ReflectUtils
/**
* private/protectedpublicJDKSecurityManager
*/
public static void makeAccessible(Field field)
{
public static void makeAccessible(Field field) {
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
|| Modifier.isFinal(field.getModifiers())) && !field.isAccessible())
{
|| Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
}
@ -332,8 +263,7 @@ public class ReflectUtils
* , Object.class.
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> getClassGenricType(final Class clazz)
{
public static <T> Class<T> getClassGenricType(final Class clazz) {
return getClassGenricType(clazz, 0);
}
@ -341,26 +271,22 @@ public class ReflectUtils
* , Class.
* , Object.class.
*/
public static Class getClassGenricType(final Class clazz, final int index)
{
public static Class getClassGenricType(final Class clazz, final int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType))
{
if (!(genType instanceof ParameterizedType)) {
logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0)
{
if (index >= params.length || index < 0) {
logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class))
{
if (!(params[index] instanceof Class)) {
logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
}
@ -368,18 +294,14 @@ public class ReflectUtils
return (Class) params[index];
}
public static Class<?> getUserClass(Object instance)
{
if (instance == null)
{
public static Class<?> getUserClass(Object instance) {
if (instance == null) {
throw new RuntimeException("Instance must not be null");
}
Class clazz = instance.getClass();
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR))
{
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && !Object.class.equals(superClass))
{
if (superClass != null && !Object.class.equals(superClass)) {
return superClass;
}
}
@ -390,15 +312,11 @@ public class ReflectUtils
/**
* checked exceptionunchecked exception.
*/
public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e)
{
public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e) {
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|| e instanceof NoSuchMethodException)
{
|| e instanceof NoSuchMethodException) {
return new IllegalArgumentException(msg, e);
}
else if (e instanceof InvocationTargetException)
{
} else if (e instanceof InvocationTargetException) {
return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException());
}
return new RuntimeException(msg, e);

View File

@ -5,72 +5,60 @@ package com.muyu.common.core.utils.sign;
*
* @author muyu
*/
public final class Base64
{
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static final private byte[] base64Alphabet = new byte[BASELENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
public final class Base64 {
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static final private byte[] base64Alphabet = new byte[BASELENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static
{
for (int i = 0; i < BASELENGTH; ++i)
{
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--)
{
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--)
{
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--)
{
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++)
{
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++)
{
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++)
{
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect)
{
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect)
{
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect)
{
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
@ -80,16 +68,13 @@ public final class Base64
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData)
{
if (binaryData == null)
{
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0)
{
if (lengthDataBits == 0) {
return "";
}
@ -105,8 +90,7 @@ public final class Base64
int encodedIndex = 0;
int dataIndex = 0;
for (int i = 0; i < numberTriplets; i++)
{
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
@ -125,8 +109,7 @@ public final class Base64
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT)
{
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
@ -134,9 +117,7 @@ public final class Base64
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
}
else if (fewerThan24bits == SIXTEENBIT)
{
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
@ -159,10 +140,8 @@ public final class Base64
* @param encoded string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded)
{
if (encoded == null)
{
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
}
@ -170,15 +149,13 @@ public final class Base64
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0)
{
if (len % FOURBYTE != 0) {
return null;// should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0)
{
if (numberQuadruple == 0) {
return new byte[0];
}
@ -191,12 +168,10 @@ public final class Base64
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++)
{
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++])))
{
|| !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))) {
return null;
} // if found "no data" just return null
@ -210,8 +185,7 @@ public final class Base64
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++])))
{
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
return null;// if found "no data" just return null
}
@ -220,10 +194,8 @@ public final class Base64
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4)))
{// Check if they are PAD characters
if (isPad(d3) && isPad(d4))
{
if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null;
@ -232,9 +204,7 @@ public final class Base64
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
}
else if (!isPad(d3) && isPad(d4))
{
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
@ -245,14 +215,10 @@ public final class Base64
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
}
else
{
} else {
return null;
}
}
else
{ // No PAD e.g 3cQl
} else { // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
@ -269,20 +235,16 @@ public final class Base64
* @param data the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data)
{
if (data == null)
{
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++)
{
if (!isWhiteSpace(data[i]))
{
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}

View File

@ -8,8 +8,7 @@ import com.muyu.common.core.utils.StringUtils;
*
* @author muyu
*/
public class SqlUtil
{
public class SqlUtil {
/**
* sql
*/
@ -28,14 +27,11 @@ public class SqlUtil
/**
*
*/
public static String escapeOrderBySql(String value)
{
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value))
{
public static String escapeOrderBySql(String value) {
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
throw new UtilException("参数不符合规范,不能进行查询");
}
if (StringUtils.length(value) > ORDER_BY_MAX_LENGTH)
{
if (StringUtils.length(value) > ORDER_BY_MAX_LENGTH) {
throw new UtilException("参数已超过最大限制,不能进行查询");
}
return value;
@ -44,25 +40,20 @@ public class SqlUtil
/**
* order by
*/
public static boolean isValidOrderBySql(String value)
{
public static boolean isValidOrderBySql(String value) {
return value.matches(SQL_PATTERN);
}
/**
* SQL
*/
public static void filterKeyword(String value)
{
if (StringUtils.isEmpty(value))
{
public static void filterKeyword(String value) {
if (StringUtils.isEmpty(value)) {
return;
}
String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|");
for (String sqlKeyword : sqlKeywords)
{
if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1)
{
for (String sqlKeyword : sqlKeywords) {
if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1) {
throw new UtilException("参数存在SQL注入风险");
}
}

View File

@ -5,15 +5,13 @@ package com.muyu.common.core.utils.uuid;
*
* @author muyu
*/
public class IdUtils
{
public class IdUtils {
/**
* UUID
*
* @return UUID
*/
public static String randomUUID()
{
public static String randomUUID() {
return UUID.randomUUID().toString();
}
@ -22,8 +20,7 @@ public class IdUtils
*
* @return UUID线
*/
public static String simpleUUID()
{
public static String simpleUUID() {
return UUID.randomUUID().toString(true);
}
@ -32,8 +29,7 @@ public class IdUtils
*
* @return UUID
*/
public static String fastUUID()
{
public static String fastUUID() {
return UUID.fastUUID().toString();
}
@ -42,10 +38,10 @@ public class IdUtils
*
* @return UUID线
*/
public static String fastSimpleUUID()
{
public static String fastSimpleUUID() {
return UUID.fastUUID().toString(true);
}
public static String generateShortUUID() {
String uuid = UUID.fastUUID().toString(true);
// 截取前 14 位作为新的 UUID

View File

@ -8,8 +8,7 @@ import java.util.concurrent.atomic.AtomicInteger;
/**
* @author muyu
*/
public class Seq
{
public class Seq {
// 通用序列类型
public static final String commSeqType = "COMMON";
@ -30,8 +29,7 @@ public class Seq
*
* @return
*/
public static String getId()
{
public static String getId() {
return getId(commSeqType);
}
@ -40,11 +38,9 @@ public class Seq
*
* @return
*/
public static String getId(String type)
{
public static String getId(String type) {
AtomicInteger atomicInt = commSeq;
if (uploadSeqType.equals(type))
{
if (uploadSeqType.equals(type)) {
atomicInt = uploadSeq;
}
return getId(atomicInt, 3);
@ -54,11 +50,10 @@ public class Seq
* yyMMddHHmmss + + length
*
* @param atomicInt
* @param length
* @param length
* @return
*/
public static String getId(AtomicInteger atomicInt, int length)
{
public static String getId(AtomicInteger atomicInt, int length) {
String result = DateUtils.dateTimeNow();
result += machineCode;
result += getSeq(atomicInt, length);
@ -70,15 +65,13 @@ public class Seq
*
* @return
*/
private synchronized static String getSeq(AtomicInteger atomicInt, int length)
{
private synchronized static String getSeq(AtomicInteger atomicInt, int length) {
// 先取值再+1
int value = atomicInt.getAndIncrement();
// 如果更新后值>=10 的 (length)幂次方则重置为1
int maxSeq = (int) Math.pow(10, length);
if (atomicInt.get() >= maxSeq)
{
if (atomicInt.get() >= maxSeq) {
atomicInt.set(1);
}
// 转字符串用0左补齐

View File

@ -13,23 +13,24 @@ import java.util.concurrent.ThreadLocalRandom;
*
* @author muyu
*/
public final class UUID implements java.io.Serializable, Comparable<UUID>
{
public final class UUID implements java.io.Serializable, Comparable<UUID> {
private static final long serialVersionUID = -1185015143654744140L;
/**
* SecureRandom
*
*/
private static class Holder
{
private static class Holder {
static final SecureRandom numberGenerator = getSecureRandom();
}
/** 此UUID的最高64有效位 */
/**
* UUID64
*/
private final long mostSigBits;
/** 此UUID的最低64有效位 */
/**
* UUID64
*/
private final long leastSigBits;
/**
@ -37,17 +38,14 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
*
* @param data
*/
private UUID(byte[] data)
{
private UUID(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++)
{
for (int i = 0; i < 8; i++) {
msb = (msb << 8) | (data[i] & 0xff);
}
for (int i = 8; i < 16; i++)
{
for (int i = 8; i < 16; i++) {
lsb = (lsb << 8) | (data[i] & 0xff);
}
this.mostSigBits = msb;
@ -57,11 +55,10 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
/**
* 使 UUID
*
* @param mostSigBits {@code UUID} 64
* @param mostSigBits {@code UUID} 64
* @param leastSigBits {@code UUID} 64
*/
public UUID(long mostSigBits, long leastSigBits)
{
public UUID(long mostSigBits, long leastSigBits) {
this.mostSigBits = mostSigBits;
this.leastSigBits = leastSigBits;
}
@ -71,8 +68,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
*
* @return {@code UUID}
*/
public static UUID fastUUID()
{
public static UUID fastUUID() {
return randomUUID(false);
}
@ -81,8 +77,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
*
* @return {@code UUID}
*/
public static UUID randomUUID()
{
public static UUID randomUUID() {
return randomUUID(true);
}
@ -92,8 +87,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* @param isSecure 使{@link SecureRandom}
* @return {@code UUID}
*/
public static UUID randomUUID(boolean isSecure)
{
public static UUID randomUUID(boolean isSecure) {
final Random ng = isSecure ? Holder.numberGenerator : getRandom();
byte[] randomBytes = new byte[16];
@ -109,18 +103,13 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* 3UUID
*
* @param name UUID
*
* @return {@code UUID}
*/
public static UUID nameUUIDFromBytes(byte[] name)
{
public static UUID nameUUIDFromBytes(byte[] name) {
MessageDigest md;
try
{
try {
md = MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException nsae)
{
} catch (NoSuchAlgorithmException nsae) {
throw new InternalError("MD5 not supported");
}
byte[] md5Bytes = md.digest(name);
@ -137,17 +126,13 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* @param name {@code UUID}
* @return {@code UUID}
* @throws IllegalArgumentException name {@link #toString}
*
*/
public static UUID fromString(String name)
{
public static UUID fromString(String name) {
String[] components = name.split("-");
if (components.length != 5)
{
if (components.length != 5) {
throw new IllegalArgumentException("Invalid UUID string: " + name);
}
for (int i = 0; i < 5; i++)
{
for (int i = 0; i < 5; i++) {
components[i] = "0x" + components[i];
}
@ -169,8 +154,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
*
* @return UUID 128 64
*/
public long getLeastSignificantBits()
{
public long getLeastSignificantBits() {
return leastSigBits;
}
@ -179,8 +163,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
*
* @return UUID 128 64
*/
public long getMostSignificantBits()
{
public long getMostSignificantBits() {
return mostSigBits;
}
@ -197,8 +180,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
*
* @return {@code UUID}
*/
public int version()
{
public int version() {
// Version is bits masked by 0x000000000000F000 in MS long
return (int) ((mostSigBits >> 12) & 0x0f);
}
@ -216,8 +198,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
*
* @return {@code UUID}
*/
public int variant()
{
public int variant() {
// This field is composed of a varying number of bits.
// 0 - - Reserved for NCS backward compatibility
// 1 0 - The IETF aka Leach-Salz variant (used by this class)
@ -239,8 +220,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
*
* @throws UnsupportedOperationException {@code UUID} version 1 UUID
*/
public long timestamp() throws UnsupportedOperationException
{
public long timestamp() throws UnsupportedOperationException {
checkTimeBase();
return (mostSigBits & 0x0FFFL) << 48//
| ((mostSigBits >> 16) & 0x0FFFFL) << 32//
@ -257,11 +237,9 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* UnsupportedOperationException
*
* @return {@code UUID}
*
* @throws UnsupportedOperationException UUID version 1
*/
public int clockSequence() throws UnsupportedOperationException
{
public int clockSequence() throws UnsupportedOperationException {
checkTimeBase();
return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48);
}
@ -276,11 +254,9 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* UUID UUID UnsupportedOperationException
*
* @return {@code UUID}
*
* @throws UnsupportedOperationException UUID version 1
*/
public long node() throws UnsupportedOperationException
{
public long node() throws UnsupportedOperationException {
checkTimeBase();
return leastSigBits & 0x0000FFFFFFFFFFFFL;
}
@ -310,8 +286,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* @see #toString(boolean)
*/
@Override
public String toString()
{
public String toString() {
return toString(false);
}
@ -339,31 +314,26 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* @param isSimple '-'UUID
* @return {@code UUID}
*/
public String toString(boolean isSimple)
{
public String toString(boolean isSimple) {
final StringBuilder builder = new StringBuilder(isSimple ? 32 : 36);
// time_low
builder.append(digits(mostSigBits >> 32, 8));
if (false == isSimple)
{
if (false == isSimple) {
builder.append('-');
}
// time_mid
builder.append(digits(mostSigBits >> 16, 4));
if (false == isSimple)
{
if (false == isSimple) {
builder.append('-');
}
// time_high_and_version
builder.append(digits(mostSigBits, 4));
if (false == isSimple)
{
if (false == isSimple) {
builder.append('-');
}
// variant_and_sequence
builder.append(digits(leastSigBits >> 48, 4));
if (false == isSimple)
{
if (false == isSimple) {
builder.append('-');
}
// node
@ -378,8 +348,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* @return UUID
*/
@Override
public int hashCode()
{
public int hashCode() {
long hilo = mostSigBits ^ leastSigBits;
return ((int) (hilo >> 32)) ^ (int) hilo;
}
@ -390,14 +359,11 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* {@code null} UUID UUID varriant {@code true}
*
* @param obj
*
* @return {@code true} {@code false}
*/
@Override
public boolean equals(Object obj)
{
if ((null == obj) || (obj.getClass() != UUID.class))
{
public boolean equals(Object obj) {
if ((null == obj) || (obj.getClass() != UUID.class)) {
return false;
}
UUID id = (UUID) obj;
@ -413,13 +379,10 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
* UUID UUID UUID UUID UUID
*
* @param val UUID UUID
*
* @return UUID val -10 1
*
*/
@Override
public int compareTo(UUID val)
{
public int compareTo(UUID val) {
// The ordering is intentionally set up so that the UUIDs
// can simply be numerically compared as two numbers
return (this.mostSigBits < val.mostSigBits ? -1 : //
@ -431,15 +394,15 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
// -------------------------------------------------------------------------------------------------------------------
// Private method start
/**
* hex
*
* @param val
* @param val
* @param digits
* @return
*/
private static String digits(long val, int digits)
{
private static String digits(long val, int digits) {
long hi = 1L << (digits * 4);
return Long.toHexString(hi | (val & (hi - 1))).substring(1);
}
@ -447,10 +410,8 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
/**
* time-basedUUID
*/
private void checkTimeBase()
{
if (version() != 1)
{
private void checkTimeBase() {
if (version() != 1) {
throw new UnsupportedOperationException("Not a time-based UUID");
}
}
@ -460,14 +421,10 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
*
* @return {@link SecureRandom}
*/
public static SecureRandom getSecureRandom()
{
try
{
public static SecureRandom getSecureRandom() {
try {
return SecureRandom.getInstance("SHA1PRNG");
}
catch (NoSuchAlgorithmException e)
{
} catch (NoSuchAlgorithmException e) {
throw new UtilException(e);
}
}
@ -478,8 +435,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
*
* @return {@link ThreadLocalRandom}
*/
public static ThreadLocalRandom getRandom()
{
public static ThreadLocalRandom getRandom() {
return ThreadLocalRandom.current();
}
}

View File

@ -21,22 +21,18 @@ import java.util.List;
*
* @author coderjacky
*/
public class BaseController
{
public class BaseController {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Date
*/
@InitBinder
public void initBinder(WebDataBinder binder)
{
public void initBinder(WebDataBinder binder) {
// Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
{
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text)
{
public void setAsText(String text) {
setValue(DateUtils.parseDate(text));
}
});
@ -45,25 +41,22 @@ public class BaseController
/**
*
*/
protected void startPage()
{
protected void startPage() {
PageUtils.startPage();
}
/**
* 线
*/
protected void clearPage()
{
protected void clearPage() {
PageUtils.clearPage();
}
/**
*
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Result<TableDataInfo> getDataTable(List<?> list)
{
@SuppressWarnings({"rawtypes", "unchecked"})
protected Result<TableDataInfo> getDataTable(List<?> list) {
TableDataInfo rspData = new TableDataInfo();
rspData.setRows(list);
rspData.setTotal(new PageInfo(list).getTotal());
@ -80,32 +73,28 @@ public class BaseController
/**
* Result.success()
*/
public Result success()
{
public Result success() {
return Result.success();
}
/**
*
*/
public Result success(String message)
{
public Result success(String message) {
return Result.success(message);
}
/**
*
*/
public Result success(Object data)
{
public Result success(Object data) {
return Result.success(data);
}
/**
*
*/
public Result error()
{
public Result error() {
return Result.error();
}
@ -113,8 +102,7 @@ public class BaseController
/**
*
*/
public Result error(String message)
{
public Result error(String message) {
return Result.error(message);
}
@ -124,8 +112,7 @@ public class BaseController
* @param rows
* @return
*/
protected Result toAjax(int rows)
{
protected Result toAjax(int rows) {
return rows > 0 ? Result.success() : Result.error();
}
@ -135,8 +122,7 @@ public class BaseController
* @param result
* @return
*/
protected Result toAjax(boolean result)
{
protected Result toAjax(boolean result) {
return result ? success() : error();
}
}

View File

@ -11,34 +11,37 @@ import java.util.Objects;
*
* @author muyu
*/
public class AjaxResult extends HashMap<String, Object>
{
public class AjaxResult extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
/** 状态码 */
/**
*
*/
public static final String CODE_TAG = "code";
/** 返回内容 */
/**
*
*/
public static final String MSG_TAG = "msg";
/** 数据对象 */
/**
*
*/
public static final String DATA_TAG = "data";
/**
* AjaxResult 使
*/
public AjaxResult()
{
public AjaxResult() {
}
/**
* AjaxResult
*
* @param code
* @param msg
* @param msg
*/
public AjaxResult(int code, String msg)
{
public AjaxResult(int code, String msg) {
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
}
@ -47,15 +50,13 @@ public class AjaxResult extends HashMap<String, Object>
* AjaxResult
*
* @param code
* @param msg
* @param msg
* @param data
*/
public AjaxResult(int code, String msg, Object data)
{
public AjaxResult(int code, String msg, Object data) {
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data))
{
if (StringUtils.isNotNull(data)) {
super.put(DATA_TAG, data);
}
}
@ -65,42 +66,38 @@ public class AjaxResult extends HashMap<String, Object>
*
* @return
*/
public static AjaxResult success()
{
return AjaxResult.success("操作成功");
}
public static AjaxResult success() {
return AjaxResult.success("操作成功");
}
/**
*
*
* @return
*/
public static AjaxResult success(Object data)
{
return AjaxResult.success("操作成功", data);
}
/**
*
*
* @param msg
* @return
*/
public static AjaxResult success(String msg)
{
return AjaxResult.success(msg, null);
public static AjaxResult success(Object data) {
return AjaxResult.success("操作成功", data);
}
/**
*
*
* @param msg
* @return
*/
public static AjaxResult success(String msg) {
return AjaxResult.success(msg, null);
}
/**
*
*
* @param msg
* @param data
* @return
*/
public static AjaxResult success(String msg, Object data)
{
public static AjaxResult success(String msg, Object data) {
return new AjaxResult(HttpStatus.SUCCESS, msg, data);
}
@ -110,44 +107,42 @@ public class AjaxResult extends HashMap<String, Object>
* @param msg
* @return
*/
public static AjaxResult warn(String msg)
{
public static AjaxResult warn(String msg) {
return AjaxResult.warn(msg, null);
}
// /**
// /**
// * 返回警告消息
// *
// * @param msg 返回内容
// * @param data 数据对象
// * @return 警告消息
// */
public static AjaxResult warn(String msg, Object data)
{
public static AjaxResult warn(String msg, Object data) {
return new AjaxResult(HttpStatus.WARN, msg, data);
}
//
//
// /**
// * 返回错误消息
// *
// * @return 错误消息
// */
public static AjaxResult error()
{
public static AjaxResult error() {
return AjaxResult.error("操作失败");
}
// /**
// /**
// * 返回错误消息
// *
// * @param msg 返回内容
// * @return 错误消息
// */
public static AjaxResult error(String msg)
{
public static AjaxResult error(String msg) {
return AjaxResult.error(msg, null);
}
//
//
// /**
// * 返回错误消息
// *
@ -155,50 +150,46 @@ public class AjaxResult extends HashMap<String, Object>
// * @param data 数据对象
// * @return 错误消息
// */
public static AjaxResult error(String msg, Object data)
{
public static AjaxResult error(String msg, Object data) {
return new AjaxResult(HttpStatus.ERROR, msg, data);
}
// /**
// /**
// * 返回错误消息
// *
// * @param code 状态码
// * @param msg 返回内容
// * @return 错误消息
// */
public static AjaxResult error(int code, String msg)
{
public static AjaxResult error(int code, String msg) {
return new AjaxResult(code, msg, null);
}
//
//
// /**
// * 是否为成功消息
// *
// * @return 结果
// */
public boolean isSuccess()
{
public boolean isSuccess() {
return Objects.equals(HttpStatus.SUCCESS, this.get(CODE_TAG));
}
// /**
// /**
// * 是否为警告消息
// *
// * @return 结果
// */
public boolean isWarn()
{
public boolean isWarn() {
return Objects.equals(HttpStatus.WARN, this.get(CODE_TAG));
}
// /**
// /**
// * 是否为错误消息
// *
// * @return 结果
// */
public boolean isError()
{
public boolean isError() {
return Objects.equals(HttpStatus.ERROR, this.get(CODE_TAG));
}
@ -210,8 +201,7 @@ public class AjaxResult extends HashMap<String, Object>
* @return
*/
@Override
public AjaxResult put(String key, Object value)
{
public AjaxResult put(String key, Object value) {
super.put(key, value);
return this;
}

View File

@ -14,106 +14,104 @@ import java.util.Map;
*
* @author muyu
*/
public class BaseEntity implements Serializable
{
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/** 搜索值 */
/**
*
*/
@JsonIgnore
private String searchValue;
/** 创建者 */
/**
*
*/
private String createBy;
/** 创建时间 */
/**
*
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/** 更新者 */
/**
*
*/
private String updateBy;
/** 更新时间 */
/**
*
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/** 备注 */
/**
*
*/
private String remark;
/** 请求参数 */
/**
*
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Map<String, Object> params;
public String getSearchValue()
{
public String getSearchValue() {
return searchValue;
}
public void setSearchValue(String searchValue)
{
public void setSearchValue(String searchValue) {
this.searchValue = searchValue;
}
public String getCreateBy()
{
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy)
{
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime()
{
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime)
{
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateBy()
{
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy)
{
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime()
{
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime)
{
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getRemark()
{
public String getRemark() {
return remark;
}
public void setRemark(String remark)
{
public void setRemark(String remark) {
this.remark = remark;
}
public Map<String, Object> getParams()
{
if (params == null)
{
public Map<String, Object> getParams() {
if (params == null) {
params = new HashMap<>();
}
return params;
}
public void setParams(Map<String, Object> params)
{
public void setParams(Map<String, Object> params) {
this.params = params;
}
}

View File

@ -8,75 +8,75 @@ import java.util.List;
*
* @author muyu
*/
public class TreeEntity extends BaseEntity
{
public class TreeEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 父菜单名称 */
/**
*
*/
private String parentName;
/** 父菜单ID */
/**
* ID
*/
private Long parentId;
/** 显示顺序 */
/**
*
*/
private Integer orderNum;
/** 祖级列表 */
/**
*
*/
private String ancestors;
/** 子部门 */
/**
*
*/
private List<?> children = new ArrayList<>();
public void setChildren(List<?> children) {
this.children = children;
}
public List<?> getChildren()
{
public List<?> getChildren() {
return children;
}
public String getParentName()
{
public String getParentName() {
return parentName;
}
public void setParentName(String parentName)
{
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Long getParentId()
{
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId)
{
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public Integer getOrderNum()
{
public Integer getOrderNum() {
return orderNum;
}
public void setOrderNum(Integer orderNum)
{
public void setOrderNum(Integer orderNum) {
this.orderNum = orderNum;
}
public String getAncestors()
{
public String getAncestors() {
return ancestors;
}
public void setAncestors(String ancestors)
{
public void setAncestors(String ancestors) {
this.ancestors = ancestors;
}
}

View File

@ -7,95 +7,87 @@ import com.muyu.common.core.utils.StringUtils;
*
* @author muyu
*/
public class PageDomain
{
/** 当前记录起始索引 */
public class PageDomain {
/**
*
*/
private Integer pageNum;
/** 每页显示记录数 */
/**
*
*/
private Integer pageSize;
/** 排序列 */
/**
*
*/
private String orderByColumn;
/** 排序的方向desc或者asc */
/**
* descasc
*/
private String isAsc = "asc";
/** 分页参数合理化 */
/**
*
*/
private Boolean reasonable = true;
public String getOrderBy()
{
if (StringUtils.isEmpty(orderByColumn))
{
public String getOrderBy() {
if (StringUtils.isEmpty(orderByColumn)) {
return "";
}
return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc;
}
public Integer getPageNum()
{
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum)
{
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize()
{
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize)
{
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public String getOrderByColumn()
{
public String getOrderByColumn() {
return orderByColumn;
}
public void setOrderByColumn(String orderByColumn)
{
public void setOrderByColumn(String orderByColumn) {
this.orderByColumn = orderByColumn;
}
public String getIsAsc()
{
public String getIsAsc() {
return isAsc;
}
public void setIsAsc(String isAsc)
{
if (StringUtils.isNotEmpty(isAsc))
{
public void setIsAsc(String isAsc) {
if (StringUtils.isNotEmpty(isAsc)) {
// 兼容前端排序类型
if ("ascending".equals(isAsc))
{
if ("ascending".equals(isAsc)) {
isAsc = "asc";
}
else if ("descending".equals(isAsc))
{
} else if ("descending".equals(isAsc)) {
isAsc = "desc";
}
this.isAsc = isAsc;
}
}
public Boolean getReasonable()
{
if (StringUtils.isNull(reasonable))
{
public Boolean getReasonable() {
if (StringUtils.isNull(reasonable)) {
return Boolean.TRUE;
}
return reasonable;
}
public void setReasonable(Boolean reasonable)
{
public void setReasonable(Boolean reasonable) {
this.reasonable = reasonable;
}
}

View File

@ -9,14 +9,17 @@ import java.util.List;
*
* @author muyu
*/
public class TableDataInfo implements Serializable
{
public class TableDataInfo implements Serializable {
private static final long serialVersionUID = 1L;
/** 总记录数 */
/**
*
*/
private long total;
/** 列表数据 */
/**
*
*/
private List<?> rows;
@ -40,23 +43,19 @@ public class TableDataInfo implements Serializable
// this.total = total;
// }
public long getTotal()
{
public long getTotal() {
return total;
}
public void setTotal(long total)
{
public void setTotal(long total) {
this.total = total;
}
public List<?> getRows()
{
public List<?> getRows() {
return rows;
}
public void setRows(List<?> rows)
{
public void setRows(List<?> rows) {
this.rows = rows;
}

View File

@ -8,8 +8,7 @@ import com.muyu.common.core.utils.ServletUtils;
*
* @author muyu
*/
public class TableSupport
{
public class TableSupport {
/**
*
*/
@ -38,8 +37,7 @@ public class TableSupport
/**
*
*/
public static PageDomain getPageDomain()
{
public static PageDomain getPageDomain() {
PageDomain pageDomain = new PageDomain();
pageDomain.setPageNum(Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1));
pageDomain.setPageSize(Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10));
@ -49,8 +47,7 @@ public class TableSupport
return pageDomain;
}
public static PageDomain buildPageRequest()
{
public static PageDomain buildPageRequest() {
return getPageDomain();
}
}

View File

@ -13,13 +13,12 @@ import java.lang.annotation.Target;
* @author muyu
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER })
@Constraint(validatedBy = { XssValidator.class })
public @interface Xss
{
@Target(value = {ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Constraint(validatedBy = {XssValidator.class})
public @interface Xss {
String message()
default "不允许任何脚本运行";
default "不允许任何脚本运行";
Class<?>[] groups() default {};

View File

@ -12,22 +12,18 @@ import java.util.regex.Pattern;
*
* @author muyu
*/
public class XssValidator implements ConstraintValidator<Xss, String>
{
public class XssValidator implements ConstraintValidator<Xss, String> {
private static final String HTML_PATTERN = "<(\\S*?)[^>]*>.*?|<.*? />";
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext)
{
if (StringUtils.isBlank(value))
{
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
if (StringUtils.isBlank(value)) {
return true;
}
return !containsHtml(value);
}
public static boolean containsHtml(String value)
{
public static boolean containsHtml(String value) {
Pattern pattern = Pattern.compile(HTML_PATTERN);
Matcher matcher = pattern.matcher(value);
return matcher.matches();

Some files were not shown because too many files have changed in this diff Show More