Commit 9388d2e9 authored by hongguangwu's avatar hongguangwu

core

parent c8835290
package com.yifu.cloud.plus.v1.yifu.common.core.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 异步线程池
* @Author fxj
* @Date 2021-05-20
* @return
**/
@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {
// todo 幂等性如何保证
@Override
public Executor getAsyncExecutor() {
//定义线程池
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
/**
* <!-- 设置allowCoreThreadTimeout=true(默认false)时,核心线程会超时关闭 -->
*/
taskExecutor.setAllowCoreThreadTimeOut(true);
/**
* 核心线程数
* 1)<!-- 线程池维护线程的最少数量,即使没有任务需要执行,也会一直存活 -->
* 2)<!-- 设置allowCoreThreadTimeout=true(默认false)时,核心线程会超时关闭 -->
*/
taskExecutor.setCorePoolSize(2);
/**
* <!-- 允许的空闲时间,当线程空闲时间达到keepAliveTime时,线程会退出,直到线程数量=corePoolSize -->
* <!-- 如果allowCoreThreadTimeout=true,则会直到线程数量=0 -->
*/
taskExecutor.setKeepAliveSeconds(200);
/**
* <!-- 线程池维护线程的最大数量 -->
* <!-- 当线程数>=corePoolSize,且任务队列已满时。线程池会创建新线程来处理任务 -->
* <!-- 当线程数=maxPoolSize,且任务队列已满时,线程池会拒绝处理任务而抛出异常,异常见下
*/
taskExecutor.setMaxPoolSize(8);
/**
* <!-- 缓存队列(阻塞队列)当核心线程数达到最大时,新任务会放在队列中排队等待执行 -->
*/
taskExecutor.setQueueCapacity(100);
/**
* 建议配置threadNamePrefix属性,出问题时可以更方便的进行排查。
**/
taskExecutor.setThreadNamePrefix("CRM_TO_HRO_EXECUTOR");
// 捕捉线程队列满的 拒绝处理
taskExecutor.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor exe) -> {
log.info("当前任务线程池队列已满.");
});
//初始化
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.config;
import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.yifu.cloud.plus.v1.yifu.common.core.jackson.YifuJavaTimeModule;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.ZoneId;
import java.util.Locale;
import java.util.TimeZone;
/**
* JacksonConfig
*
* @author lengleng
* @author L.cm
* @author lishangbu
* @date 2020-06-17
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
@AutoConfigureBefore(JacksonAutoConfiguration.class)
public class JacksonConfiguration {
@Bean
@ConditionalOnMissingBean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return builder -> {
builder.locale(Locale.CHINA);
builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
builder.serializerByType(Long.class, ToStringSerializer.instance);
builder.modules(new YifuJavaTimeModule());
};
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.config;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
/**
* @author lengleng
* @date 2019/2/1 Redis 配置类
*/
@EnableCaching
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisTemplateConfiguration {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(RedisSerializer.string());
redisTemplate.setHashKeySerializer(RedisSerializer.string());
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.setHashValueSerializer(RedisSerializer.java());
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
@Bean
public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
return redisTemplate.opsForValue();
}
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author lengleng
* @date 2019/2/1 RestTemplate
*/
@Configuration(proxyBeanMethods = false)
public class RestTemplateConfiguration {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.config;
import cn.hutool.core.date.DatePattern;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.SERVLET;
/**
* @author lengleng
* @date 2019-06-24
* <p>
* 注入自自定义SQL 过滤
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = SERVLET)
public class WebMvcConfiguration implements WebMvcConfigurer {
/**
* 增加GET请求参数中时间类型转换 {@link com.yifu.cloud.plus.v1.yifu.common.core.jackson.YifuJavaTimeModule}
* <ul>
* <li>HH:mm:ss -> LocalTime</li>
* <li>yyyy-MM-dd -> LocalDate</li>
* <li>yyyy-MM-dd HH:mm:ss -> LocalDateTime</li>
* </ul>
* @param registry
*/
@Override
public void addFormatters(FormatterRegistry registry) {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setTimeFormatter(DatePattern.NORM_TIME_FORMATTER);
registrar.setDateFormatter(DatePattern.NORM_DATE_FORMATTER);
registrar.setDateTimeFormatter(DatePattern.NORM_DATETIME_FORMATTER);
registrar.registerFormatters(registry);
}
/**
* 系统国际化文件配置
* @return MessageSource
*/
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:i18n/messages");
return messageSource;
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.constant;
/**
* @author lengleng
* @date 2020年01月01日
* <p>
* 缓存的key 常量
*/
public interface CacheConstants {
/**
* oauth 缓存前缀
*/
String PROJECT_OAUTH_ACCESS = "yifu_oauth:access:";
/**
* oauth 缓存令牌前缀
*/
String PROJECT_OAUTH_TOKEN = "yifu_oauth:token:";
/**
* 验证码前缀
*/
String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY:";
/**
* 菜单信息缓存
*/
String MENU_DETAILS = "menu_details";
/**
* 用户信息缓存
*/
String USER_DETAILS = "user_details";
/**
* 字典信息缓存
*/
String DICT_DETAILS = "dict_details";
/**
* 字典项信息缓存
*/
String DICT_ITEM_DETAILS = "dict_item_details";
/**
* oauth 客户端信息
*/
String CLIENT_DETAILS_KEY = "yifu_oauth:client:details";
/**
* 参数缓存
*/
String PARAMS_DETAILS = "params_details";
/**
* 数据权限信息缓存
* data_auth_details0:用户组
* data_auth_details1:用户
* hgw
* 2022-6-9 17:29:49
*/
String DATA_AUTH_DETAILS = "data_auth_details";
/**
* @Description: 每日员工主码缓存
* @Author: hgw
* @Date: 2022/6/21 17:09
**/
String EVERYDAY_EMP_CODE = "everyday_emp_code";
/**
* @Description: 每日员工合同的 申请编码 缓存
* @Author: hgw
* @Date: 2022/6/21 17:09
**/
String EVERYDAY_EMP_CONTRACT_CODE = "everyday_emp_contract_code";
/**
* @Description: 派单申请编码
* @Author: fxj
**/
String EVERYDAY_DISPATCH_CODE = "everyday_dispatch_code";
/**
* 区域数据--标签
*/
String AREA_LABEL = "area_label:";
/**
* 区域数据--值
*/
String AREA_VALUE = "area_value:";
/**
* 用户登录的项目vo缓存
*/
public static final String WXHR_SETTLE_DOMAIN_VOS_BY_USERID = ServiceNameConstants.ARCHIVES_SERVICE + "_SettleDomainVosByUserId";
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.constant;
import java.math.BigDecimal;
/**
* @author lengleng
* @date 2019/2/1
*/
public interface CommonConstants {
/**
* 删除
*/
String STATUS_DEL = "1";
/**
* 正常
*/
String STATUS_NORMAL = "0";
/**
* 锁定
*/
String STATUS_LOCK = "9";
/**
* 菜单树根节点
*/
Long MENU_TREE_ROOT_ID = -1L;
/**
* 部门根节点
*/
Long DEPT_TREE_ROOT_ID = 0L;
/**
* 1L
*/
Long LONG_1 = 1L;
/**
* 菜单
*/
String MENU = "0";
/**
* 编码
*/
String UTF8 = "UTF-8";
/**
* JSON 资源
*/
String CONTENT_TYPE = "application/json; charset=utf-8";
/**
* 前端工程名
*/
String FRONT_END_PROJECT = "yifu-ui";
/**
* 后端工程名
*/
String BACK_END_PROJECT = "yifu";
/**
* 获取一条数据的后缀
*/
String LAST_ONE_SQL = " limit 1";
/**
* 成功标记
*/
Integer SUCCESS = 200;
/**
* 商险导出最大值
*/
Integer EXPORT_TWENTY_THOUSAND = 20000;
/**
* 商险导入最大值
*/
Integer IMPORT_TWENTY_THOUSAND = 20000;
/**
* 失败标记
*/
Integer FAIL = 1;
/**
* 验证码前缀
*/
String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY_";
/**
* 当前页
*/
String CURRENT = "current";
/**
* size
*/
String SIZE = "size";
/**
* JSON 资源
*/
/**
* number 0
*/
String ZERO_STRING = "0";
String FOUR_STRING = "4";
String FIVE_STRING = "5";
String TWELVE_STRING = "12";
String THIRTEEN_STRING = "13";
String FOURTEEN_STRING = "14";
String FIFTEEN_STRING = "15";
String SIXTEEN_STRING = "16";
/**
* number 0
*/
String ZERO_ONE = "01";
/**
* number 0
*/
int ZERO_INT = 0;
/**
* number 5000
*/
int FIVES_INT = 5000;
/**
* number 1
*/
String ONE_STRING = "1";
/**
* number 2
*/
String TWO_STRING = "2";
/**
* number 3
*/
String THREE_STRING = "3";
/**
* 数字int 3
*/
int THREE_INT = 3;
/**
* 下划线
* hgw 2022-6-9 17:36:35
*/
String DOWN_LINE_STRING = "_";
/**
* 空字符串
* hgw 2022-6-9 17:36:35
*/
String EMPTY_STRING ="";
/**
* 数字int 1
* @author fxj
*/
int ONE_INT = 1;
int TWO_INT = 2;
/**
* 个位数字(阿里编码规约不允许直接使用‘魔法值’)
* @Author pwang
* @Date 2019-08-02 16:39
**/
int[] dingleDigitIntArray = {0,1,2,3,4,5,6,7,8,9};
/**
* 个位数字串(阿里编码规约不允许直接使用‘魔法值’)
* @Author pwang
* @Date 2019-08-02 16:39
**/
String[] dingleDigitStrArray = {"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"};
/**
* 月份(阿里编码规约不允许直接使用‘魔法值’)
* @Author zhaji
* @Date 2022-07-28 16:39
**/
String[] MonthStrArray = {"0","1","2","3","4","5","6","7","8","9","10","11","12"};
/**
* 逗号
* @Author fxj
**/
char COMMA_CHAR = ',';
char SPOT_CHAR = '.';
/**
* 100
* @Author fxj
**/
int INTEGER_HUNDRED = 100;
//,逗号
String COMMA_STRING = ",";
//、顿号
String DUNHAO_STRING = "、";
//- 横
char DOWN_LINE_CHAR ='_';
// 冒号 :
String COLON_STRING =":";
// - 横 分割线 中
String CENTER_SPLIT_LINE_STRING = "-";
// 斜杠
String SLASH_SPLIT_LINE_STRING = "/";
// = 等
char ETC_CHAR = '=';
// = 等
String ETC_STRING = "=";
//+ 加
char ADD_CHAR = '+';
//int 4
int FOUR_INT = 4;
//int 5
int FIVE_INT = 5;
String TEN_STRING = "10";
int SEVEN_INT = 7;
public static final String SPOT = ".";
int FIFTY_INT = 50;
int BYTE = 1024;
/**
* 员工初始序列
* @Author pwang
* @Date 2020-05-14 11:13
* @param null
* @return
**/
public static final String EMPLOYEE_INIT_NO = "0001";
/**
* 员工的的前缀位数
* @Author pwang
* @Date 2020-05-14 14:10
**/
int EMPLOYEE_INIT_NO_START = 7;
String SAVE_FAILED = "保存失败!";
String RESULT_EMPTY = "获取结果为空";
//错误信息
String ERROR_NO_DOMAIN = "无此实体!";
String NULL = null;
/**
* @Author fxj
* @Date 2020-03-12 14:48
* @return
**/
String RESULT_DATA_FAIL= "操作失败";
String SAVE_SUCCESS = "保存成功!";
String UPDATE_SUCCESS = "更新成功!";
String PARAM_IS_NOT_EMPTY = "参数不可为空";
String DATA_CAN_NOT_EMPTY = "数据不可为空";
String NO_DATA_TO_HANDLE = "无数据可操作!";
String PLEASE_LOG_IN = "请登录!";
String SEX_MAN = "1";
String SEX_WONMAN = "2";
String SALARY_ISFLAG = "已结算";
String SALARY_UNFLAG = "未结算";
// 是否
String IS_FALSE = "否";
String IS_TRUE = "是";
int SIX_INT = 6;
int EIGHT_INT = 8;
public static final String ZIP_TYPE = "zip";
int BATCH_COUNT = 100;
int BATCH_COUNT1 = 1000;
String IMPORT_DATA_ANALYSIS_ERROR = "数据导入解析异常,请检查表数据格式(1.日期格式:yyyy-MM-dd,2.比例为整数且不含%)";
String CREATE_TIME = "CREATE_TIME";
String ID = "ID";
String PARAM_IS_NOT_ERROR = "传参异常,请检查参数";
int EXCEL_EXPORT_LIMIT = 60000;
String USER = "用户";
/**
* multipart/form-data
* @Author fxj
* @Date 2020-10-13
**/
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
/**
* Content-Disposition
* @Author fxj
* @Date 2020-10-13
**/
public static final String CONTENT_DISPOSITION = "Content-Disposition";
/**
* attachment;filename=
* @Author fxj
* @Date 2020-10-13
**/
public static final String ATTACHMENT_FILENAME = "attachment;filename=";
/**
* USER_AGENT
* @Author fxj
* @Date 2020-10-26
**/
public static final String USER_AGENT = "USER-AGENT";
/**
* 成功颜色
*/
String GREEN = "green";
/**
* 失败颜色
*/
String RED = "red";
/**
* 数字int -1
* @author fxj
*/
int ONE_INT_NEGATE = -1;
/**
* 数字int -1
* @author fxj
*/
String ONE_STRING_NEGATE = "-1";
/**
* 数字int -1
* @author fxj
*/
int TWO_INT_NEGATE = -2;
/**
* 数字int -1
* @author fxj
*/
int THREE_INT_NEGATE = -3;
// 是否
String IS_CHANGE = "划转";
// 年
String YEAR = "年";
// 月
String MONTH = "月";
// 日
String DAY = "日";
/**
* 一年365天
*/
int ONE_YEAR = 365;
/**
* 数字70
*/
int SEVENTY = 70;
/**
* 省市
* @Author fxj
* @Date 2020-08-25
**/
public static final String HEFEISTRING="安徽省-合肥市";
/**
* 省
* @Author fxj
* @Date 2020-08-25
**/
public static final String ANHUISTRING="安徽省";
/**
*是所有者
**/
public static final String IS_OWNER_YES = "0";
/**
*不是所有者
**/
public static final String IS_OWNER_NO = "1";
/**
* 获取登录用户信息失败
**/
public static final String USER_FAIL = "获取登录用户信息失败!";
public static final int SIXTEEN_INT = 16;
public static final String FIFTEEN = "15";
public static final String NINETEEN = "19";
public static final String NINE_STRING = "9";
String EIGHT_STRING = "8";
public static final String PAYMENT_SOCIAL_IMPORT = "payment_social_import";
public static final String PAYMENT_SOCIAL_WAIT_EXPORT = "payment_social_wait_export";
//百分之一 1/100
public static final BigDecimal ONE_OF_PERCENT = new BigDecimal("0.01");
// 1/2
public static final BigDecimal HALF_OF_ONE = new BigDecimal("0.5");
public static final BigDecimal TWO_BIG = new BigDecimal("2");
String SIX_STRING = "6";
String SEVEN_STRING = "7";
/**
* 工资最大不能超过9999999.99
*/
public static final BigDecimal MONEY_MAX = new BigDecimal("9999999.99");
/**
* 工资最小不能小于零
*/
public static final BigDecimal MONEY_MIN = new BigDecimal(0);
public static final int TWENTY_INT = 20;
public static final int TWENTY_ONE_STRING = 21;
public static final String ERROR_MSG_PRFIX = "error=";
public static final String SUCCESS_MSG_PREFIX = "success=";
// 社保细分类型 hgw 2021-6-9 17:54:08
public static final String[] SOCIAL_HANDLE_TYPE = {"0","养老", "医疗", "失业", "工伤", "生育", "大病"};
public static final int SIXTY_INT = 60;
/**
* param error
* @Author fxj
* @Date 2020-08-25
**/
public static final String PARAM_INFO_ERROR = "传参有误!";
public static final String XLSX = ".xlsx";
public static final String ERROR_IMPORT = "执行异常";
// 权限使用的
public static final String A_DEPT_ID = "a.dept_id";
public static final String A_CREATE_BY = "a.CREATE_BY";
}
package com.yifu.cloud.plus.v1.yifu.common.core.constant;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Description Excel配置注解自定义接口
* @author fangxinjiang
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ java.lang.annotation.ElementType.FIELD })
public @interface ExcelAttribute {
/**
* Excel中的列名
*
* @return
*/
public abstract String name();
/**
* 不好用 建议顺序用表头固定
* 列名对应的A,B,C,D...,不指定按照默认顺序排序
*
* @return
*/
public abstract String column() default "";
/**
* 最大长度校验,默认0无需校验
* @return
*/
public abstract int maxLength() default 0;
/**
* 最大值
* @return
*/
public abstract String max() default "0";
/**
* 最小值
* @return
*/
public abstract float min() default 0;
/**
* 提示信息
*
* @return
*/
public abstract String prompt() default "";
/**
* 设置只能选择不能输入的列内容
*
* @return
*/
public abstract String[] combo() default {};
/**
* 是否导出数据
*
* @return
*/
public abstract boolean isExport() default true;
/**
* 是否为重要字段(整列标红,着重显示)
*
* @return
*/
public abstract boolean isMark() default false;
/**
* 是否合计当前列
*
* @return
*/
public abstract boolean isSum() default false;
/**
* 是否必填字段
* @return
*/
public abstract boolean isNotEmpty() default false;
/**
* 是否为电话字段
* @return
*/
public abstract boolean isPhone() default false;
/**
* 是否为身份证
* @return
*/
public abstract boolean isIdCard() default false;
/**
* 是否为日期
* @return
*/
public abstract boolean isDate() default false;
/**
* 是否为邮箱
* @return
*/
public abstract boolean isEmail() default false;
/**
* 是否为Integer
* @return
*/
public abstract boolean isInteger() default false;
/**
* 是否为float
* @return
*/
public abstract boolean isFloat() default false;
/**
* 是否为double
* @return
*/
public abstract boolean isDouble() default false;
/**
* 验证表达式
* @return
*/
public abstract String pattern() default "";
/**
* 数据类型标识或字典表CODE 与 isDataId()同步出现
* 因为字典有的地方有value有的地方用id
* 建议value不用加后缀 id的后缀加_id
* 组装map的时候code=值 冗余一遍code_id =值
* @return
*/
public abstract String dataType() default "";
/**
* 读取内容转表达式 (如: 0=男,1=女,2=未知)
*/
public String readConverterExp() default "";
/**
* 日期格式化字符串
* @return
*/
public abstract String dateFormat() default "yyyy-MM-dd";
/**
* 日期格式化字符串
* @return
*/
public abstract String dateFormatExport() default "";
/**
* 默认错误信息
* @return
*/
public abstract String errorInfo() default "";
/**
* 默认错误信息
* @return
*/
public abstract String errorInfoImport() default "";
/**
* 是否为实体ID 导入要从字典表取数据 导出要对应导出中文数据
* @return
*/
public abstract boolean isDataId() default false;
/**
* 是否为客户单位和项目实体ID 导入要从字典表取数据 导出要对应导出中文数据
* @return
*/
public abstract boolean isOrgan() default false;
/**
* 是否转义,默认 true 如果是字典会转义, false不会转义值
* @return
*/
public abstract boolean isConvert() default true;
/**
* 是否为区域数据 前提:isDataId = true
* @Author fxj
* @Date 2019-09-02
* @param
* @return
**/
public abstract boolean isArea() default false;
/**
* 父ID 前提:isDataId = true
* @Author fxj
* @Date 2019-09-02
* @param
* @return
**/
public abstract String parentField() default "";
/**
* 导出字段组合 只用于导出
* @Author fxj
* @Date 2019-10-11
* @param
* @return
**/
public abstract String componentFieldExport() default "";
/**
* 用于返回可选择导出的中文字段
* @param
* @Author: wangan
* @Date: 2019/10/17
* @Description:
* @return: boolean
**/
public abstract boolean needExport() default false;
/**
* @param
* @Author: wangan
* @Date: 2020/11/5
* @Description: 字典映射不成功是否展示字典key
* @return: boolean
**/
public abstract boolean noRelationExport() default true;
/**
* 是否为实体ID 导入要从字典表取数据 导出要对应导出中文数据
* @return
*/
public abstract String divider() default "";
/**
* @description: 错误信息 需要对字段值提前设置 error= 前缀为错误信息展示为红色, success= 前缀为正确信息展示为绿色
* @return: boolean 是否开启错误信息展示,对字体颜色进行修改
* @author: wangweiguo
* @date: 2021/6/30
*/
public abstract boolean errorMsg() default false;
}
package com.yifu.cloud.plus.v1.yifu.common.core.constant;
/**
* @Author hgw
* @Date 2022-6-29 19:27:33
* @return
* @Description 注解式 静态数据
**/
public class ExcelAttributeConstants {
// 员工类型
public static final String EMP_NATRUE = "emp_natrue";
// 婚姻状况
public static final String EMP_MARRIED = "emp_married";
// 民族
public static final String EMP_NATIONAL = "emp_national";
// 政治面貌
public static final String EMP_POLITICAL = "emp_political";
// 户口性质
public static final String EMP_REGISTYPE = "emp_registype";
// 最高学历
public static final String EDUCATION = "education";
// 合同状态
public static final String PERSONNEL_STATE = "personnel_state";
// 商险状态
public static final String COMMERCIAL_SATTE = "commercial_satte";
// 社保状态
public static final String SOCIAL_ECURITY_STATE = "social_ecurity_state";
// 公积金状态
public static final String FUND_STATUS = "fund_status";
// 减档原因
public static final String DOWNSHIFT_REASON = "downshift_reason";
// 业务类型一级分类
public static final String CUSTOMER_BUSSINESS_PARENT = "customer_business_parent";
// 业务类型二级分类
public static final String CUSTOMER_BUSSINESS_TYPE = "customer_business_type";
// 业务类型三级分类
public static final String CUSTOMER_BUSSINESS_SUB_TYPE = "customer_business_sub_type";
//员工合同类型---签订期限
public static final String EMPLOYEE_CONTRACT_TYPE = "employee_contract_type" ;
//员工合同工时制 1标准工时 2 综合工时 3不定时工时制
public static final String WORKING_HOURS = "working_hours";
//员工合同续签情况
public static final String EMPLOYEE_SITUATION_TYPE = "situation_type" ;
//商险结算类型
public static final String SETTLEMENT_TYPE = "settlementType";
//商险订单状态
public static final String INSURANCE_RECORD_STATUS = "Insurance_record_status";
//社保大病是否收取费用 0 是 1 否
public static final String IS_ILLNESS = "is_illness";
//社保大病取值方式 0 按比例 1按定值
public static final String VALUE_TYPE = "value_type";
public static final String NATION = "nation";
//家庭信息:与本人关系
public static final String RELATIONSHIP_SELF = "relationship_self";
//员工档案:性别
public static final String SEX ="sex";
//员工档案:户口性质
public static final String HOUSEHOLD_NATURE = "household_nature";
//员工档案:客户性质
public static final String NATURE ="nature";
//员工档案:婚姻状况
public static final String MARITAL_STATUS = "marital_status";
//员工档案:人员类型(合同类型)
public static final String PERSONNEL_TYPE = "personnel_type";
//合同业务细分
public static final String PERSONNEL_TYPE_SUB = "personnel_type_sub";
//员工档案:员工标签
public static final String EMPLOYEE_LABLE = "employee_lable";
//员工档案:政治面貌
public static final String POLITICAL_STATUS = "political_status";
//审核状态
public static final String AUDIT_STATUS ="audit_status";
//是否委托
public static final String IS_ENTRUST ="is_entrust";
//系统用户
public static final String SYS_USER ="sys_user";
//区域
public static final String SYS_AREA ="sys_area";
//员工档案:银行
public static final String BANK="bank";
//通用状态标识 0 是 1 否
public static final String STATUS_FLAG = "status_flag";
//学历信息:学历类型
public static final String EDUCATION_TYPE = "education_type";
//职业资格:资格类型
public static final String QUALIFICATION_TYPE = "qualification_type";
//职业资格:资格等级
public static final String QUALIFICATION_LEVEL = "qualification_level";
//员工伤残:伤残等级
public static final String DISABILITY_GRADE = "disability_grade";
//工作履历:工作类型 如兼职、全职等
public static final String WORK_TYPE = "work_type";
//职业资格:获取方式
public static final String OBTAIN_TYPE = "obtain_type";
//学历信息:学制
public static final String EDUCATION_SYSTEM = "education_system";
//工资形式 1.计时工资 2.计件工资 3.其他
public static final String SALARY_TYPE = "salary_type";
// 关系类型
public static final String FAMILY_RELATION = "family_relation";
// 工作类型---工具履历
public static final String WORKINFO_TYPE = "workinfo_type";
// 项目档案来源
public static final String PROJECT_EMP_SOURCE = "project_emp_source";
//区域字段组合
public static final String DEPARTID_PROVINCE_CITY_TOWN = "departId_province_city_town";
//派减离职原因
public static final String REDUCE_PROJECT_REASON = "reduce_project_reason";
//派减离职原因
public static final String REDUCE_SOCIAL_REASON = "social_reduce_reason";
//社保缴纳月份
public static final String SOCIAL_PAY_MONTH = "socialPayMonth";
//身份证
public static final String EMPIDCARD = "empIdcard";
//最低工资提醒
public static final String SYS_MESSAGE_SALARY_TYPE="SYS_MESSAGE_SALARY_TYPE";
//有工资无社保
public static final String HAVE_SALARY_NO_SOCIAL_TYPE="HAVE_SALARY_NO_SOCIAL_TYPE";
}
package com.yifu.cloud.plus.v1.yifu.common.core.constant;
import lombok.experimental.UtilityClass;
@UtilityClass
public class ResultConstants {
public static final String SAVE_SUCCESS ="保存成功!";
public static final String SAVE_FAIL ="保存失败!";
public static final String MODIFY_SUCCESS ="修改成功!";
public static final String MODIFY_FAIL ="修改失败!";
public static final String VALIDITY_FAIL="校验失败";
public static final String NO_USER = "获取登录用户信息失败!";
public static final String SUCCESS_INFO = "操作成功!";
public static final String FAIL_INFO_NO_MODEL = "操作失败无此实体信息!";
public static final String FAIL_INFO_HAVE = "操作失败记录已存在!";
public static final String FAIL_INFO_PARAM_NULL = "操作失败,参数为空!";
public static final String FAIL_INFO_RELATION_FOLLOW = "已关联跟进记录,禁止删除!";
public static final String FAIL_INFO_RELATION_CONTACT = "已关联联系人,禁止删除!";
public static final String REQUEST_LOCK_FAIL = "获取锁失败";
public static final String DATA_IMPORT_PARSING_RESULT = "数据导入解析!数据行数:";
public static final String NO_SELECT_DATA = "请选择数据";
public static final String NO_GETLOCK_DATA = "获取锁失败,10秒后重试!";
public static final String NO_ID = "操作失败,id不能为空!";
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.constant;
/**
* @author lengleng
* @date 2019/2/1
*/
public interface SecurityConstants {
/**
* 角色前缀
*/
String ROLE = "ROLE_";
/**
* 前缀
*/
String PROJECT_PREFIX = "yifu_";
/**
* 项目的license
*/
String PROJECT_LICENSE = "made by yifu";
/**
* 内部
*/
String FROM_IN = "Y";
/**
* 标志
*/
String FROM = "from";
/**
* 默认登录URL
*/
String OAUTH_TOKEN_URL = "/oauth/token";
/**
* grant_type
*/
String REFRESH_TOKEN = "refresh_token";
/**
* 手机号登录
*/
String APP = "app";
/**
* {bcrypt} 加密的特征码
*/
String BCRYPT = "{bcrypt}";
/**
* sys_oauth_client_details 表的字段,不包括client_id、client_secret
*/
String CLIENT_FIELDS = "client_id, CONCAT('{noop}',client_secret) as client_secret, resource_ids, scope, "
+ "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, "
+ "refresh_token_validity, additional_information, autoapprove";
/**
* JdbcClientDetailsService 查询语句
*/
String BASE_FIND_STATEMENT = "select " + CLIENT_FIELDS + " from sys_oauth_client_details";
/**
* 默认的查询语句
*/
String DEFAULT_FIND_STATEMENT = BASE_FIND_STATEMENT + " order by client_id";
/**
* 按条件client_id 查询
*/
String DEFAULT_SELECT_STATEMENT = BASE_FIND_STATEMENT + " where client_id = ?";
/***
* 资源服务器默认bean名称
*/
String RESOURCE_SERVER_CONFIGURER = "resourceServerConfigurerAdapter";
/**
* 用户信息
*/
String DETAILS_USER = "user_info";
/**
* 协议字段
*/
String DETAILS_LICENSE = "license";
/**
* 验证码有效期,默认 60秒
*/
long CODE_TIME = 60;
/**
* 验证码长度
*/
String CODE_SIZE = "6";
/**
* 客户端模式
*/
String CLIENT_CREDENTIALS = "client_credentials";
/**
* 客户端ID
*/
String CLIENT_ID = "clientId";
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.constant;
/**
* @author lengleng
* @date 2018年06月22日16:41:01 服务名称
*/
public interface ServiceNameConstants {
/**
* 认证服务的SERVICEID
*/
String AUTH_SERVICE = "yifu-auth";
/**
* UMPS模块
*/
String UMPS_SERVICE = "yifu-upms-biz";
/**
* consumer模块
*/
String CONSUMER_SERVICE = "consumer-biz";
/**
* provider模块
*/
String PROVIDER_SERVICE = "provider-biz";
/**
* hrms-archives模块
*/
String ARCHIVES_SERVICE = "yifu-archives";
}
package com.yifu.cloud.plus.v1.yifu.common.core.constant;
/**
* @author fxj
* @Date 2022-05-19
*/
public interface UpmsDaprSiderConstants {
// -app-id register-sider -app-port 8848 -dapr-http-port 3005 -dapr-grpc-port 52000 -metrics-port 9098
String APP_ID = "yifu_upms_sider";
String APP_PORT = "4000";
String HTTP_PORT = "3005";
String GRPC_PORT = "52000";
String METRICS_PORT = "9094";
}
package com.yifu.cloud.plus.v1.yifu.common.core.constant;
/**
* @author fang
* 常用的一些验证,如手机、移动号码、联通号码、电信号码、密码、座机、 邮政编码、邮箱、年龄、身份证、URL、QQ、汉字、字母、数字等校验表达式
*/
public class ValidityConstants {
/** 工资-档案-手机号规则 */
public static final String EMP_PHONE_PATTERN = "^1[3-9]\\d{9}$";
/** 手机号规则 hgw2022-1-14 19:24:48客服刘岚有一个电信客户的手机号是16655125569故变更规则 */
public static final String MOBILE_PATTERN="^(1[3-9][0-9])(\\d{8})$";
/** 中国电信号码格式验证 手机段: 133,153,180,181,189,177,1700,173 **/
public static final String CHINA_TELECOM_PATTERN = "(?:^(?:\\+86)?1(?:33|53|7[37]|8[019])\\d{8}$)|(?:^(?:\\+86)?1700\\d{7}$)";
/** 中国联通号码格式验证 手机段:130,131,132,155,156,185,186,145,176,1707,1708,1709,175 **/
public static final String CHINA_UNICOM_PATTERN = "(?:^(?:\\+86)?1(?:3[0-2]|4[5]|5[56]|7[56]|8[56])\\d{8}$)|(?:^(?:\\+86)?170[7-9]\\d{7}$)";
/** 中国移动号码格式验证 手机段:134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705 **/
public static final String CHINA_MOVE_PATTERN = "(?:^(?:\\+86)?1(?:3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(?:^(?:\\+86)?1705\\d{7}$)";
/** 密码规则(6-16位字母、数字) */
public static final String PASSWORD_PATTERN="^[0-9A-Za-z]{6,16}$";
/** 固号(座机)规则 */
public static final String LANDLINE_PATTERN="^(?:\\(\\d{3,4}\\)|\\d{3,4}-)?\\d{7,8}(?:-\\d{1,4})?$";
/** 邮政编码规则 */
public static final String POSTCODE_PATTERN = "[1-9]\\d{5}" ;
/** 邮箱规则 */
public static final String EMAIL_PATTERN = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$" ;
/** 年龄规则 1-120之间 */
public static final String AGE_PATTERN="^(?:[1-9][0-9]?|1[01][0-9]|120)$";
/** 身份证规则 */
public static final String IDCARD_PATTERN="(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)" ;
/** URL规则,http、www、ftp */
public static final String URL_PATTERN = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?" ;
/** QQ规则 */
public static final String QQ_PATTERN = "^[1-9][0-9]{4,13}$" ;
/** 全汉字规则 */
public static final String CHINESE_PATTERN = "^[\u4E00-\u9FA5]+$" ;
/** 全字母规则 */
public static final String STR_ENG_PATTERN="^[A-Za-z]+$";
/** 整数规则 */
public static final String INTEGER_PATTERN = "^-?[0-9]+$" ;
/** 正整数规则 */
public static final String POSITIVE_INTEGER_PATTERN = "^\\+?[1-9][0-9]*$" ;
/**浮点数规则*/
public static final String FLOAT_PATTERN = "^(-?\\d+)(\\.\\d+)?$";
/**日期格式化1*/
public static final String DATEFORMAT1_PATTERN = "YYYY-MM-dd";
/**日期格式化2*/
public static final String DATEFORMAT2_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**日期格式化3*/
public static final String DATEFORMAT3_PATTERN = "YYYY-MM";
/**姓名规则 汉字、英文、· 最多10位*/
public static final String USER_NAME_PATTERN = "^[\\u4e00-\\u9fa5a-zA-Z\\·]{1,10}";
/** 全汉字 最多20位 规则 */
public static final String CHINESE_PATTERN_20 = "^[\\u4E00-\\u9FA5]{1,20}";
/** 最多20位 规则 */
public static final String PATTERN_20 = "^.{1,20}$";
/** 最多32位 规则 */
public static final String PATTERN_32 = "^.{1,32}$";
/** 最多50位 规则 */
public static final String PATTERN_50 = "^.{1,50}$";
/** 最多60位 规则 */
public static final String PATTERN_60 = "^.{1,60}$";
/** 最多200位 规则 */
public static final String PATTERN_200 = "[\\s\\S]{1,200}$";
public static String NUMBER_OF_DECIMAL_PLACE= "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$";
/** 不超过两位小数的正数 */
public static final String POSITIVE_INTEGER_PATTERN_TWO_FLOAT = "^[+]?([0-9]+(.[0-9]{1,2})?)$";
/** 身份证规则(x只能大写) */
public static final String IDCARD_UPPERCASE_PATTERN = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9X]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)" ;
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.constant.enums;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* @author lengleng
* @date 2019-05-16
* <p>
* 字典类型
*/
@Getter
@RequiredArgsConstructor
public enum DictTypeEnum {
/**
* 字典类型-系统内置(不可修改)
*/
SYSTEM("0", "系统内置"),
/**
* 字典类型-业务类型
*/
BIZ("1", "业务类");
/**
* 类型
*/
private final String type;
/**
* 描述
*/
private final String description;
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.constant.enums;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* @author lengleng
* @date 2018/8/15 社交登录类型
*/
@Getter
@RequiredArgsConstructor
public enum LoginTypeEnum {
/**
* 账号密码登录
*/
PWD("PWD", "账号密码登录"),
/**
* 验证码登录
*/
SMS("SMS", "验证码登录");
/**
* 类型
*/
private final String type;
/**
* 描述
*/
private final String description;
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.constant.enums;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* @author lengleng
* @date 2020-02-17
* <p>
* 菜单类型
*/
@Getter
@RequiredArgsConstructor
public enum MenuTypeEnum {
/**
* 字典类型-系统内置(不可修改)
*/
SYSTEM("0", "系统内置"),
/**
* 字典类型-数据权限配置表示
*/
DATA_FLAG("0", "是"),
/**
* 左侧菜单
*/
LEFT_MENU("0", "left"),
/**
* 顶部菜单
*/
TOP_MENU("2", "top"),
/**
* 按钮
*/
BUTTON("1", "button");
/**
* 类型
*/
private final String type;
/**
* 描述
*/
private final String description;
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.exception;
import lombok.NoArgsConstructor;
/**
* @author lengleng
* @date 😴2018年06月22日16:21:57
*/
@NoArgsConstructor
public class CheckedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CheckedException(String message) {
super(message);
}
public CheckedException(Throwable cause) {
super(cause);
}
public CheckedException(String message, Throwable cause) {
super(message, cause);
}
public CheckedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.yifu.cloud.plus.v1.yifu.common.core.exception;
/**
* 错误编码
*
* @author lengleng
* @date 2022/3/30
*/
public interface ErrorCodes {
/**
* 系统编码错误
*/
String SYS_PARAM_CONFIG_ERROR = "sys.param.config.error";
/**
* 系统内置参数不能删除
*/
String SYS_PARAM_DELETE_SYSTEM = "sys.param.delete.system";
/**
* 用户已存在
*/
String SYS_USER_USERNAME_EXISTING = "sys.user.username.existing";
/**
* 用户原密码错误,修改失败
*/
String SYS_USER_UPDATE_PASSWORDERROR = "sys.user.update.passwordError";
/**
* 用户信息为空
*/
String SYS_USER_USERINFO_EMPTY = "sys.user.userInfo.empty";
/**
* 获取当前用户信息失败
*/
String SYS_USER_QUERY_ERROR = "sys.user.query.error";
/**
* 部门名称不存在
*/
String SYS_DEPT_DEPTNAME_INEXISTENCE = "sys.dept.deptName.inexistence";
/**
* 岗位名称不存在
*/
String SYS_POST_POSTNAME_INEXISTENCE = "sys.post.postName.inexistence";
/**
* 岗位名称或编码已经存在
*/
String SYS_POST_NAMEORCODE_EXISTING = "sys.post.nameOrCode.existing";
/**
* 角色名称不存在
*/
String SYS_ROLE_ROLENAME_INEXISTENCE = "sys.role.roleName.inexistence";
/**
* 角色名或角色编码已经存在
*/
String SYS_ROLE_NAMEORCODE_EXISTING = "sys.role.nameOrCode.existing";
/**
* 系统内置菜单不允许删除
*/
String SYS_MENU_DELETE_SYSTEM = "sys.menu.delete.system";
/**
* 菜单上级菜单不可为数据权限配置类菜单
*/
String SYS_MENU_ADD_PARENT_ERROR = "sys.menu.add.parent.error";
/**
* 菜单存在下级节点 删除失败
*/
String SYS_MENU_DELETE_EXISTING = "sys.menu.delete.existing";
/**
* 系统内置字典不允许删除
*/
String SYS_DICT_DELETE_SYSTEM = "sys.dict.delete.system";
/**
* 系统内置字典不能修改
*/
String SYS_DICT_UPDATE_SYSTEM = "sys.dict.update.system";
/**
* 验证码发送频繁
*/
String SYS_APP_SMS_OFTEN = "sys.app.sms.often";
/**
* 手机号未注册
*/
String SYS_APP_PHONE_UNREGISTERED = "sys.app.phone.unregistered";
/**
* 字典存在下级节点 删除失败
*/
String SYS_DICT_DELETE_EXISTING = "sys.dict.delete.existing";
/**
* 系统内置角色不允许删除
*/
String SYS_ROLE_DELETE_SYSTEM = "sys.role.delete.system";
/**
* 该角色下还有关联的用户,请先将用户转移到其他角色!
*/
String SYS_ROLE_DELETE_EXIST_USER = "sys.role.delete.existing.user";
/**
* 系统内置角色不能修改
*/
String SYS_ROLE_UPDATE_SYSTEM = "sys.role.update.system";
/**
* 系统内置用户不允许删除
*/
String SYS_USER_DELETE_SYSTEM = "sys.user.delete.system";
/**
* 系统内置用户不允许修改
*/
String SYS_USER_UPDATE_SYSTEM = "sys.user.update.system";
/**
* 已存在对应标识的角色
*/
String SYS_ROLE_UPDATE_ERROR_CODE_EXIST= "sys.role.update.error.code.exist";
/**
* 已存在对应名称的菜单
*/
String SYS_MENU_ADD_NAME_EXIST = "sys_menu_add_name_exist";
/**
* 已存在对应名称的角色
*/
String SYS_ROLE_UPDATE_ERROR_NAME_EXIST ="sys.role.update.error.name.exist";
/**
* 已存在对应编码的字典
*/
String SYS_DICT_ADD_TYPE_EXISTS = "sys.dict.add.type.exist";
/**
* 已存在对应值的字典项
*/
String SYS_DICT_ITEM_ADD_VALUE_EXIST = "sys.dict.item.add.value.exist";
/**
* 存在下级字典,禁止删除
*/
String SYS_DICT_DELETE_EXIST_CHILD = "sys.dict.delete.exist.child";
/**
* 存在下级字典项值,禁止删除
*/
String SYS_DICT_ITEM_DELETE_EXIST_CHILD = "sys.dict.item.delete.exist.child";
/**
* 已存在对应伤残病名称的数据
*/
String ARCHIVES_EMP_DISABILITY_NAME_EXISTING = "archives.emp.disability.name.existing";
/**
* 已存在对应身份证的家庭成员信息
*/
String ARCHIVES_EMP_FAMILY_NAME_EXISTING = "archives.emp.family.name.existing";
/**
* 无对应身份证的员工信息
*/
String ARCHIVES_EMP_NOT_EXIST = "archives.emp.not.exist";
/**
* 员工已减档
*/
String ARCHIVES_EMP_REDUCED = "archives.emp.reduced";
/**
* 已存在对应身份证的工作记录信息
*/
String ARCHIVES_EMP_WORK_RECORD_EXISTING = "archives.emp.work.record.existing";
/**
* 已存在该员工对应学历名称的学历信息
*/
String ARCHIVES_EMP_EDUCATION_EXISTING = "archives.emp.education.existing";
/**
* 参数不可为空
*/
String PARAM_NOT_EMPTY = "param.not.empty";
/**
* 校验请求异常
*/
String CHECKS_MOBILE_REQUEST_ERROR = "checks.mobile.request.error";
/**
* 单次号码状态校验请求上限100
*/
String CHECKS_MOBILE_REQUEST_LIMIT_HUNDRED = "checks.mobile.request.limit.hundred";
/**
* 银行卡号校验传参有误:姓名、身份证号、银行卡号 必填
*/
String CHECKS_BANK_NO_REQUEST_PARAM_ERROR = "checks.bank.no.request.param.error";
/**
* 存在已减档的档案和已减项的项目,禁止导入
*/
String CHECKS_EMP_PROJECT_ERROR = "checks.emp.project.error";
/**
* 存在已减档的档案,禁止导入
*/
String CHECKS_REDUCE_EMP_ERROR = "checks.reduce.emp.error";
/**
* 该人员暂无档案信息,请先至“在档人员”处建档
*/
String CHECKS_EXIT_EMPPROJECT_ERROR = "checks.exit.empproject.error";
/**
* 存在已减项的项目,禁止导入
*/
String CHECKS_REDUCE_PROJECT_ERROR = "checks.reduce.project.error";
/**
* 人员不在该项目,无法更新
*/
String CHECKS_EMP_EXIT_ERROR = "checks.emp.exit.error";
/**
* 人员已减项,无法更新
*/
String CHECKS_EMP_DELETE_ERROR = "checks.emp.delete.error";
// 该人员已存在,禁止重复添加
String ARCHIVES_IMPORT_EMP_IDCARD_EXISTING = "archives.import.emp.idCard.existing";
// 手机号校验错误
String ARCHIVES_IMPORT_EMP_PHONE_CHECK_ERROR = "archives.import.emp.phone.check.error";
// 手机号已被其他身份证使用
String ARCHIVES_IMPORT_EMP_PHONE_EXIST_ERROR = "archives.import.emp.phone.exist.error";
// 婚姻状况在字典中未找到
String ARCHIVES_IMPORT_EMP_MARRIED_ERROR = "archives.import.emp.married.error";
// 民族在字典中未找到
String ARCHIVES_IMPORT_EMP_NATIONAL_ERROR = "archives.import.emp.national.error";
// 政治面貌在字典中未找到
String ARCHIVES_IMPORT_EMP_POLITICAL_ERROR = "archives.import.emp.political.error";
// 户口性质在字典中未找到
String ARCHIVES_IMPORT_EMP_REGISTYPE_ERROR = "archives.import.emp.registype.error";
// 最高学历在字典中未找到
String ARCHIVES_IMPORT_EMP_EDUCATION_ERROR = "archives.import.emp.education.error";
// 员工类型在字典中未找到
String ARCHIVES_IMPORT_EMP_NATRUE_ERROR = "archives.import.emp.natrue.error";
// 户籍所在地未找到区域
String ARCHIVES_IMPORT_EMP_AREA_ERROR = "archives.import.emp.area.error";
// 档案所在地未找到区域
String ARCHIVES_IMPORT_EMP_FILE_AREA_ERROR = "archives.import.emp.file.area.error";
// 大专及以上,最高学历必填
String ARCHIVES_IMPORT_EMP_HIGH_EDUCATION_ERROR = "archives.import.emp.high.education.error";
// 该人员未在档,请核实
String ARCHIVES_IMPORT_EMP_NOT_EXISTS = "archives.import.emp.not.exists";
// 存在已减档的档案,禁止导入
String ARCHIVES_IMPORT_EMP_ERROR_STATUS_EXISTS = "archives.import.emp.error.status.exists";
// 身份证必填
String ARCHIVES_IMPORT_EMP_IDCARD_MUST = "archives.import.emp.idCard.must";
String ARCHIVES_IMPORT_EMP_EMPNAME_MUST = "archives.import.emp.empName.must";
// 减档原因必填
String ARCHIVES_IMPORT_EMP_LEAVEREASON_MUST = "archives.import.emp.leaveReason.must";
String ARCHIVES_IMPORT_EMP_LEAVEREMARK_LENGTH = "archives.import.emp.leaveRemark.length";
String ARCHIVES_IMPORT_EMP_HAVE_PROJECT = "archives.import.emp.have.project";
String ARCHIVES_IMPORT_EMP_EMAIL_CHECK = "archives.import.emp.email.check";
String ARCHIVES_IMPORT_EMP_EMAIL_LENGTH = "archives.import.emp.email.length";
// 减项原因在字典中未找到
String ARCHIVES_IMPORT_EMP_REDUCE_ERROR = "archives.import.emp.reduce.error";
/**
* 项目档案状态为已审核,禁止删除
*/
String CHECKS_PROJECT_DELETE_ERROR = "checks.project.delete.error";
/**
* 已存在对应身份证的证书信息
*/
String ARCHIVES_EMP_CERTIFICATE_NAME_EXISTING = "archives.emp.certificate.name.existing";
/**
* 待划转员工已在目标项目下不可划转
*/
String CHECKS_CHANGE_EMP_PROJECT = "checks.change.emp.project";
/**
* 导入的文件格式不正确
*/
String IMPORT_FILE_TYPE_ERROR = "import.file.type.error";
/**
* 申请年份不可为未来年份
*/
String ARCHIVES_EMP_CERTIFICATE_DECLARE_YEAR_ERROR = "archives.emp.certificate.declare.year.error";
/**
* 对应项目编码无项目档案信息,请核实后导入
*/
String ARCHIVES_PROJECT_EMP_NOT_EXIST = "archives.project.emp.not.exist";
/**
* 人员在该项目下存在进行中/未完结的服务
*/
String ARCHIVES_PROJECT_CHANGE_NOT_EXIST = "archives.project.change.not.exist";
/**
* 人员在原项目中存在在途的服务,请先终止后,再进行划转
*/
String QT_PROJECT_CHANGE_NOT_EXIST = "qt.project.change.not.exist";
/**
* 未找到对应的项目,请核实
*/
String PROJECT_SEARCH_NOT_EXIST = "project.search.not.exist";
/**
* 不良记录费用损失和其他损失不可同时为空
*/
String ARCHIVES_PROJECT_EMP_LOSE_FEE_NOT_EMPTY = "archives.project.emp.lose.fee.not.empty";
/**
* 划转起始月不能为空
*/
String CHANGE_START_MONTH_EXIT = "change.strat.month.exit";
/**
* 划转起始月要小于等于当前月
*/
String CHANGE_LESS_MONTH_EXIT = "change.less.month.exit";
/**
* 未找到该人员的项目档案,请核实
*/
String PROJECT_PERSON_SEARCH_EXIT = "project.person.search.exit";
/**
* 该人员项目档案已减项,不允许划转
*/
String PROJECT_PERSON_DELETE_EXIT = "project.person.delete.exit";
/**
* 派单员工合同相关信息不可为空
*/
String EMP_DISPATCH_CONTRACT_NOT_EMPTY = "emp.dispatch.contract.not.empty";
/**
* 派单员工社保相关信息不可为空
*/
String EMP_DISPATCH_SOCIAL_NOT_EMPTY = "emp.dispatch.social.not.empty";
/**
* 派单公积金信息不可为空
*/
String EMP_DISPATCH_FUND_NOT_EMPTY = "emp.dispatch.fund.not.empty";
/**
* 新增异常:已存在社保数据
*/
String EMP_DISPATCH_SOCIAL_EXISTING = "emp.dispatch.social.existing";
/**
* 新增异常:存在办理成功未派减的工伤社保数据
*/
String EMP_DISPATCH_SOCIAL_INJURY_EXISTING = "emp.dispatch.social.injury.existing";
/**
* 新增异常:存在办理成功未派减的五险社保数据,禁止新增工伤
*/
String EMP_DISPATCH_SOCIAL_NOT_REDUCE = "emp.dispatch.social.not.reduce";
/**
* 新增异常:存在办理成功未派减的工伤社保数据,禁止新增五险
*/
String EMP_DISPATCH_SOCIAL_INJURY_NOT_REDUCE = "emp.dispatch.social.injury.not.reduce";
/**
* 新增异常:未找到对应社保户名称的可用基数配置信息
*/
String EMP_DISPATCH_SOCIAL_HOLD_NOT_EXIST = "emp.dispatch.social.hold.not.exist";
/**
* 新增异常:未找到对应公积金户名称的可用基数配置信息
*/
String EMP_DISPATCH_FUND_HOLD_NOT_EXIST = "emp.dispatch.fund.hold.not.exist";
/**
* 新增异常:未找到对应公积金比例配置信息
*/
String EMP_DISPATCH_FUND_PERCENT_NOT_EXIST = "emp.dispatch.fund.percent.not.exist";
/**
* 新增异常:必须派单社保或公积金,不支持单派档案
*/
String EMP_DISPATCH_SOCIAL_AND_FUND_NOT_EMPTY = "emp.dispatch.social.and.fund.not.empty";
/**
* 新增异常:未找到对应项目编码信息
*/
String EMP_DISPATCH_PROJECT_NOT_FOUND = "emp.dispatch.project.not.found";
/**
* 新增异常:派单新增档案失败,请重试
*/
String EMP_DISPATCH_ADD_EMP_ERROR = "emp.dispatch.add.emp.error";
/**
* 新增异常:派单新增合同失败,请重试
*/
String EMP_DISPATCH_ADD_CONTRACT_ERROR="emp.dispatch.add.contract.error";
/**
* 新增异常:派单新增项目档案失败,请重试
*/
String EMP_DISPATCH_ADD_PROJECT_ERROR="emp.dispatch.add.project.error";
/**
* 新增异常:已存在公积金数据
*/
String EMP_DISPATCH_FUND_EXISTING = "emp.dispatch.fund.existing";
/**
* 派减异常: 未找到社保及公积金信息
*/
String EMP_DISPATCH_SOCIAL_FUND_NOT_EMPTY = "emp.dispatch.social.fund.not.empty";
/**
* 派减异常: 请选择社保停缴日期或公积金停缴日期
*/
String EMP_DISPATCH_REDUCE_SOCIAL_FUND_NOT_EMPTY = "emp.dispatch.reduce.social.fund.not.empty";
/**
* 派减异常: 未找到办理成功的社保状态,或社保派减中,请确认后重试
*/
String EMP_DISPATCH_REDUCE_SOCIAL_STATUS_ERROR = "emp.dispatch.reduce.social.status.error";
/**
* 派减异常: 未找到办理成功的公积金状态,或公积金派减中,请确认后重试
*/
String EMP_DISPATCH_REDUCE_FUND_STATUS_ERROR = "emp.dispatch.reduce.fund.status.error";
/**
* 派减异常: 本次派增已存在对应身份证号的派减记录
*/
String EMP_DISPATCH_REDUCE_EXISTS = "emp.dispatch.reduce.exists";
/**
* 当前社保导入队列不足或者数据量过大,请稍后重试!
*/
String SOCIALINFO_LIST_NUM_LARGE = "socialinfo.list.num.large";
/**
* 派增异常: 自定义缴纳养老基数不可为空
*/
String EMP_DISPATCH_SOCIAL_DIY_NOT_EMPTY = "emp.dispatch.social.diy.not.empty";
/**
* 派增异常: 对应项目编码的项目档案已减项,请去项目档案处复项
*/
String EMP_DISPATCH_EMP_PROJECT_NOT_USED = "emp.dispatch.emp.project.not.used";
/**
* 派增异常: 对应身份证的人员档案已减档
*/
String EMP_DISPATCH_EMP_NOT_USED = "emp.dispatch.emp.not.used";
/**
* 派增异常: 社保派单基数不可小于最低基数且不可大于最高基数
*/
String EMP_DISPATCH_SOCIAL_LIMIT_ERROR = "emp.dispatch.social.limit.error";
/**
* 派增异常: 公积金派单基数不可小于最低基数且不可大于最高基数
*/
String EMP_DISPATCH_FUND_LIMIT_ERROR = "emp.dispatch.fund.limit.error";
/**
* 派增异常: 社保各项基数不一致,委托备注必填
*/
String EMP_DISPATCH_SOCIAL_BASE_LIMIT_ERROR = "emp.dispatch.social.base.limit.error";
/**
* 派增异常: 社保各项起缴日不一致,委托备注必填
*/
String EMP_DISPATCH_SOCIAL_DATE_LIMIT_ERROR = "emp.dispatch.social.date.limit.error";
/**
* 派增异常: 社保各项起缴日不一致,委托备注必填
*/
String EMP_DISPATCH_SOCIAL_DATE_LIMIT_ERROR2 = "emp.dispatch.social.date.limit.error2";
/**
* 派增异常: 社保各项起缴月份需为可补缴月份,请确认后操作
*/
String EMP_DISPATCH_SOCIAL_START_IS_ERROR = "emp.dispatch.social.start.is.error";
/**
* 派增异常: 公积金起缴月份需为可补缴月份,请确认后操作
*/
String EMP_DISPATCH_FUND_DATE_LIMIT_ERROR = "emp.dispatch.fund.start.is.error";
/**
* 派增异常: 合同起缴时间、合同类型、签订期限必填不可为空
*/
String EMP_DISPATCH_EMP_CONTRACT_NOT_EMPTY = "emp.dispatch.emp.contract.not.empty";
/**
* 派增异常: 系统无对应项目档案,档案相关同色字段必填
*/
String EMP_DISPATCH_EMP_NOT_EMPTY = "emp.dispatch.emp.not.empty";
/**
* 派增异常: 对应项目编码已停止合作
*/
String EMP_DISPATCH_SETTLEDOMAIN_STOP = "emp.dispatch.settleDomain.stop";
/**
* 派减异常: 无对应项目编码的社保信息
*/
String EMP_DISPATCH_REDUCE_SOCIAL_DEPARTNO_ERROR = "emp.dispatch.reduce.social.depart.no.error";
/**
* 派减异常: 无对应项目编码的公积金信息
*/
String EMP_DISPATCH_REDUCE_FUND_DEPARTNO_ERROR = "emp.dispatch.reduce.fund.depart.no.error";
/**
* 派增异常: 单派工伤其他起缴日期不可填写
*/
String EMP_DISPATCH_SOCIAL_DIY_INJURY_ERROR = "emp.dispatch.social.diy.injury.error";
/**
* 派增异常: 已存在对应手机号码的在用员工档案
*/
String EMP_DISPATCH_EMP_MOBILE_REPEAT = "emp.dispatch.emp.mobile.repeat";
/**
* 派增异常: 同一身份证不可分多行派单
*/
String EMP_DISPATCH_EXIST = "emp_dispatch_exist";
/**
* 派增异常: 已存在兼职工伤,请派减后再派增五险
*/
String EMP_DISPATCH_SOCIAL_INJURY_EXISTING_LIMIT = "emp.dispatch.social.injury.existing.limit";
/**
* 派增异常: 失败项重新派单社保户与已有社保户不一致
*/
String EMP_DISPATCH_SOCIAL_HOLD_NOT_SAME = "emp.dispatch.social.hold.same";
/**
* 派增异常: 失败项重新派单缴纳方式不可变更
*/
String EMP_DISPATCH_SOCIAL_PAYMENT_TYPE_NOT_SAME = "emp.dispatch.social.payment.type.same";
String ARCHIVES_IMPORT_EMP_TRUE = "archives.import.emp.true";
/**
* 派增异常: 固定期限合同截止日期不可为空
**/
String EMP_DISPATCH_EMP_CONTRACT_END_NOT_EMPTY = "emp.dispatch.emp.contract.end.not.empty";
/**
* 派增异常: 合同类型为其他时业务细分不可为空
**/
String EMP_DISPATCH_EMP_CONTRACT_SUB_NAME_NOT_EMPTY = "emp.dispatch.emp.contract.sub.name.not.empty";
}
package com.yifu.cloud.plus.v1.yifu.common.core.exception;
import lombok.NoArgsConstructor;
@NoArgsConstructor //@NoArgsConstructor: 自动生成无参数构造函数。
public class ExcelException extends RuntimeException {
public ExcelException(String message) {
super(message);
}
public ExcelException(Throwable cause) {
super(cause);
}
public ExcelException(String message, Throwable cause) {
super(message, cause);
}
public ExcelException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.exception;
/**
* @author lengleng
* @date 2018年06月22日16:22:15
*/
public class ValidateCodeException extends RuntimeException {
private static final long serialVersionUID = -7285211528095468156L;
public ValidateCodeException() {
}
public ValidateCodeException(String msg) {
super(msg);
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.exception;
import lombok.NoArgsConstructor;
/**
* @author lengleng
* @date 2018年06月22日16:22:03 403 授权拒绝
*/
@NoArgsConstructor
public class YifuDeniedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public YifuDeniedException(String message) {
super(message);
}
public YifuDeniedException(Throwable cause) {
super(cause);
}
public YifuDeniedException(String message, Throwable cause) {
super(message, cause);
}
public YifuDeniedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.yifu.cloud.plus.v1.yifu.common.core.factory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* @author lengleng
* @date 2022/3/29
*
* 读取自定义 yaml 文件工厂类
*/
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
}
catch (IllegalStateException e) {
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.jackson;
import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.PackageVersion;
import com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.InstantSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
/**
* java 8 时间默认序列化
*
* @author L.cm
* @author lishanbu
*/
public class YifuJavaTimeModule extends SimpleModule {
public YifuJavaTimeModule() {
super(PackageVersion.VERSION);
// ======================= 时间序列化规则 ===============================
// yyyy-MM-dd HH:mm:ss
this.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER));
// yyyy-MM-dd
this.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ISO_LOCAL_DATE));
// HH:mm:ss
this.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ISO_LOCAL_TIME));
// Instant 类型序列化
this.addSerializer(Instant.class, InstantSerializer.INSTANCE);
// ======================= 时间反序列化规则 ==============================
// yyyy-MM-dd HH:mm:ss
this.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER));
// yyyy-MM-dd
this.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_LOCAL_DATE));
// HH:mm:ss
this.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ISO_LOCAL_TIME));
// Instant 反序列化
this.addDeserializer(Instant.class, InstantDeserializer.INSTANT);
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.util;
import lombok.experimental.UtilityClass;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.web.method.HandlerMethod;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* 类工具类
*
* @author L.cm
*/
@UtilityClass
public class ClassUtils extends org.springframework.util.ClassUtils {
private final ParameterNameDiscoverer PARAMETERNAMEDISCOVERER = new DefaultParameterNameDiscoverer();
/**
* 获取方法参数信息
* @param constructor 构造器
* @param parameterIndex 参数序号
* @return {MethodParameter}
*/
public MethodParameter getMethodParameter(Constructor<?> constructor, int parameterIndex) {
MethodParameter methodParameter = new SynthesizingMethodParameter(constructor, parameterIndex);
methodParameter.initParameterNameDiscovery(PARAMETERNAMEDISCOVERER);
return methodParameter;
}
/**
* 获取方法参数信息
* @param method 方法
* @param parameterIndex 参数序号
* @return {MethodParameter}
*/
public MethodParameter getMethodParameter(Method method, int parameterIndex) {
MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex);
methodParameter.initParameterNameDiscovery(PARAMETERNAMEDISCOVERER);
return methodParameter;
}
/**
* 获取Annotation
* @param method Method
* @param annotationType 注解类
* @param <A> 泛型标记
* @return {Annotation}
*/
public <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) {
Class<?> targetClass = method.getDeclaringClass();
// The method may be on an interface, but we need attributes from the target
// class.
// If the target class is null, the method will be unchanged.
Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
// If we are dealing with method with generic parameters, find the original
// method.
specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
// 先找方法,再找方法上的类
A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType);
;
if (null != annotation) {
return annotation;
}
// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
return AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), annotationType);
}
/**
* 获取Annotation
* @param handlerMethod HandlerMethod
* @param annotationType 注解类
* @param <A> 泛型标记
* @return {Annotation}
*/
public <A extends Annotation> A getAnnotation(HandlerMethod handlerMethod, Class<A> annotationType) {
// 先找方法,再找方法上的类
A annotation = handlerMethod.getMethodAnnotation(annotationType);
if (null != annotation) {
return annotation;
}
// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
Class<?> beanType = handlerMethod.getBeanType();
return AnnotatedElementUtils.findMergedAnnotation(beanType, annotationType);
}
}
package com.yifu.cloud.plus.v1.yifu.common.core.util;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.compile;
/**
* @author: FANG
* @createDate: 2017年7月24日 下午4:50:23
* @Description 常用工具类
*/
@Slf4j
public class Common {
/**
* 字符串不为空且不是空串不是字符"null"
*
* @param str
* @return
* @author: fxj
*/
public static boolean isEmpty(String str) {
return null == str || "".equals(str.trim()) || "null".equals(str.trim()) || "undefinded".equals(str.trim());
}
/**
* 截取startStr和endStr中间的字符串(开区间)
*
* @param startStr 开始的标志
* @param endStr 结束标志
* @param src 源串
* @return 返回符合要求的字符串或者返回null
* @author: fxj
*/
public static String subByStr(String startStr, String endStr, String src) {
if (StringUtils.isNotBlank(src) && StringUtils.isNotBlank(startStr) && StringUtils.isNotBlank(endStr)) {
int start = src.indexOf(startStr);
int end = src.indexOf(endStr);
if (end > start && start > -1) {
return src.substring(start + 1, end);
}
}
return null;
}
/**
* 对象null
*
* @param obj
* @return
* @author: fxj
*/
public static boolean isEmpty(Object obj) {
return null == obj || "".equals(obj) || "null".equals(obj);
}
public static boolean isNotNull(Object obj) {
return null != obj && !"".equals(obj) && !"null".equals(obj);
}
public static boolean isNotEmpty(List obj) {
return (null != obj && obj.size() > 0);
}
public static boolean isNotNull(String obj) {
if (null != obj && !"".equals(obj) && !"undefined".equals(obj) && !"null".equals(obj)) {
return true;
}
return false;
}
// 金额验证
public static boolean isNumber(String str) {
// 判断小数点后2位的数字的正则表达式
Pattern pattern = compile("^((-?[1-9]{1}\\d*)|(-?[0]{1}))(\\.(\\d){0,2})?$");
Matcher match = pattern.matcher(str);
return match.matches() != false;
}
/**
* 允许上传的文件类型
*
* @Author pwang
* @Date 2020-01-07 15:52
* @param null
* @return
**/
private static final String suffixList = "gif|jpg|jpeg|png|bmp|xls|xlsx|csv|pdf|docx|doc|m4a|mp3|zip|rar|txt";
/**
* 判断是否为允许的上传文件类型,true表示允许
*/
public static boolean checkFile(String fileName) {
// 获取文件后缀
String suffix = getSuffix(fileName);
if (null != suffix) {
if (suffixList.contains(suffix.trim().toLowerCase())) {
return true;
}
}
return false;
}
/**
* 判断是否为允许的上传文件类型,true表示允许
*/
public static String getSuffix(String fileName) {
if (isEmpty(fileName) || fileName.lastIndexOf(CommonConstants.SPOT_CHAR) < 0) {
return null;
}
// 获取文件后缀
return fileName.substring(fileName.lastIndexOf(CommonConstants.SPOT_CHAR)
+ 1, fileName.length());
}
/**
* 将字符串根据分割附转换为字符集合
*
* @param str
* @param regex
* @return
* @author: pwang
*/
public static List<String> initStrToList(String str, String regex) {
List<String> result = new ArrayList<String>();
try {
if (isNotNull(str) && isNotNull(regex)) {
String[] strTemp = str.split(regex);
if (isNotNull(strTemp)) {
for (String temp : strTemp) {
if (isNotNull(temp)) {
result.add(temp);
}
}
}
}
} catch (Exception e) {
log.error("字符串转LIST错误");
return null;
}
return result;
}
/**
* 将集合拼成串
*
* @param <T>
* @param str
* @param regex 分隔符默认,
* @return
*/
public static <T> String ListToStr(Collection<T> str, String regex) {
String result = "";
try {
if (isNotNull(str)) {
// 默认用,分割
if (!isNotNull(regex)) {
regex = ",";
}
for (Object strtemp : str) {
if ("".equals(result)) {
result = String.valueOf(strtemp);
} else {
result = result + regex + strtemp;
}
}
}
} catch (Exception e) {
// 数据异常
}
return result;
}
public static <T> boolean isNotNull(Collection<T> obj) {
return null != obj && obj.size() > 0;
}
public static List<String> getList(String ids) {
List<String> idList = null;
if (Common.isNotNull(ids)) {
idList = Common.initStrToList(ids, CommonConstants.COMMA_STRING);
}
return idList;
}
/**
* 对象转string
*
* @param param
* @return
*/
public static String getStringValByObject(Object param) {
if (null == param) {
return null;
} else if (param instanceof Integer) {
return Integer.toString(((Integer) param).intValue());
} else if (param instanceof String) {
return (String) param;
} else if (param instanceof Double) {
return Double.toString(((Double) param).doubleValue());
} else if (param instanceof Float) {
return Float.toString(((Float) param).floatValue());
} else if (param instanceof Long) {
return Long.toString(((Long) param).longValue());
} else if (param instanceof Boolean) {
return Boolean.toString(((Boolean) param).booleanValue());
} else if (param instanceof Date) {
return DateUtil.formatDate((Date) param);
} else {
return param.toString();
}
}
/**
* 根据属性名获取属性值
*
* @param fieldName
* @param o
* @return
*/
public static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter);
Object value = method.invoke(o);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static <T> HashMap<String, T> listToHashMapByKey(List<T> list, String keyPreStr, String filedKey) {
HashMap<String, T> hashMap = new HashMap<String,T>();
Object key = null;
String[] split = null;
if (null != list) {
if (filedKey.indexOf(CommonConstants.DOWN_LINE_CHAR) > CommonConstants.dingleDigitIntArray[0]) {
split = filedKey.split(CommonConstants.DOWN_LINE_STRING);
for (T t : list) {
key= null;
key = getFieldsValue(t, split, key);
hashMap.put(keyPreStr +CommonConstants.DOWN_LINE_STRING+ getStringValByObject(key), t);
}
} else {
for (T t : list) {
key= null;
key = getFieldValueByName(filedKey, t);
hashMap.put(keyPreStr +CommonConstants.DOWN_LINE_STRING+ getStringValByObject(key), t);
}
}
}
return hashMap;
}
/**
* 从实体中获取多个字段的值并已下划线分割
*
* @param t
* @param split
* @return
* @Author fxj
* @Date 2019-09-24
**/
private static <T> Object getFieldsValue(T t, String[] split, Object key) {
int i = 0;
while (i < split.length) {
if (null == key || CommonConstants.EMPTY_STRING.equals(key)) {
key = getFieldValueByName(split[i], t);
} else {
key = key + CommonConstants.DOWN_LINE_STRING + getFieldValueByName(split[i], t);
}
i++;
}
return key;
}
/**
* 如果为空或零 返回true 否则 返回false
* @Author fxj
* @Date 2020-12-29
* @param data
* @return
**/
public static boolean isNullOrZero(BigDecimal data) {
if (null == data ||
BigDecimal.ZERO.compareTo(data) == CommonConstants.ZERO_INT){
return true;
}
return false;
}
public static String isNotNullToStr(Integer value) {
if (Common.isNotNull(value)){
return Integer.toString(value);
}
return null;
}
public static Integer isNotNullToInt(String value) {
if (Common.isNotNull(value)){
try {
return Integer.valueOf(value);
}catch (Exception e){
return null;
}
}
return null;
}
/**
* 默认"null"
* @param obj
* @return
*/
public static String isBlankToNullString(String obj) {
if(obj == null || "".equals(obj)) {
return CommonConstants.NULL;
}
if(obj.trim().length() == 0) {
return CommonConstants.NULL;
}
if(obj.trim().equals("null")) {
return CommonConstants.NULL;
}
return obj;
}
public static String isNullToString(StringBuilder obj) {
if(obj == null) {
return CommonConstants.EMPTY_STRING;
}
return obj.toString();
}
public static String isNullToString(String obj) {
if(obj == null || "".equals(obj)) {
return CommonConstants.EMPTY_STRING;
}
if(obj.trim().length() == 0) {
return CommonConstants.EMPTY_STRING;
}
if(obj.trim().equals("null")) {
return CommonConstants.EMPTY_STRING;
}
return obj;
}
/**
* 两个日期中间年份
* @Author fxj
* @Date 2021-07-22
* @param start yyyy-MM-dd
* @param end yyyy-MM-dd
* @return
**/
public static int getYearOfTime(String start, String end) {
int year = 0;
if (Common.isEmpty(start) || Common.isEmpty(end) || start.length() < 10 || end.length() < 10){
return year;
}
String startYear = start.substring(0,4);
String endYear = end.substring(0,4);
if (!Common.isNumber(startYear) || !Common.isNumber(endYear)){
return year;
}
year = Integer.valueOf(endYear).intValue() - Integer.valueOf(startYear).intValue() ;
return year < 0?0:year;
}
public static int getYearOfTime(Date start, Date end) {
int year = 0;
if (Common.isEmpty(start) || Common.isEmpty(end)){
return year;
}
String startYear = DateUtil.getYear(start).substring(0,4);
String endYear = DateUtil.getYear(end).substring(0,4);
if (!Common.isNumber(startYear) || !Common.isNumber(endYear)){
return year;
}
year = Integer.valueOf(endYear).intValue() - Integer.valueOf(startYear).intValue() ;
return year < 0?0:year;
}
/**
* 公积金单边小数点格式化
*
* @param money
* @param type
* @return
* @Author fxj
* @Date 2019-09-26
**/
public static BigDecimal formatMoneyForFund(BigDecimal money, int type) {
DecimalFormat formater = new DecimalFormat("#0.#");
if (type == 1) {//四舍五入取整
return BigDecimal.valueOf(money.doubleValue()).setScale(0, RoundingMode.HALF_UP);
}
if (type == 2) {//元一下全部舍去,取整
return BigDecimal.valueOf(Math.floor(money.doubleValue())).setScale(0, BigDecimal.ROUND_UP);
}
if (type == 3) {//见角进元
return BigDecimal.valueOf(Math.ceil(BigDecimal.valueOf(money.doubleValue()).setScale(1, RoundingMode.HALF_DOWN).doubleValue())).setScale(0, BigDecimal.ROUND_UP);
}
if (type == 4) {//保留两位小数
return BigDecimal.valueOf(money.doubleValue()).setScale(2, RoundingMode.HALF_UP);
}
if (type == 5) {//保留一位小数
return BigDecimal.valueOf(money.doubleValue()).setScale(1, RoundingMode.HALF_UP);
}
return money;
}
public static void clear(Collection map){
if (Common.isNotNull(map)){
map.clear();
}
}
public static void clear(Map map){
if (Common.isNotNull(map)){
map.clear();
}
}
/**
* 按字段返回字符串
*
* @param list
* @param filedName
* @param <T>
* @return
*/
public static <T> List<String> listObjectToStrList(List<T> list, String filedName) {
List<String> idsStr = new ArrayList<String>();
Object temp = null;
if (null != list && list.size() > 0) {
for (T t : list) {
temp = getFieldValueByName(filedName, t);
if (null != temp) {
idsStr.add(temp.toString());
}
}
}
return idsStr;
}
/**
* 默认空 置为零
* @param obj
* @return
*/
public static BigDecimal isBlankToBigDecimalZero(BigDecimal obj) {
if(obj == null) {
return BigDecimal.ZERO;
}
if(String.valueOf(obj).trim().length() == 0) {
return BigDecimal.ZERO;
}
if(String.valueOf(obj).trim().equals("null")) {
return BigDecimal.ZERO;
}
return obj;
}
/**
* 商险附件允许上传的文件类型
*
* @Author pwang
* @Date 2020-01-07 15:52
* @param null
* @return
**/
private static final String insuranceSuffixList = "pdf|png|jpg|doc|docx|xls|xlsx|rar|zip";
/**
* 判断是否为允许的上传文件类型,true表示允许
*/
public static boolean checkInsuranceFile(String fileName) {
// 获取文件后缀
String suffix = getSuffix(fileName);
if (null != suffix) {
if (insuranceSuffixList.contains(suffix.trim().toLowerCase())) {
return true;
}
}
return false;
}
}
package com.yifu.cloud.plus.v1.yifu.common.core.util;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.sms.MonthObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
/**
* 日期工具类
*
* @author fang
* @ClassName: DateUtil
* @date 2017年7月10日 下午4:13:33
*/
@Slf4j
public class DateUtil {
private DateUtil(){
throw new IllegalStateException("DateUtil class");
}
/**
* 可用时间格式
*/
private static String[] parsePatterns = {DateUtil.DATE_PATTERN, DateUtil.ISO_EXPANDED_DATE_FORMAT, DateUtil.DATETIME_PATTERN_SECOND, DateUtil.DATETIME_PATTERN_MINUTE, DateUtil.DATETIME_PATTERN_XIEGANG,
"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyymmdd"};
/**
* Base ISO 8601 Date format yyyyMMdd i.e., 20021225 for the 25th day of
* December in the year 2002
*/
public static final String ISO_DATE_FORMAT = "yyyyMMdd";
/**
* Expanded ISO 8601 Date format yyyy-MM-dd i.e., 2002-12-25 for the 25th
* day of December in the year 2002
*/
public static final String ISO_EXPANDED_DATE_FORMAT = "yyyy-MM-dd";
/**
* yyyy/MM/dd
*/
public static final String DATETIME_PATTERN_XIEGANG = "yyyy/MM/dd";
/**
* yyyyMM
*/
public static final String DATETIME_YYYYMM = "yyyyMM";
/**
* yyyy
*/
public static final String DATETIME_YYYY = "yyyy";
/**
* yyyy-MM
*/
public static final String DATETIME_YYYY_MM = "yyyy-MM";
/**
* yyyy-MM-dd hh:mm:ss
*/
public static final String DATETIME_PATTERN_SECOND = "yyyy-MM-dd HH:mm:ss";
/**
* yyyy-MM-dd hh:mm:ss
*/
public static final String DATETIME_PATTERN_CONTAINS = "yyyyMMdd HH:mm:ss";
/**
* yyyy-MM-dd hh:mm:ss
*/
public static final String DATETIME_PATTERN_MINUTE = "yyyy-MM-dd HH:mm";
/**
* yyyyMMddHHmmss
*/
public static final String DATE_PATTERN = "yyyyMMddHHmmss";
public static final String EXPORT_PATTERN = "yyyyMMdd-HHmmss";
protected static final float normalizedJulian(float jd) {
return Math.round(jd + 0.5f) - 0.5f;
}
/**
* Returns the Date from a julian. The Julian date will be converted to noon
* GMT, such that it matches the nearest half-integer (i.e., a julian date
* of 1.4 gets changed to 1.5, and 0.9 gets changed to 0.5.)
*
* @param jd the Julian date
* @return the Gregorian date
*/
public static final Date toDate(float jd) {
/*
* To convert a Julian Day Number to a Gregorian date, assume that it is
* for 0 hours, Greenwich time (so that it ends in 0.5). Do the
* following calculations, again dropping the fractional part of all
* multiplicatons and divisions. Note: This method will not give dates
* accurately on the Gregorian Proleptic Calendar, i.e., the calendar
* you get by extending the Gregorian calendar backwards to years
* earlier than 1582. using the Gregorian leap year rules. In
* particular, the method fails if Y<400.
*/
float z = (normalizedJulian(jd)) + 0.5f;
float w = (int) ((z - 1867216.25f) / 36524.25f);
float x = (int) (w / 4f);
float a = z + 1 + w - x;
float b = a + 1524;
float c = (int) ((b - 122.1) / 365.25);
float d = (int) (365.25f * c);
float e = (int) ((b - d) / 30.6001);
float f = (int) (30.6001f * e);
int day = (int) (b - d - f);
int month = (int) (e - 1);
if (month > 12) {
month = month - 12;
}
int year = (int) (c - 4715);
if (month > 2) {
year--;
}
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DATE, day);
return calendar.getTime();
}
/**
* Returns the days between two dates. Positive values indicate that the
* second date is after the first, and negative values indicate, well, the
* opposite. Relying on specific times is problematic.
*
* @param early the "first date"
* @param late the "second date"
* @return the days between the two dates
*/
public static final int daysBetween(Date early, Date late) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(early);
c2.setTime(late);
return daysBetween(c1, c2);
}
/**
* Returns the days between two dates. Positive values indicate that the
* second date is after the first, and negative values indicate, well, the
* opposite.
*
* @param early
* @param late
* @return the days between two dates.
*/
public static final int daysBetween(Calendar early, Calendar late) {
return (int) (toJulian(late) - toJulian(early));
}
/**
* Return a Julian date based on the input parameter. This is based from
* calculations found at
* <a href="http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html">Julian
* Day Calculations (Gregorian Calendar)</a>, provided by Bill Jeffrys.
*
* @param calendar a calendar instance
* @return the julian day number
*/
public static final float toJulian(Calendar calendar) {
int y = calendar.get(Calendar.YEAR);
int m = calendar.get(Calendar.MONTH);
int d = calendar.get(Calendar.DATE);
int a = y / 100;
int b = a / 4;
int c = 2 - a + b;
float e = (int) (365.25f * (y + 4716));
float f = (int) (30.6001f * (m + 1));
return ((c + d + e + f) - 1524.5f);
}
/**
* Return a Julian date based on the input parameter. This is based from
* calculations found at
* <a href="http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html">Julian
* Day Calculations (Gregorian Calendar)</a>, provided by Bill Jeffrys.
*
* @param date
* @return the julian day number
*/
public static final float toJulian(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return toJulian(c);
}
/**
* @param isoString
* @param fmt
* @param field Calendar.YEAR/Calendar.MONTH/Calendar.DATE
* @param amount
* @return
* @throws ParseException
*/
public static final String dateIncrease(String isoString, String fmt, int field, int amount) {
try {
Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(stringToDate2(isoString, fmt));
cal.add(field, amount);
return dateToString(cal.getTime(), fmt);
} catch (Exception ex) {
return null;
}
}
/**
* Time Field Rolling function. Rolls (up/down) a single unit of time on the
* given time field.
*
* @param isoString
* @param field the time field.
* @param up Indicates if rolling up or rolling down the field value.
* use formating char's
* @throws ParseException if an unknown field value is given.
*/
public static final String roll(String isoString, String fmt, int field, boolean up) {
Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(stringToDate(isoString, fmt));
cal.roll(field, up);
return dateToString(cal.getTime(), fmt);
}
/**
* Time Field Rolling function. Rolls (up/down) a single unit of time on the
* given time field.
*
* @param isoString
* @param field the time field.
* @param up Indicates if rolling up or rolling down the field value.
* @throws ParseException if an unknown field value is given.
*/
public static final String roll(String isoString, int field, boolean up){
return roll(isoString, DATETIME_PATTERN_MINUTE, field, up);
}
/**
* java.util.Date
*
* @param dateText
* @param format
* @return
*/
public static Date stringToDate2(String dateText, String format) {
if (dateText == null) {
return null;
}
DateFormat df = null;
try {
if (format == null) {
df = new SimpleDateFormat();
} else {
df = new SimpleDateFormat(ISO_DATE_FORMAT);
}
// setLenient avoids allowing dates like 9/32/2001
// which would otherwise parse to 10/2/2001
df.setLenient(false);
return df.parse( dateText.replace("/","").replace("-","")
.replace(CommonConstants.YEAR,"").replace(CommonConstants.MONTH,"")
.replace(CommonConstants.DAY,""));
} catch (ParseException e) {
return null;
}
}
/**
* @return Timestamp
*/
public static java.sql.Timestamp getCurrentTimestamp() {
return new java.sql.Timestamp(System.currentTimeMillis());
}
/**
* java.util.Date
*
* @param dateString
* @param format
* @return
*/
public static Date stringToDate(String dateString, String format) {
return stringToDate2(dateString, format);
}
/**
* 校验按指定格式是否可以转换成日期
*
* @param @param dateString
* @param @param format
* @param @return 参数
* @return boolean 返回类型
* @throws
* @Title: checkStringToDate
*/
public static boolean checkStringToDate(String dateString, String formatStr) {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
try {
format.setLenient(false);
format.parse(dateString);
} catch (ParseException e) {
return false;
}
return true;
}
/**
* java.util.Date
*
* @param dateString
*/
public static Date stringToDate(String dateString) {
return stringToDate2(dateString, ISO_EXPANDED_DATE_FORMAT);
}
/**
* @param dateString
* @param patten 格式
* @Description:
* @Author: hgw
* @Date: 2022/7/8 12:02
* @return: java.util.Date
**/
public static Date stringToDateByPatten(String dateString, String patten) {
return stringToDate2(dateString, patten);
}
/**
* @param pattern
* @param date
* @return
*/
public static String dateToString(Date date, String pattern) {
if (date == null) {
return null;
}
try {
SimpleDateFormat sfDate = new SimpleDateFormat(pattern);
sfDate.setLenient(false);
return sfDate.format(date);
} catch (Exception e) {
return null;
}
}
/**
* yyyy-MM-dd
*
* @param date
* @return
*/
public static String dateToString(Date date) {
return dateToString(date, ISO_EXPANDED_DATE_FORMAT);
}
/**
* @return
*/
public static Date getCurrentDateTime() {
Calendar calNow = Calendar.getInstance();
return calNow.getTime();
}
/**
* @param pattern
* @return
*/
public static String getCurrentDateString(String pattern) {
return dateToString(getCurrentDateTime(), pattern);
}
/**
* yyyy-MM-dd
*
* @return
*/
public static String getCurrentDateString() {
return dateToString(getCurrentDateTime(), ISO_EXPANDED_DATE_FORMAT);
}
/**
* 返回固定格式的当前时间 yyyy-MM-dd hh:mm:ss
*
* @param
* @return
*/
public static String dateToStringWithTime() {
return dateToString(new Date(), DATETIME_PATTERN_MINUTE);
}
/**
* yyyy-MM-dd hh:mm:ss
*
* @param date
* @return
*/
public static String dateToStringWithTime(Date date) {
return dateToString(date, DATETIME_PATTERN_MINUTE);
}
/**
* yyyyMMdd
*
* @param date
* @return String
*/
public static String dateToStringWithTimeIso(Date date) {
return dateToString(date, ISO_DATE_FORMAT);
}
/**
* @param date
* @param days
* @return java.util.Date
*/
public static Date dateIncreaseByDay(Date date, int days) {
Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(date);
cal.add(Calendar.DATE, days);
return cal.getTime();
}
/**
* @param date
* @param mnt
* @return java.util.Date
*/
public static Date dateIncreaseByMonth(Date date, int mnt) {
Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(date);
cal.add(Calendar.MONTH, mnt);
return cal.getTime();
}
/**
* @param date
* @param mnt
* @return java.util.Date
*/
public static Date dateIncreaseByYear(Date date, int mnt) {
Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(date);
cal.add(Calendar.YEAR, mnt);
return cal.getTime();
}
/**
* @param date yyyy-MM-dd
* @param days
* @return yyyy-MM-dd
*/
public static String dateIncreaseByDay(String date, int days) {
return dateIncreaseByDay(date, ISO_DATE_FORMAT, days);
}
/**
* @param date
* @param fmt
* @param days
* @return
*/
public static String dateIncreaseByDay(String date, String fmt, int days) {
return dateIncrease(date, fmt, Calendar.DATE, days);
}
/**
* @param src
* @param srcfmt
* @param desfmt
* @return
*/
public static String stringToString(String src, String srcfmt, String desfmt) {
return dateToString(stringToDate(src, srcfmt), desfmt);
}
/**
* @param date
* @return string
*/
public static String getYear(Date date) {
SimpleDateFormat formater = new SimpleDateFormat("yyyy");
return formater.format(date);
}
/**
* @param date
* @return string
*/
public static int getYearOfInt(Date date) {
SimpleDateFormat formater = new SimpleDateFormat("yyyy");
return Integer.parseInt(formater.format(date));
}
/**
* @param date
* @return string
*/
public static String getMonth(Date date) {
SimpleDateFormat formater = new SimpleDateFormat("MM");
return formater.format(date);
}
/**
* @param date
* @return string
*/
public static String getDay(Date date) {
SimpleDateFormat formater = new SimpleDateFormat("dd");
return formater.format(date);
}
/**
* @param date
* @return string
*/
public static String getHour(Date date) {
SimpleDateFormat formater = new SimpleDateFormat("HH");
return formater.format(date);
}
public static int getMinsFromDate(Date dt) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dt);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
return ((hour * 60) + min);
}
/**
* Function to convert String to Date Object. If invalid input then current
* or next day date is returned (Added by Ali Naqvi on 2006-5-16).
*
* @param str String input in YYYY-MM-DD HH:MM[:SS] format.
* @param isExpiry boolean if set and input string is invalid then next day date
* is returned
* @return Date
*/
public static Date convertToDate(String str, boolean isExpiry) {
SimpleDateFormat fmt = new SimpleDateFormat(DATETIME_PATTERN_MINUTE);
Date dt = null;
try {
dt = fmt.parse(str);
} catch (ParseException ex) {
Calendar cal = Calendar.getInstance();
if (isExpiry) {
cal.add(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
} else {
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
}
dt = cal.getTime();
}
return dt;
}
public static Date convertToDate(String str) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date dt = null;
try {
dt = fmt.parse(str);
} catch (ParseException ex) {
dt = new Date();
}
return dt;
}
public static String dateFromat(Date date, int minute) {
String dateFormat = null;
int year = Integer.parseInt(getYear(date));
int month = Integer.parseInt(getMonth(date));
int day = Integer.parseInt(getDay(date));
int hour = minute / 60;
int min = minute % 60;
dateFormat = year + (month > 9 ? String.valueOf(month) : "0" + month + "")
+ (day > 9 ? String.valueOf(day) : "0" + day) + " "
+ (hour > 9 ? String.valueOf(hour) : "0" + hour)
+ (min > 9 ? String.valueOf(min) : "0" + min) + "00";
return dateFormat;
}
public static String sDateFormat() {
return new SimpleDateFormat(DATE_PATTERN).format(Calendar.getInstance().getTime());
}
/**
* 判断是否为有效时间格式
*
* @param str
* @return
*/
public static Boolean valid(String str) {
Boolean result = false;
if (null != str) {
for (String Pattern : parsePatterns) {
if (Pattern.equals(str)) {
result = true;
break;
}
}
}
return result;
}
/**
* 返回一个有效时间格式串若自身无效则返回"yyyy-MM-dd"
*
* @param str
* @return
*/
public static String validAndReturn(String str) {
String result = ISO_EXPANDED_DATE_FORMAT;
if (valid(str)) {
result = str;
}
return result;
}
/**
* 根据type返回时间差(除不尽加1)
*
* @param end 结束时间
* @param begin 开始时间
* @param type 返回类型1秒2分3小时4天(type其他值都返回秒)
* @return
*/
public static long getSubTime(Date end, Date begin, Integer type) {
long between = 0;
if (end != null && begin != null) {
try {
// 得到两者的毫秒数
between = (end.getTime() - begin.getTime());
} catch (Exception ex) {
log.error("根据type返回时间差",ex);
}
return initSubTime(type, between);
} else {
return between;
}
}
private static long initSubTime(Integer type, long between) {
if (null == type) {
return between;
} else if (type == 2) {
long min = (between / (60 * 1000));
if (between % (60 * 1000) != 0) {
min++;
}
return min;
} else if (type == 3) {
long hour = (between / (60 * 60 * 1000));
if (between % (60 * 60 * 1000) != 0) {
hour++;
}
return hour;
} else if (type == 4) {
long day = between / (24 * 60 * 60 * 1000);
if (between % (24 * 60 * 60 * 1000) != 0) {
day++;
}
return day;
} else {
return between;
}
}
/**
* 已当月为基准往前退 i+1 个生成月份格式:YYYYMMDD 未完善
*
* @param @param i
* @param @return 参数
* @return String 返回类型
* @throws
* @Title: getMonthByNum
* @Description:
*/
public static List<MonthObject> getMonthByNum(int i, int endDate) {
List<MonthObject> socailStartList = new ArrayList<>();
MonthObject temp = null;
MonthObject temp2 = null;
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
// 取时间
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
if (endDate <= Integer.parseInt(DateUtil.getDay(date))) {
// 把日期往后增加一个月.整数往后推,负数往前移动
calendar.add(Calendar.MONTH, 2);
} else {
// 把日期往后增加一个月.整数往后推,负数往前移动
calendar.add(Calendar.MONTH, 1);
}
temp2 = new MonthObject();
temp2.setMonth(sdf.format(calendar.getTime()));
date = calendar.getTime();
socailStartList.add(temp2);
for (int x = 1; x <= i; x++) {
calendar.setTime(date);
calendar.add(Calendar.MONTH, -x);
temp = new MonthObject();
temp.setMonth(sdf.format(calendar.getTime()));
socailStartList.add(temp);
}
return socailStartList;
}
/**
* 获得指定月份的日期
*
* @param i
* @return
* @Author fxj
* @Date 2019-09-18
**/
public static Date getDateByMonthNum(int i) {
// 取时间
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
// 把日期往后增加一个月.整数往后推,负数往前移动
calendar.add(Calendar.MONTH, i);
return calendar.getTime();
}
/**
* @param @param i
* @param @return 参数
* @return List<MonthObject> 返回类型
* @throws
* @Title: getFutureMonthByNum
* @Description: (已当前月份未基准往后退 i + 1个月份)
*/
public static List<MonthObject> getFutureMonthByNum(int k, int endDate) {
List<MonthObject> socailStartList = new ArrayList<>();
MonthObject temp = null;
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
Date date = new Date();//取时间
Calendar calendar = new GregorianCalendar();
int j = 0;
if (endDate <= Integer.parseInt(DateUtil.getDay(date))) {
j = 2;
} else {
j = 1;
}
for (int x = j; x < k; x++) {
calendar.setTime(date);
calendar.add(Calendar.MONTH, x);
temp = new MonthObject();
temp.setMonth(sdf.format(calendar.getTime()));
socailStartList.add(temp);
}
return socailStartList;
}
public static List<Date> getDateListByStartEndDate(Date startDate, Date endDate) {
List<Date> lstDate = new ArrayList<>();
lstDate.add(startDate);
if (startDate.equals(endDate)) {
return lstDate;
}
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
Calendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
for (int i = 1; i > 0; i = 1) {
calendar.add(Calendar.MONTH, i);
try {
if (sdf.format(calendar.getTime()).equals(sdf.format(endDate))) {
lstDate.add(sdf.parse(sdf.format(calendar.getTime())));
break;
}
lstDate.add(sdf.parse(sdf.format(calendar.getTime())));
} catch (ParseException e) {
log.error("getDateListByStartEndDate",e);
}
}
return lstDate;
}
/**
* @param @param startDate 起缴日期
* @param @param backNum 补缴月份
* @param @param type 补缴类型 1.当月缴纳当月 2.当月缴纳次月
* @param @return 参数
* @return boolean 返回类型
* @throws
* @Title: checkStartDate
* @Description: (判断日期是否在指定的日期范围内)
*/
public static boolean checkStartDate(Date startDate, int backNum, int type) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(new Date());
Date temp = null;
if (type == 1) {
calendar.add(Calendar.MONTH, backNum);
} else if (type == 2) {
calendar.add(Calendar.MONTH, backNum - 1);
}
temp = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
try {
// 当startDate 在temp 前 返回false
if (!startDate.before(sdf.parse(sdf.format(temp)))) {
return true;
}
} catch (ParseException e) {
return true;
}
return false;
}
/**
* @param startDate
* @param endDate
* @Description: 计算年月的月份差值(202205-202205=0,202205-202105=12)想要1自己+1 年月差值
* @Author: hgw
* @Date: 2022/7/15 12:16
* @return: int
**/
public static int getMonthDiff(Date startDate, Date endDate) {
try {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(startDate);
c2.setTime(endDate);
return 12 * (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
} catch (IllegalFormatException e) {
log.error("计算日期月份差,方法名:getMonthDiff,出错:",e);
return 0;
}
}
public static int getMonthCountByDate(Date startDate, Date endDate) {
// type:1.当月缴当月的 2.当月缴次月的
int monthC = 0;
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
if (endDate == null) {
endDate = new Date();
}
try {
monthC = getMonthSpace(sdf.format(startDate), sdf.format(endDate));
monthC = monthC + 1;
} catch (ParseException e) {
log.error("getMonthCountByDate",e);
return 0;
}
return monthC;
}
/**
* @param date1 <String>
* @param date2 <String>
* @return int
* @throws ParseException
*/
public static int getMonthSpace(String date1, String date2)
throws ParseException {
int result = 0;
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(sdf.parse(date1));
c2.setTime(sdf.parse(date2));
result = 12 * (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
return result / 1;
}
/**
* @param date1 <String>
* @param date2 <String>
* @return int
* @throws ParseException
*/
public static int getYearSpace(String date1, String date2)
throws ParseException {
int result = 0;
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(sdf.parse(date1));
c2.setTime(sdf.parse(date2));
result = 1 * (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) + (c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH))/12;
return result / 1;
}
/**
* 获取任意时间的月的最后一天
* 描述:<描述函数实现的功能>.
*
* @param repeatDate
* @return
*/
public static String getMaxMonthDate(String repeatDate) {
SimpleDateFormat dft = new SimpleDateFormat(ISO_DATE_FORMAT);
Calendar calendar = Calendar.getInstance();
try {
if (StringUtils.isNotBlank(repeatDate) && !"null".equals(repeatDate)) {
calendar.setTime(dft.parse(repeatDate));
}
} catch (ParseException e) {
log.error("getMaxMonthDate",e);
}
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
return dft.format(calendar.getTime());
}
public static Date getMaxDayOfMonth(Date temp) {
SimpleDateFormat sdf = new SimpleDateFormat(ISO_DATE_FORMAT);
String dateStr = sdf.format(temp);
dateStr = getMaxMonthDate(dateStr);
Date res = null;
try {
res = sdf.parse(dateStr);
} catch (ParseException e) {
log.error("getMaxDayOfMonth",e);
}
return res;
}
public static Integer getDateOfNow() {
Calendar now = Calendar.getInstance();
return now.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取i年后的时间自动 -1天
* @param @param date
* @param @param i
* @param @return
* @param @throws ParseException 参数
* @return String 返回类型
* @throws
* @Title: getMonthSpace
* @Description: (获取指定日期后指定 (i 个年的时间)
*/
public static String getDateStr(Date date, int i) {
String str = "";
Calendar c1 = Calendar.getInstance();
c1.setTime(date);
c1.set(Calendar.YEAR,c1.get(Calendar.YEAR)+i);
c1.set(Calendar.DAY_OF_MONTH,c1.get(Calendar.DAY_OF_MONTH) -1);
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH)+1;
int day = c1.get(Calendar.DAY_OF_MONTH);
str = year +""+ (month < 10 ? "0" + month : month) + (day < 10 ? "0" + day : day);
return str;
}
/**
* 获取指定月份
* @Author fxj
* @Date 2019-10-16
* @param yearMonth 格式 :YYYYMM
* @param i
* @return
* @Description (获取指定日期后指定 ( i)个月的时间YYYYMM)
**/
public static String getYearAndMonth(String yearMonth,int i){
if (!Common.isNotNull(yearMonth) || yearMonth.length() != 6 || !Common.isNumber(yearMonth)){
return null;
}
Calendar c1 = Calendar.getInstance();
c1.set(Integer.valueOf(yearMonth.substring(0,4)),Integer.valueOf(yearMonth.substring(4,6)),1);
c1.set(Calendar.MONTH,c1.get(Calendar.MONTH) + i);
String str ="";
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
if (month == 0){
year = year -1;
month = month + 12;
str = year + (month < 10 ? "0" + month: month + "");
}else{
str = year + (month < 10 ? "0" + month : month + "");
}
return str;
}
/**
* 获取指定月份
* @Author fxj
* @Date 2019-10-16
* @param yearMonth 格式 :LocalDateTime
* @param i
* @return
* @Description (获取指定日期后指定 ( i)个月的时间YYYYMM)
**/
public static String getYearAndMonth(LocalDateTime yearMonth, int i){
String str ="";
if(yearMonth != null) {
Calendar c1 = Calendar.getInstance();
c1.set(yearMonth.getYear(),yearMonth.getMonthValue(),1);
c1.set(Calendar.MONTH,c1.get(Calendar.MONTH) + i );
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
if (month == 0){
year = year -1;
month = month + 12;
str = year + (month < 10 ? "0" + month : Integer.toString(month));
}else{
str = year + (month < 10 ? "0" + month : Integer.toString(month));
}
}
return str;
}
/**
* @param i 加减年份
* @Description: 获取当前年月,对年月加减(yyyyMM)
* @Author: hgw
* @Date: 2019/10/29 17:13
* @return: java.lang.String
**/
public static String getYearMonthByAddYear(int i){
Calendar c1 = Calendar.getInstance();
c1.set(Calendar.YEAR,c1.get(Calendar.YEAR) + i);
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
return sdf.format(c1.getTime());
}
/**
* 获取第一天
* @Author fxj
* @Date 2019-10-16
* @param yearMonth YYYYMM
* @return
**/
public static Date getFirstDay(String yearMonth){
if (!Common.isNotNull(yearMonth) || yearMonth.length() != 6 || !Common.isNumber(yearMonth)){
return null;
}
Calendar c1 = Calendar.getInstance();
c1.set(Integer.valueOf(yearMonth.substring(0,4)),Integer.valueOf(yearMonth.substring(4,6))-1,1);
return c1.getTime();
}
/**
* 获取第一天
* @Author fxj
* @Date 2019-10-16
* @param yearMonth YYYYMM
* @return
**/
public static String getFirstDayString(String yearMonth){
return yearMonth.substring(0,4)+"-"+yearMonth.substring(4,6)+"-01";
}
/**
* 当月第一天
* @Author fxj
* @Date 2021-01-05
* @param
* @return
* @see com.yifu.cloud.v1.common.core.util
**/
public static LocalDateTime getFirstDay(){
return LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth());
}
/**
* 获取最后一天
* @Author fxj
* @Date 2019-10-16
* @param yearMonth YYYYMM
* @return
**/
public static Date getLastDay(String yearMonth){
if (!Common.isNotNull(yearMonth) || yearMonth.length() != 6 || !Common.isNumber(yearMonth)){
return null;
}
Calendar c1 = Calendar.getInstance();
c1.set(Integer.valueOf(yearMonth.substring(0,4)),Integer.valueOf(yearMonth.substring(4,6))-1,c1.getActualMaximum(Calendar.DAY_OF_MONTH));
return c1.getTime();
}
/**
* 根据指定的格式将字符串转换成Date 如输入:2003-11-19 11:20:20将按照这个转成时间
*
* @param src 将要转换的原始字符窜
* @param pattern 转换的匹配格式
* @return 如果转换成功则返回转换后的日期
* @throws ParseException
*/
public static Date parseDate(String src, String pattern) throws ParseException {
return getSDFormat(pattern).parse(src);
}
// 指定模式的时间格式
private static SimpleDateFormat getSDFormat(String pattern) {
return new SimpleDateFormat(pattern);
}
/**
* 指定日期的默认显示,具体格式:年-月-日
*
* @param date 指定的日期
* @return 指定日期按“年-月-日“格式显示
*/
public static String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(ISO_EXPANDED_DATE_FORMAT);
return sdf.format(date);
}
/**
* @param date
* @param patten
* @Description: 按指定格式返回
* @Author: hgw
* @Date: 2022/7/19 17:10
* @return: java.lang.String
**/
public static String formatDatePatten(Date date, String patten) {
if (Common.isEmpty(patten)) {
patten = DATETIME_YYYYMM;
}
SimpleDateFormat sdf = new SimpleDateFormat(patten);
return sdf.format(date);
}
/**
* @param date
* @Description: 按指定格式返回int
* @Author: hgw
* @Date: 2022/7/19 17:13
* @return: java.lang.Integer
**/
public static Integer formatDateInt(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
return Integer.parseInt(sdf.format(date));
}
/**
* @param mnt 增减月份的 值
* @param yearMonth 202101
* @Description: 增减月份
* @Author: hgw
* @Date: 2019/9/17 10:15
* @return: java.lang.String
**/
public static String addMonthByYearMonth(int mnt, String yearMonth) {
Calendar cal = Calendar.getInstance();
cal.set(Integer.valueOf(yearMonth.substring(0,4)),Integer.valueOf(yearMonth.substring(4,6))-1,1);
cal.add(Calendar.MONTH, mnt);
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
return sdf.format(cal.getTime());
}
/**
* @param mnt 增减月份的 值
* @param yearToMonth 2021-01
* @Description: 增减月份
* @Author: hgw
* @Date: 2019/9/17 10:15
* @return: java.lang.String
**/
public static String addMonthByYearToMonth(int mnt, String yearToMonth) {
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(yearToMonth.substring(0,4)),Integer.parseInt(yearToMonth.substring(5,7))-1,1);
cal.add(Calendar.MONTH, mnt);
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYY_MM);
return sdf.format(cal.getTime());
}
/**
* @param yearToMonth 2021-01
* @Description: 比较年月大小
* @Author: hgw
* @Date: 2021/4/27 14:55
* @return: boolean
**/
public static int paseYearToMonth(String yearToMonth) {
return Integer.parseInt(yearToMonth.substring(0,4) + yearToMonth.substring(5,7));
}
/**
* @param mnt 增减月份的 值
* @Description: 增减月份
* @Author: hgw
* @Date: 2019/9/17 10:15
* @return: java.lang.String
**/
public static String addMonth(int mnt) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, mnt);
SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_YYYYMM);
return sdf.format(cal.getTime());
}
/**
* @Description: 增减(月)
* @Author: hgw
* @Date: 2022/8/3 9:17
* @return: java.util.Date
**/
public static Date addMonthByDate(Date date, int mnt) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.MONTH, mnt);
return cal.getTime();
}
/**
* @Description: 增减(日)
* @Author: hgw
* @Date: 2022/8/3 9:17
* @return: java.util.Date
**/
public static Date addDayByDate(Date date, int mnt) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.DATE, mnt);
return cal.getTime();
}
/**
* @param mnt 增减日的 值
* @Description: 增减日
* @Author: hgw
* @Date: 2021-7-15 11:36:23
* @return: java.lang.String
**/
public static String addDay(int mnt) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, mnt);
SimpleDateFormat sdf = new SimpleDateFormat(ISO_EXPANDED_DATE_FORMAT);
return sdf.format(cal.getTime());
}
/**
* @param taxYearMonth 计税月
* @Description: 根据计税年月返回个税扣除额
* @Author: hgw
* @Date: 2019/9/19 16:02
* @return: double
**/
public static BigDecimal getTaxMonthMoney(String taxYearMonth) {
try {
int taxYear = Integer.parseInt(taxYearMonth.substring(0, 4));
int taxMonth = Integer.parseInt(taxYearMonth.substring(4, 6));
int nowYear = Integer.parseInt(DateFormatUtils.format(new Date(), "yyyy"));
int nowMonth = Integer.parseInt(DateFormatUtils.format(new Date(), "MM"));
// 同一个计税年
if (nowYear - taxYear == 0) {
return new BigDecimal((nowMonth - taxMonth + 1) * 5000);
// 前一个计税年
} else if (nowYear - taxYear > 0) {
// 禅道461:王成说的。
return new BigDecimal((nowMonth) * 5000);
} else {
// 比当前年还大
return new BigDecimal(0);
}
} catch (Exception e) {
log.error("getTaxMonthMoney",e);
}
return new BigDecimal(0);
}
/**
* <p>Description: 返回最大值月份</p>
* @author hgw
* @Date 2019年4月29日下午6:52:41
* @param taxMonth
* @return
*/
/**
* @param taxMonth
* @Description: 返回起始计税月(例如:计税月是今年之前的,则取值今年1月,否则=计税月)
* @Author: hgw
* @Date: 2019/9/30 18:16
* @return: java.lang.String
**/
public static String getMaxYearMonth(String taxMonth) {
if (Common.isNotNull(taxMonth) && taxMonth.length() >= 6) {
taxMonth = taxMonth.substring(0, 6);
String nowYearMonth = getCurrentDateString("yyyy") + "01";
int nowYearMonthInt = Integer.parseInt(nowYearMonth);
if (Integer.parseInt(taxMonth) > nowYearMonthInt) {
return taxMonth;
} else {
return nowYearMonth;
}
}
return null;
}
/**
* <p>Description: 返回年月</p>
* @author hgw
* @Date 2019年5月16日下午6:39:02
* @param currentMonth
* @return
*/
public static String getYearMonth(String currentMonth) {
if (Common.isNotNull(currentMonth) && currentMonth.length() > 5) {
if (currentMonth.indexOf('-') >= 0) {
currentMonth = currentMonth.replace("-", "");
}
return currentMonth.substring(0,4) + currentMonth.substring(4,6);
}
return null;
}
/**
*
* @Author fxj
* @Date 2019-11-20
* @param backMonths 补缴月份数
* @param haveThisMonth 0是1否 补缴是否含当月 含当月 补缴月份数 -1 不含当月补缴月数不变
* @param isBack 0是1否 是否补缴 不补缴默认从当前月开始 至次月
* @return
**/
public static List<String> getMonthsForSocialAndFund(int isBack,int backMonths,int haveThisMonth){
List<String> months = new ArrayList<>();
int count = 0;
//补缴
if (isBack==0){
//含当月
if (haveThisMonth == 0){
count = backMonths-1;
//不含当月
}else if (haveThisMonth == 1){
count = backMonths;
}
}
LocalDateTime now = LocalDateTime.now();
while (count >= 0){
months.add(getYearAndMonth(now,-count));
count--;
}
months.add(getYearAndMonth(now,1));
return months;
}
/**
* @param cur
* @param to
* @Description: 比较月份大小
* @Author: hgw
* @Date: 2019/11/25 18:18
* @return: int
**/
public static int compareMonth(LocalDateTime cur, LocalDateTime to) {
return (cur.getYear() - to.getYear()) * 12 + (cur.getMonthValue() - to.getMonthValue());
}
/**
* @param a 第一个年月
* @param b 第二个年月
* @Description: 比较a和b的大小,a大,则返回true;
* @Author: hgw
* @Date: 2020/10/16 15:44
* @return: boolean
**/
public static boolean compareYearMonth(String a, String b) {
try {
if (a != null && b != null && !"".equals(a) && !"".equals(b) && a.length() == 6 && b.length() == 6) {
int aInt = Integer.parseInt(a.substring(0, 4));
int bInt = Integer.parseInt(b.substring(0, 4));
if (aInt > bInt) {
return true;
} else if (aInt < bInt) {
return false;
} else {
aInt = Integer.parseInt(a.substring(4, 6));
bInt = Integer.parseInt(b.substring(4, 6));
return aInt > bInt;
}
}
return true;
} catch (NumberFormatException e) {
return true;
}
}
/**
* @param
* @Author: wangan
* @Date: 2020/12/21
* @Description: 获取这个月
* @return: java.lang.String
**/
public static String getThisMonth(){
SimpleDateFormat sf = new SimpleDateFormat(DateUtil.DATETIME_YYYYMM);
Date nowDate = new Date();
String thisMonth = sf.format(nowDate);
return thisMonth;
}
/**
* @param years 出生年
* @Description: 获取年龄
* @Author: hgw
* @Date: 2022/6/24 16:49
* @return: int
**/
public static int getAge(int years){
SimpleDateFormat sf = new SimpleDateFormat(DateUtil.DATETIME_YYYY);
Date nowDate = new Date();
int thisYear = Integer.parseInt(sf.format(nowDate));
return thisYear - years + 1;
}
/**
* @Description: 返回当前年月日字符串
* @Author: hgw
* @Date: 2022/6/21 17:19
* @return: java.lang.String
**/
public static String getThisDay(){
SimpleDateFormat sf = new SimpleDateFormat(DateUtil.ISO_DATE_FORMAT);
return sf.format(new Date());
}
/**
* @Description: 返回当前年月日时分秒字符串(一般用在导出文件名)
* @Author: hgw
* @Date: 2022-6-24 10:00:41
* @return: java.lang.String
**/
public static String getThisTime(){
SimpleDateFormat sf = new SimpleDateFormat(DateUtil.EXPORT_PATTERN);
return sf.format(new Date());
}
/**
* @param
* @Author: wangan
* @Date: 2020/12/21
* @Description: 获取上个月
* @return: java.lang.String
**/
public static String getLastMonth(){
SimpleDateFormat sf = new SimpleDateFormat(DateUtil.DATETIME_YYYYMM);
Date nowDate = new Date();
Calendar instance = Calendar.getInstance();
instance.setTime(nowDate);
instance.add(Calendar.MONTH, -1);
String lastMonth = sf.format(instance.getTime());
return lastMonth;
}
/**
* @param
* @Author: wangan
* @Date: 2020/12/21
* @Description: 获取上n个月
* @return: java.lang.String
**/
public static String getLastXMonth(int month){
SimpleDateFormat sf = new SimpleDateFormat(DateUtil.DATETIME_YYYYMM);
Date nowDate = new Date();
Calendar instance = Calendar.getInstance();
instance.setTime(nowDate);
instance.add(Calendar.MONTH, month);
return sf.format(instance.getTime());
}
/**
* @param yearMonth 年月(例:202201)
* @param month 增减数值(例:1,或 -1)
* @Description: String年月,根据month增减,大多数为了获取下月或上月使用
* @Author: hgw
* @Date: 2022/3/31 20:43
* @return: java.lang.String
**/
public static String addMonthByString(String yearMonth, int month) {
if (Common.isNotNull(yearMonth)) {
try {
SimpleDateFormat sf = new SimpleDateFormat(DateUtil.DATETIME_YYYYMM);
Date d1 = sf.parse(yearMonth);
Calendar instance = Calendar.getInstance();
instance.setTime(d1);
instance.add(Calendar.MONTH, month);
return sf.format(instance.getTime());
} catch (ParseException e) {
return null;
}
} else {
return null;
}
}
}
package com.yifu.cloud.plus.v1.yifu.common.core.util;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ExcelAttribute;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ValidityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ExcelException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
/**
* @Author fxj
* @Date 2022/6/23
* @Description
* @Version 1.0
*/
@Data
@Slf4j
public class ExcelUtil <T> implements Serializable {
private Class<T> clazz;
/**
* 用于返回错误信息
*/
private List<ErrorMessage> errorInfo;
private HashMap<Integer, ErrorMessage> errorMessageHashMap;
/**
* 用于返回实体
*/
private List<T> entityList;
public ExcelUtil(Class<T> clazz) {
this.clazz = clazz;
this.fields =clazz.getDeclaredFields();
}
private Field[] fields;
public void convertEntity(T vo, String[] exportFields, Map<String,String> diyDicMap, String dateFormat) {
// 得到所有定义字段
Field[] allFields = clazz.getDeclaredFields();
List<Field> fields = new ArrayList<>();
Class<?> superClazz = clazz.getSuperclass();
// 将需要字典表头存起来备用,如果没传,则全部翻译
List<String> allField = new ArrayList<>();
ExcelAttribute annotation;
for (Field field : allFields) {
if (field.isAnnotationPresent(ExcelAttribute.class)) {
fields.add(field);
annotation = field.getAnnotation(ExcelAttribute.class);
if (annotation != null && Common.isNotNull(annotation.name())) {
allField.add(annotation.name());
}
}
}
if (Common.isEmpty(exportFields) && !allField.isEmpty()) {
exportFields = new String[allField.size()];
for (int i = 0; i < allField.size(); i++) {
exportFields[i] = allField.get(i);
}
}
if (superClazz != null) {
Field[] superFields = superClazz.getDeclaredFields();
for (Field field : superFields) {
if (field.isAnnotationPresent(ExcelAttribute.class)) {
fields.add(field);
}
}
}
fields = getFiledsByParamFiled(fields, exportFields);
ExcelAttribute attr;
Field field;
//分割符
String divider;
for (int j = 0; j < fields.size(); j++) {
// 获得field
field = fields.get(j);
// 设置实体类私有属性可访问
field.setAccessible(true);
attr = field.getAnnotation(ExcelAttribute.class);
if (attr.isExport()) {
// 如果数据存在就填入,不存在填入空格
Class<?> classType = field.getType();
String value = null;
Date date;
try {
if (field.get(vo) != null && (classType.isAssignableFrom(Date.class) || classType.isAssignableFrom(LocalDateTime.class) || classType.isAssignableFrom(LocalDate.class))) {
if (Common.isNotNull(attr.dateFormatExport())) {
date = DateUtil.stringToDate2(String.valueOf(field.get(vo)), attr.dateFormatExport());
if (classType.isAssignableFrom(LocalDateTime.class)){
value = LocalDateTimeUtils.formatTime((LocalDateTime)field.get(vo),attr.dateFormatExport());
}else {
value = DateUtil.dateToString(date, attr.dateFormatExport());
}
} else {
date = DateUtil.stringToDate2(String.valueOf(field.get(vo)), !Common.isNotNull(dateFormat) ? DateUtil.ISO_EXPANDED_DATE_FORMAT : dateFormat);
if (classType.isAssignableFrom(LocalDateTime.class)){
value = LocalDateTimeUtils.formatTime((LocalDateTime)field.get(vo),!Common.isNotNull(dateFormat) ? DateUtil.ISO_EXPANDED_DATE_FORMAT : dateFormat);
}else {
value = cn.hutool.core.date.DateUtil.format(date, !Common.isNotNull(dateFormat) ? DateUtil.ISO_EXPANDED_DATE_FORMAT : dateFormat);
}
}
}
//如果有默认字典数据直接取值
if (Common.isNotNull(attr.readConverterExp())) {
value = convertByExp(field.get(vo) == null ? "" : String.valueOf(field.get(vo)), attr.readConverterExp());
} else if (attr.isDataId()) {
//加入分割符逻辑
divider = attr.divider();
if (!"".equals(divider) && field.get(vo) != null){
try {
value = "";
for(String key : String.valueOf(field.get(vo)).split(divider)){
value += getLableById(attr, diyDicMap, key) + divider;
}
if(Common.isNotNull(value)){
value = value.substring(0,value.length()-1);
}
}catch (Exception e){
log.error("excel数据导出字符切割错误",e);
value = "字符切割错误";
}
} else {
//如果是字典数据ID或区域ID 去dicMap(包含了区域) 取值 取不到返回空
value = getLableById(attr, diyDicMap, field.get(vo) == null ? "" : String.valueOf(field.get(vo)));
}
} else if (attr.isArea()){
//区域字段处理 TODO
value = getAreaLabel((String) field.get(vo));
}
field.set(vo, Common.isNotNull(value)?value:field.get(vo));
}catch (Exception e){
log.error("字典数据解析异常");
}
}
}
}
/**
* 通过标志_字典ID的方式去dicMap 取值
*
* @param attr
* @param dicMap 字典值 key: 类型标识_ID value:实际要导出的内容
* @param value 对应字段的ID值
* @return
* @Author fxj
* @Date 2019-08-06
**/
private String getLableById(ExcelAttribute attr, Map<String, String> dicMap, String value) {
String tempValue = null;
if (null != dicMap && dicMap.size() > 0 && Common.isNotNull(value)) {
if (Common.isNotNull(attr.dataType())) {
tempValue = dicMap.get(attr.dataType() + CommonConstants.DOWN_LINE_STRING + value);
if (Common.isEmpty(tempValue)){
tempValue = dicMap.get(attr.dataType() + CommonConstants.DOWN_LINE_STRING +"id"+CommonConstants.DOWN_LINE_STRING + value);
}
} else {
tempValue = dicMap.get(value);
}
}
// 默认字典获取不到 去 缓存获取
if (Common.isEmpty(tempValue) && Common.isNotNull(attr.dataType())){
Map<String,String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue()
.get(CacheConstants.DICT_DETAILS
+ CommonConstants.COLON_STRING
+attr.dataType());
if (dicObj != null) {
for (Map.Entry<String, String> entry : dicObj.entrySet()) {
if (Common.isNotNull(entry.getKey()) && entry.getKey().equals(value.trim())) {
tempValue = entry.getValue();
break;
}
}
}
}
return tempValue;
}
/**
* 返回传参对应的fileds
*
* @param fields
* @param paramFields
* @return
* @Author fxj
* @Date 2019-08-05
**/
private List<Field> getFiledsByParamFiled(List<Field> fields, String[] paramFields) {
List<Field> fieldsTemp = new ArrayList<Field>();
List<String> attrName = new ArrayList();//存中文名 wangan修改
if (null != paramFields && paramFields.length > 0) {
ExcelAttribute attr;
Field field;
for (int j = 0; j < paramFields.length; j++) {
for (int i = 0; i < fields.size(); i++) {
field = fields.get(i);
attr = field.getAnnotation(ExcelAttribute.class);
//如果有同样的中文名数据字段,后面不再添加。 wangan修改
if (!attrName.contains(attr.name())) {
if (attr.name().equals(paramFields[j])) {
fieldsTemp.add(field);
attrName.add(attr.name());
break;
}
}
}
}
} else {
return fields;
}
return fieldsTemp;
}
public ErrorMessage checkEntity(T data , Integer rowNum) {
if (!Common.isNotNull(fields)){
return null;
}
//存储错误数据
Class<?> fieldType;
String error = "";
String c = null;
//临时存储单元格数据
String tempStr = "";
ErrorMessage errorTemp = null;
errorMessageHashMap = new HashMap<>();
Map<String,Field> mapArea = new HashMap<>();
// 参数校验
ExcelAttribute attr = null;
try{
for (Field field : fields) {
if (field == null) {
continue;
}
tempStr=null;
// 设置实体类私有属性可访问
field.setAccessible(true);
attr = field.getAnnotation(ExcelAttribute.class);
if (Common.isEmpty(attr)){
continue;
}
// 单元格中的内容.
c = getStringValByObject(field.get(data));
if (c != null) {
c = c.trim();
}
//校验字段是否符合要求 返回错误信息
error = validateUtil(c, attr, rowNum);
if (null != error) {
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(rowNum, error), errorTemp);
continue;
}
//单元格数据为空不需要处理了
if (!StringUtils.isNotBlank(c)) {
continue;
}
//如果是需要从字典表取值数据的话在这里处理即可
if (Common.isNotNull(attr.readConverterExp())) {
tempStr= reverseByExp( c, attr.readConverterExp());
if (Common.isEmpty(tempStr)){
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(rowNum, "未找到:" + c + "的字典数据"), errorTemp);
continue;
}else {
c = tempStr;
}
} else if (attr.isDataId()) {
if (Common.isNotNull(attr.dataType())) {
//非区域字段处理 TODO
tempStr = getDicValue(c, tempStr, attr,rowNum,errorTemp);
/*if (Common.isNotNull(attr.parentField())){
tempStr = dicMap.get(attr.dataType() + "_" + c.trim() + "_" + getFieldValueByName(attr.parentField(), entity, DateUtil.ISO_EXPANDED_DATE_FORMAT));
}else {
tempStr = dicMap.get(attr.dataType() + "_" + c.trim());
}*/
}
}else {
if (attr.isArea()) {
//区域字段处理 TODO
if (!Common.isNotNull(attr.parentField())) {
tempStr = getAreaValue(c.trim(), tempStr, attr,rowNum,errorTemp);
} else {
// TODO
tempStr = getAreaValue(c.trim()+ "_" + getFieldValueByName(attr.parentField(), data, DateUtil.ISO_EXPANDED_DATE_FORMAT), tempStr, attr,rowNum,errorTemp);
}
}
}
if (StringUtils.isEmpty(tempStr) && (attr.isArea() || attr.isDataId())) {
if (attr.isOrgan()) {
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(rowNum, "未找到:" + c + "的单位或项目数据,请确认存在项目权限"), errorTemp);
}
if (attr.isArea()) {
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(rowNum, "未找到:" + c + "的区域数据"), errorTemp);
} else {
if (Common.isNotNull(attr.errorInfoImport())) {
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(rowNum, "数据'" + c + "':" + attr.errorInfoImport()), errorTemp);
} else {
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(rowNum, "未找到:" + c + "的字典数据"), errorTemp);
}
}
continue;
}
if (Common.isNotNull(tempStr)){
c = tempStr;
mapArea.put(tempStr+CommonConstants.DOWN_LINE_STRING+attr.name(),field);
}
// 取得类型,并根据对象类型设置值.
fieldType = field.getType();
if (fieldType == null) {
continue;
}
if (attr.isArea()){
// 区域字段单独处理
continue;
}else if (String.class == fieldType) {
field.set(data, c);
} else if (BigDecimal.class == fieldType) {
c = c.indexOf('%') != -1 ? c.replace("%", "") : c;
field.set(data, BigDecimal.valueOf(Double.valueOf(c)));
} else if (Date.class == fieldType && Common.isNotNull(c.trim())) {
field.set(data, DateUtil.parseDate(c.trim(), Common.isEmpty(attr.dateFormat()) ? DateUtil.ISO_EXPANDED_DATE_FORMAT : attr.dateFormat()));
} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
field.set(data, Integer.parseInt(c));
} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
field.set(data, Long.valueOf(c));
} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
field.set(data, Float.valueOf(c));
} else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
field.set(data, Short.valueOf(c));
} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
field.set(data, Double.valueOf(c));
} else if (Character.TYPE == fieldType) {
if ((c != null) && (c.length() > 0)) {
field.set(data, Character.valueOf(c.charAt(0)));
}
} else if (LocalDateTime.class == fieldType && Common.isNotNull(c.trim())) {
String dc = c.trim().replace(CommonConstants.CENTER_SPLIT_LINE_STRING, "")
.replace(CommonConstants.SLASH_SPLIT_LINE_STRING, "");
try {
if (dc.length() > CommonConstants.EIGHT_INT) {
field.set(data, LocalDateTimeUtils.convertDateToLDT(DateUtil.stringToDate(dc, DateUtil.DATETIME_PATTERN_CONTAINS)));
}else {
field.set(data, LocalDateTimeUtils.convertDateToLDT(DateUtil.stringToDate(dc, DateUtil.ISO_DATE_FORMAT)));
}
} catch (Exception e) {
if (dc.length() > CommonConstants.EIGHT_INT) {
errorMessageHashMap = initErrorMessage(errorMessageHashMap,
new ErrorMessage(rowNum, attr.name() + ":" +
c.trim() + "应满足时间格式:" + DateUtil.DATETIME_PATTERN_SECOND), errorTemp);
continue;
} else {
errorMessageHashMap = initErrorMessage(errorMessageHashMap,
new ErrorMessage(rowNum, attr.name() + ":" +
c.trim() + "应满足时间格式:" + DateUtil.ISO_DATE_FORMAT), errorTemp);
continue;
}
}
} else if (LocalDate.class == fieldType && Common.isNotNull(c.trim())) {
try {
field.set(data, LocalDate.parse(c.trim().replace(CommonConstants.CENTER_SPLIT_LINE_STRING, ""), DateTimeFormatter.ofPattern(DateUtil.ISO_DATE_FORMAT)));
} catch (Exception e) {
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(rowNum, attr.name() + ":" + c.trim() + "应满足时间格式:" + DateUtil.ISO_DATE_FORMAT), errorTemp);
continue;
}
}
}
if (Common.isNotNull(mapArea)){
for (Map.Entry<String, Field> entry: mapArea.entrySet()){
entry.getValue().set(data,entry.getKey().substring(0,entry.getKey().indexOf(CommonConstants.DOWN_LINE_STRING)));
}
}
}catch (Exception e){
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(rowNum, attr.name() + ":" + c.trim() + "校验异常,请联系管理人员"), errorTemp);
}finally {
}
return errorMessageHashMap.get(rowNum);
}
/**
* 例如:解析值 0=男,1=女,2=未知 传参 男解析为 0
*
* @param propertyValue 参数值
* @param converterExp 翻译注解
* @return 解析后值
* @throws Exception
*/
public static String reverseByExp(String propertyValue, String converterExp) throws Exception {
try {
String[] convertSource = converterExp.split(",");
for (String item : convertSource) {
String[] itemArray = item.split("=");
if (itemArray[1].equals(propertyValue)) {
return itemArray[0];
}
}
} catch (Exception e) {
throw e;
}
return null;
}
/**
* 例如:解析值 0=男,1=女,2=未知 传参 0解析为 男
*
* @param propertyValue 参数值
* @param converterExp 翻译注解
* @return 解析后值
* @throws Exception
*/
public static String convertByExp(String propertyValue, String converterExp) throws Exception {
try {
String[] convertSource = converterExp.split(",");
if(propertyValue.contains(",")){
String[] valueSource = propertyValue.split(",");
propertyValue = "";
for(String value:valueSource){
for (String item : convertSource) {
String[] itemArray = item.split("=");
if (itemArray[0].equals(value)) {
propertyValue += itemArray[1] + ",";
break;
}
}
}
if(propertyValue.endsWith(",")){
propertyValue = propertyValue.substring(CommonConstants.dingleDigitIntArray[0],propertyValue.length()-1);
}
}else{
for (String item : convertSource) {
String[] itemArray = item.split("=");
if (itemArray[0].equals(propertyValue)) {
return itemArray[1];
}
}
}
} catch (Exception e) {
throw e;
}
return propertyValue;
}
private String getAreaLabel(String c) {
return (String)RedisUtil.redis.opsForValue().get(CacheConstants.AREA_LABEL + c);
}
private String getAreaValue(String c, String tempStr, ExcelAttribute attr,Integer rowNum, ErrorMessage errorTemp) {
tempStr = String.valueOf(RedisUtil.redis.opsForValue().get(CacheConstants.AREA_VALUE + c));
if (Common.isEmpty(tempStr)){
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(rowNum, attr.name() + ":" + c.trim() + "校验异常,请联系管理人员"), errorTemp);
return CommonConstants.EMPTY_STRING;
}
return tempStr;
}
// 简单的获取区域字典value
public static String getRedisAreaValue(String c) {
Object value = RedisUtil.redis.opsForValue().get(c);
if (value != null) {
return String.valueOf(value);
} else {
return null;
}
}
private String getDicValue(String c, String tempStr, ExcelAttribute attr,Integer rowNum, ErrorMessage errorTemp) {
Map<String,String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue()
.get(CacheConstants.DICT_DETAILS
+ CommonConstants.COLON_STRING
+attr.dataType());
boolean flag = true;
for (Map.Entry<String,String> entry:dicObj.entrySet()){
if (Common.isNotNull(entry.getValue()) && entry.getValue().equals(c.trim())){
if (attr.isConvert()){
tempStr = entry.getKey();
}else {
tempStr = c;
}
flag = false;
break;
}
}
if (flag){
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(rowNum, attr.name() + ":" + c.trim() + "校验异常,请联系管理人员"), errorTemp);
return CommonConstants.EMPTY_STRING;
}
return tempStr;
}
/**
* @param fieldName 字段名
* @param o 对象
* @return 字段值
* @MethodName : getFieldValueByName
* @Description : 根据字段名获取字段值
*/
public static Object getFieldValueByName(String fieldName, Object o, String dateFormat) {
Object value = null;
Field field = null;
if (o == null) {
return "";
}
field = getFieldByName(fieldName, o.getClass());
String type = getFieldType(fieldName, o.getClass());
if (field != null) {
field.setAccessible(true);
try {
if (null != type && type.equals("Date")) {
Date date = (Date) field.get(o);
return DateUtil.dateToString(date, dateFormat == null ? "yyyy-MM-dd" : dateFormat);
} else {
value = field.get(o);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
log.info(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName);
}
return value;
}
/**
* @param fieldName 字段名
* @param clazz 包含该字段的类
* @return 字段
* @MethodName : getFieldByName
* @Description : 根据字段名获取字段
*/
private static Field getFieldByName(String fieldName, Class<?> clazz) {
// 拿到本类的所有字段
Field[] selfFields = clazz.getDeclaredFields();
// 如果本类中存在该字段,则返回
for (Field field : selfFields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
// 否则,查看父类中是否存在此字段,如果有则返回
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null && superClazz != Object.class) {
return getFieldByName(fieldName, superClazz);
}
// 如果本类和父类都没有,则返回空
return null;
}
/**
* @param fieldName 字段名
* @param clazz 包含该字段的类
* @return 字段
* @MethodName : getFieldType
* @Description : 根据字段名获取字段类型
*/
private static String getFieldType(String fieldName, Class<?> clazz) {
// 拿到本类的所有字段
Field[] selfFields = clazz.getDeclaredFields();
// 如果本类中存在该字段,则返回
for (Field field : selfFields) {
if (field.getName().equals(fieldName)) {
//如果type是类类型,则前面包含"class ",后面跟类名
String type = field.getGenericType().toString();
if (type.equals("class java.lang.String")) {
return "String";
} else if (type.equals("class java.lang.Integer")) {
return "Integer";
} else if (type.equals("class java.lang.Short")) {
return "Short";
} else if (type.equals("class java.lang.Double")) {
return "Double";
} else if (type.equals("class java.lang.Boolean")) {
return "Boolean";
} else if (type.equals("class java.util.Date")) {
return "Date";
} else {
return null;
}
}
}
// 否则,查看父类中是否存在此字段,如果有则返回
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null && superClazz != Object.class) {
return getFieldType(fieldName, superClazz);
}
// 如果本类和父类都没有,则返回空
return null;
}
/**
* 输出错误数据
*
* @param attr
* @param msg
* @param i
* @return
*/
private String errorInfo(ExcelAttribute attr, String msg, Integer i) {
return (Common.isEmpty(msg) ? (Common.isEmpty(attr.errorInfo()) ? "" : attr.errorInfo()) : (attr.name() + msg));
}
/**
* 正则匹配返回
*
* @param c
* @param attr
* @param pattern
* @return
* @Author fxj
* @Date 2019-08-06
**/
private boolean getMatchRes(String c, ExcelAttribute attr, String pattern) {
return !c.matches(Common.isEmpty(attr.pattern()) ? pattern : attr.pattern());
}
/**
* 实现各种校验方式的错误返回新
*
* @param c
* @param attr
* @param i
* @return
*/
private String validateUtil(String c, ExcelAttribute attr, int i) {
//非空校验
if (attr.isNotEmpty() && !Common.isNotNull(c)) {
return errorInfo(attr, "_字段不可为空", i);
}
if (Common.isNotNull(c)) {
//日期格式校验
if (attr.isDate()) {
if (null == DateUtil.stringToDate(c.trim(), "yyyyMMdd")) {
return errorInfo(attr, "_日期格式有误", i);
}
}
//手机号码校验
if (attr.isPhone() && getMatchRes(c.trim(), attr, ValidityConstants.MOBILE_PATTERN)) {
return errorInfo(attr, "_手机号码有误", i);
}
//身份证校验
if (attr.isIdCard() && getMatchRes(c.trim(), attr, ValidityConstants.IDCARD_PATTERN)) {
return errorInfo(attr, "_身份证格式有误", i);
}
//邮箱验证
if (attr.isEmail() && getMatchRes(c.trim(), attr, ValidityConstants.EMAIL_PATTERN)) {
return errorInfo(attr, "_邮箱格式有误", i);
}
//integer 验证
if (attr.isInteger() && getMatchRes(c.trim(), attr, ValidityConstants.INTEGER_PATTERN)) {
return errorInfo(attr, "_整数格式有误", i);
}
//float、double 验证
if (attr.isFloat() && getMatchRes(c.trim(), attr, ValidityConstants.FLOAT_PATTERN)) {
return errorInfo(attr, "_数字格式有误", i);
}
if (attr.isDouble() && getMatchRes(c.trim(), attr, ValidityConstants.FLOAT_PATTERN)) {
return errorInfo(attr, "_数字格式有误", i);
}
//最大长度校验
if (attr.maxLength() > 0 && c.length() > attr.maxLength()) {
return errorInfo(attr, "_超出最大长度", i);
}
//最大值校验
if (Common.isNotNull(attr.max()) && !CommonConstants.ZERO_STRING.equals(attr.max())) {
if (Common.isNumber(c)) {
if (attr.isDouble() && Double.doubleToLongBits(Double.valueOf(c).doubleValue()) > Double.valueOf(attr.max()).doubleValue()){
return errorInfo(attr, "_超出最大值", i);
}else if (attr.isFloat() &&
BigDecimalUtils.strToBigdecimal(c).compareTo(BigDecimalUtils.strToBigdecimal(attr.max())) > 0){
return errorInfo(attr, "_超出最大值", i);
}else{
if (Float.valueOf(c).intValue() > Float.valueOf(attr.max()).intValue()) {
return errorInfo(attr, "_超出最大值", i);
}
}
} else {
return errorInfo(attr, "_必须为数字且最多两位小数", i);
}
}
//最小值校验
if (attr.min() > 0) {
if (Common.isNumber(c)) {
if (attr.isFloat()){
if (Float.valueOf(c).compareTo(attr.min()) < CommonConstants.ZERO_INT) {
return errorInfo(attr, "_小于最小值", i);
}
}else{
if (String.valueOf(Float.valueOf(c).intValue()).length() < attr.min()) {
return errorInfo(attr, "_长度小于" + Float.valueOf(attr.min()).intValue() + "位", i);
}
}
} else {
return errorInfo(attr, "_必须为数字且最多两位小数", i);
}
} else if (attr.min() == 0) {
if (Common.isNumber(c)) {
if (attr.isFloat()){
if (Float.valueOf(c).compareTo(attr.min()) < CommonConstants.ZERO_INT) {
return errorInfo(attr, "_小于最小值", i);
}
}
}
}
}
return null;
}
/**
* 根据属性名获取属性值
*
* @param fieldName
* @param hashMap
* @return
*/
private static Object getFieldValueByName(String fieldName, HashMap hashMap) {
try {
return hashMap.get(fieldName);
} catch (Exception e) {
return null;
}
}
/**
* 按类型统一返回String内容
*
* @param param
* @return
*/
private static String getStringValByObject(Object param) {
if (null == param) {
return null;
} else if (param instanceof Integer) {
return Integer.toString(((Integer) param).intValue());
} else if (param instanceof String) {
return (String) param;
} else if (param instanceof Double) {
return Double.toString(((Double) param).doubleValue());
} else if (param instanceof Float) {
return Float.toString(((Float) param).floatValue());
} else if (param instanceof Long) {
return Long.toString(((Long) param).longValue());
} else if (param instanceof Boolean) {
return Boolean.toString(((Boolean) param).booleanValue());
} else if (param instanceof Date) {
return DateUtil.dateToString((Date) param);
} else if (param instanceof LocalDateTime) {
return LocalDateTimeUtils.formatTime((LocalDateTime) param, DateUtil.DATETIME_PATTERN_SECOND);
} else {
return param.toString();
}
}
private HashMap<Integer, ErrorMessage> initErrorMessage(HashMap<Integer, ErrorMessage> errorMessageHashMap, ErrorMessage errorMessage, ErrorMessage temp) {
if (null != errorMessageHashMap && null != errorMessage) {
temp = errorMessageHashMap.get(errorMessage.getLineNum());
if (null != temp) {
temp.setMessage(temp.getMessage() + CommonConstants.DOWN_LINE_STRING + errorMessage.getMessage());
errorMessageHashMap.put(temp.getLineNum(), temp);
} else {
errorMessageHashMap.put(errorMessage.getLineNum(), errorMessage);
}
}
return errorMessageHashMap;
}
/**
* 将JSONSTRING数据源的数据导入到list
*
* @param jsonStr 接收的对象JSON串
* @param dicMap HashMap<dateType_value,dataValue_dataId> 如 {EMPTYPE_兼职工伤,ID}
* @author fxj
* @date 2019/08/01
*/
public void getJsonStringToList(String jsonStr, Map<String, String> dicMap) {
List<HashMap> list = null;
List<T> listt = new ArrayList<T>();
list = JSONObject.parseArray(jsonStr, HashMap.class);
List<ErrorMessage> errorList = new ArrayList<ErrorMessage>();
HashMap<Integer, ErrorMessage> errorMessageHashMap = new HashMap<Integer, ErrorMessage>();
try {
// 得到数据的条数
int rows = list.size();
// 有数据时才处理
if (rows > 0) {
// 得到类的所有field
Field[] allFields = clazz.getDeclaredFields();
Field field;
// 定义一个map用于存放列的序号和field
Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
for (int i = 0, index = 0; i < allFields.length; i++) {
field = allFields[i];
// 将有注解的field存放到map中
if (field.isAnnotationPresent(ExcelAttribute.class)) {
// 设置类的私有字段属性可访问
field.setAccessible(true);
fieldsMap.put(index, field);
index++;
}
}
//存储错误数据
String error = "";
//临时存储单元格数据
String tempStr = "";
// 从第1行开始取数据
T entity = null;
HashMap temp;
ExcelAttribute attr;
String c = null;
Class<?> fieldType;
ErrorMessage errorTemp = null;
for (int i = 0; i < rows; i++) {
// 得到一行中的所有单元格对象.
temp = list.get(i);
entity = clazz.newInstance();
for (int j = 0; j < fieldsMap.size(); j++) {
// 从map中得到对应列的field
field = fieldsMap.get(j);
//获取属性对应的注解属性
attr = field.getAnnotation(ExcelAttribute.class);
// 单元格中的内容.
c = getStringValByObject(getFieldValueByName(attr.name(), temp));
if (c != null) {
c = c.trim();
}
//校验字段是否符合要求 返回错误信息
error = validateUtil(c, attr, i + 2);
if (null == error && attr.isDate() && Common.isNotNull(c)) {
c = c.replace("/","-").replace(CommonConstants.YEAR,"-")
.replace(CommonConstants.MONTH,"-").replace(CommonConstants.DAY,"");
Pattern pattern = Pattern.compile("[0-9]*");
if (pattern.matcher(c).matches()) {
StringBuilder sb = new StringBuilder(c);
sb.insert(4, "-");
sb.insert(7,"-");
c = sb.toString();
}
}
if (null != error) {
errorList.add(new ErrorMessage(i + 2, error));
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(i + 2, error), errorTemp);
continue;
}
if (field == null) {
continue;
}
//单元格数据为空不需要处理了
if (!StringUtils.isNotBlank(c)) {
continue;
}
//如果是需要从字典表取值数据的话在这里处理即可
if (attr.isDataId() && null != dicMap) {
if (Common.isNotNull(attr.dataType())) {
//非区域字段处理
if (Common.isNotNull(attr.parentField())){
tempStr = dicMap.get(attr.dataType() + "_" + c.trim() + "_" + getFieldValueByName(attr.parentField(), entity, DateUtil.ISO_EXPANDED_DATE_FORMAT));
}else {
tempStr = dicMap.get(attr.dataType() + "_" + c.trim());
}
} else {
if (attr.isArea()) {
//区域字段处理
if (Common.isEmpty(attr.parentField())) {
tempStr = dicMap.get(c.trim() + "_0");
} else {
tempStr = dicMap.get(c.trim() + "_" + getFieldValueByName(attr.parentField(), entity, DateUtil.ISO_EXPANDED_DATE_FORMAT));
}
} else {
//直接按值去找数据
tempStr = dicMap.get(c.trim());
}
}
if (!StringUtils.isNotBlank(tempStr)) {
if (attr.isOrgan()) {
errorList.add(new ErrorMessage(i + 2, "未找到:" + c + "的单位或项目数据,请确认存在项目权限"));
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(i + 2, "未找到:" + c + "的单位或项目数据,请确认存在项目权限"), errorTemp);
}
if (attr.isArea()) {
errorList.add(new ErrorMessage(i + 2, "未找到:" + c + "的区域数据"));
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(i + 2, "未找到:" + c + "的区域数据"), errorTemp);
} else {
if (Common.isNotNull(attr.errorInfoImport())) {
errorList.add(new ErrorMessage(i + 2, "数据'" + c + "':" + attr.errorInfoImport()));
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(i + 2, "数据'" + c + "':" + attr.errorInfoImport()), errorTemp);
} else {
errorList.add(new ErrorMessage(i + 2, "未找到:" + c + "的字典数据"));
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(i + 2, "未找到:" + c + "的字典数据"), errorTemp);
}
}
continue;
} else {
c = tempStr;
}
}
// 取得类型,并根据对象类型设置值.
fieldType = field.getType();
if (fieldType == null) {
continue;
}
if (String.class == fieldType) {
field.set(entity, c);
} else if (BigDecimal.class == fieldType) {
c = c.indexOf('%') != -1 ? c.replace("%", "") : c;
field.set(entity, BigDecimal.valueOf(Double.valueOf(c)));
} else if (Date.class == fieldType && Common.isNotNull(c.trim())) {
field.set(entity, DateUtil.stringToDate(c.trim(), Common.isEmpty(attr.dateFormat()) ? DateUtil.ISO_EXPANDED_DATE_FORMAT : attr.dateFormat()));
} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
field.set(entity, Integer.parseInt(c));
} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
field.set(entity, Long.valueOf(c));
} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
field.set(entity, Float.valueOf(c));
} else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
field.set(entity, Short.valueOf(c));
} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
field.set(entity, Double.valueOf(c));
} else if (Character.TYPE == fieldType) {
if ((c != null) && (c.length() > 0)) {
field.set(entity, Character.valueOf(c.charAt(0)));
}
} else if (LocalDateTime.class == fieldType && Common.isNotNull(c.trim())) {
String dc = c.trim().replace(CommonConstants.CENTER_SPLIT_LINE_STRING, "")
.replace(CommonConstants.SLASH_SPLIT_LINE_STRING, "");
try {
if (dc.length() > CommonConstants.EIGHT_INT) {
field.set(entity, LocalDateTimeUtils.convertDateToLDT(DateUtil.stringToDate(dc, DateUtil.DATETIME_PATTERN_CONTAINS)));
}else {
field.set(entity, LocalDateTimeUtils.convertDateToLDT(DateUtil.stringToDate(dc, DateUtil.ISO_DATE_FORMAT)));
}
} catch (Exception e) {
if (dc.length() > CommonConstants.EIGHT_INT) {
errorList.add(new ErrorMessage(i + 2, attr.name() + ":" +
c.trim() + "应满足时间格式:" + DateUtil.DATETIME_PATTERN_SECOND));
errorMessageHashMap = initErrorMessage(errorMessageHashMap,
new ErrorMessage(i + 2, attr.name() + ":" +
c.trim() + "应满足时间格式:" + DateUtil.DATETIME_PATTERN_SECOND), errorTemp);
continue;
} else {
errorList.add(new ErrorMessage(i + 2, attr.name() + ":" +
c.trim() + "应满足时间格式:" + DateUtil.ISO_DATE_FORMAT));
errorMessageHashMap = initErrorMessage(errorMessageHashMap,
new ErrorMessage(i + 2, attr.name() + ":" +
c.trim() + "应满足时间格式:" + DateUtil.ISO_DATE_FORMAT), errorTemp);
continue;
}
}
} else if (LocalDate.class == fieldType && !Common.isEmpty(c.trim())) {
try {
field.set(entity, LocalDate.parse(c.trim().replace(CommonConstants.CENTER_SPLIT_LINE_STRING, ""), DateTimeFormatter.ofPattern(DateUtil.ISO_DATE_FORMAT)));
} catch (Exception e) {
errorList.add(new ErrorMessage(i + 2, attr.name() + ":" + c.trim() + "应满足时间格式:" + DateUtil.ISO_DATE_FORMAT));
errorMessageHashMap = initErrorMessage(errorMessageHashMap, new ErrorMessage(i + 2, attr.name() + ":" + c.trim() + "应满足时间格式:" + DateUtil.ISO_DATE_FORMAT), errorTemp);
continue;
}
}
}
if (null == error) {
if (entity != null) {
listt.add(entity);
}
} else {
continue;
}
}
}
} catch (Exception e) {
throw new ExcelException("将jsonString数据源的数据导入到list异常:" + e.getMessage(), e);
}
this.setEntityList(listt);
this.setErrorInfo(errorList);
this.setErrorMessageHashMap(errorMessageHashMap);
}
/**
* @param clazz
* @Author: wangan
* @Date: 2020/9/28
* @Description: 获取导出中文字段
* @return: com.yifu.cloud.v1.common.core.util.R
**/
public static R<List<String>> getExportfieldsName(Class<?> clazz){
ArrayList<String> exportfieldsName = Lists.newArrayList();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
ExcelAttribute annotation = field.getAnnotation(ExcelAttribute.class);
if (annotation != null && Common.isNotNull(annotation.name()) && annotation.needExport()) {
exportfieldsName.add(annotation.name());
}
}
return R.ok(exportfieldsName,"成功");
}
}
package com.yifu.cloud.plus.v1.yifu.common.core.util;
import cn.hutool.extra.spring.SpringUtil;
import lombok.experimental.UtilityClass;
import org.springframework.context.MessageSource;
import java.util.Locale;
/**
* i18n 工具类
*
* @author lengleng
* @date 2022/3/30
*/
@UtilityClass
public class MsgUtils {
/**
* 通过code 获取中文错误信息
* @param code
* @return
*/
public String getMessage(String code) {
MessageSource messageSource = SpringUtil.getBean("messageSource");
return messageSource.getMessage(code, null, Locale.CHINA);
}
/**
* 通过code 和参数获取中文错误信息
* @param code
* @return
*/
public String getMessage(String code, Object... objects) {
MessageSource messageSource = SpringUtil.getBean("messageSource");
return messageSource.getMessage(code, objects, Locale.CHINA);
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.util;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* 响应信息主体
*
* @param <T>
* @author lengleng
*/
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Getter
@Setter
private int code;
@Getter
@Setter
private String msg;
@Getter
@Setter
private T data;
public R(T data) {
super();
this.data = data;
this.code = CommonConstants.SUCCESS;
}
//这个异常类不要放开,new R(null)容易出现问题
public R(T data,Throwable e) {
super();
this.msg = e.getMessage();
this.code = CommonConstants.FAIL;
}
public static <T> R<T> ok() {
return restResult(null, CommonConstants.SUCCESS, null);
}
public static <T> R<T> ok(T data) {
return restResult(data, CommonConstants.SUCCESS, null);
}
public static <T> R<T> ok(T data, String msg) {
return restResult(data, CommonConstants.SUCCESS, msg);
}
public static <T> R<T> failed() {
return restResult(null, CommonConstants.FAIL, null);
}
public static <T> R<T> failed(String msg) {
return restResult(null, CommonConstants.FAIL, msg);
}
public static <T> R<T> failed(T data) {
return restResult(data, CommonConstants.FAIL, null);
}
public static <T> R<T> failed(T data, String msg) {
return restResult(data, CommonConstants.FAIL, msg);
}
private static <T> R<T> restResult(T data, int code, String msg) {
R<T> apiResult = new R<>();
apiResult.setCode(code);
apiResult.setData(data);
apiResult.setMsg(msg);
return apiResult;
}
}
package com.yifu.cloud.plus.v1.yifu.common.core.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @Author fxj
* @Date 2022/6/22
* @Description
* @Version 1.0
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
public static RedisTemplate redis;
@PostConstruct
public void getRedisTemplate(){
redis = redisTemplate;
}
/**
* 批量删除对应的Value
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除KEY
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}
/**
* 删除对应的value
* @param key
*/
public void remove(final String key){
if (exists(key)){
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
* @param key
* @return
*/
public boolean exists(final String key){
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
* @param key
* @return
*/
public Object get(final String key){
Object result = null;
ValueOperations<Serializable,Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
* @param key
* @param value
* @return
*/
public boolean set(final String key ,Object value){
boolean result = false;
try {
ValueOperations<Serializable,Object> operations = redisTemplate.opsForValue();
operations.set(key,value);
result = true;
} catch (Exception e){
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
* @param key
* @param value
* @param expireTime
* @return
*/
public boolean set(final String key ,Object value,Long expireTime){
boolean result = false;
try {
ValueOperations<Serializable,Object> operations = redisTemplate.opsForValue();
operations.set(key,value);
redisTemplate.expire(key,expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e){
e.printStackTrace();
}
return result;
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.util;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
/**
* @author lengleng
* @date 2019/2/1 Spring 工具类
*/
@Slf4j
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
if (log.isDebugEnabled()) {
log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
}
/**
* 发布事件
* @param event
*/
public static void publishEvent(ApplicationEvent event) {
if (applicationContext == null) {
return;
}
applicationContext.publishEvent(event);
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
@SneakyThrows
public void destroy() {
SpringContextHolder.clearHolder();
}
}
/*
* Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yifu.cloud.plus.v1.yifu.common.core.util;
import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.CheckedException;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Miscellaneous utilities for web applications.
*
* @author L.cm
*/
@Slf4j
@UtilityClass
public class WebUtils extends org.springframework.web.util.WebUtils {
private final String BASIC_ = "Basic ";
private final String UNKNOWN = "unknown";
/**
* 判断是否ajax请求 spring ajax 返回含有 ResponseBody 或者 RestController注解
* @param handlerMethod HandlerMethod
* @return 是否ajax请求
*/
public boolean isBody(HandlerMethod handlerMethod) {
ResponseBody responseBody = ClassUtils.getAnnotation(handlerMethod, ResponseBody.class);
return responseBody != null;
}
/**
* 读取cookie
* @param name cookie name
* @return cookie value
*/
public String getCookieVal(String name) {
if (WebUtils.getRequest().isPresent()) {
return getCookieVal(WebUtils.getRequest().get(), name);
}
return null;
}
/**
* 读取cookie
* @param request HttpServletRequest
* @param name cookie name
* @return cookie value
*/
public String getCookieVal(HttpServletRequest request, String name) {
Cookie cookie = getCookie(request, name);
return cookie != null ? cookie.getValue() : null;
}
/**
* 清除 某个指定的cookie
* @param response HttpServletResponse
* @param key cookie key
*/
public void removeCookie(HttpServletResponse response, String key) {
setCookie(response, key, null, 0);
}
/**
* 设置cookie
* @param response HttpServletResponse
* @param name cookie name
* @param value cookie value
* @param maxAgeInSeconds maxage
*/
public void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
cookie.setMaxAge(maxAgeInSeconds);
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
/**
* 获取 HttpServletRequest
* @return {HttpServletRequest}
*/
public Optional<HttpServletRequest> getRequest() {
return Optional
.ofNullable(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
}
/**
* 获取 HttpServletResponse
* @return {HttpServletResponse}
*/
public HttpServletResponse getResponse() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
}
/**
* 返回json
* @param response HttpServletResponse
* @param result 结果对象
*/
public void renderJson(HttpServletResponse response, Object result) {
renderJson(response, result, MediaType.APPLICATION_JSON_VALUE);
}
/**
* 返回json
* @param response HttpServletResponse
* @param result 结果对象
* @param contentType contentType
*/
public void renderJson(HttpServletResponse response, Object result, String contentType) {
response.setCharacterEncoding(CommonConstants.UTF8);
response.setContentType(contentType);
try (PrintWriter out = response.getWriter()) {
out.append(JSONUtil.toJsonStr(result));
}
catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* 从request 获取CLIENT_ID
* @return
*/
@SneakyThrows
public String getClientId(ServerHttpRequest request) {
String header = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
return splitClient(header)[0];
}
@SneakyThrows
public String getClientId() {
if (WebUtils.getRequest().isPresent()) {
String header = WebUtils.getRequest().get().getHeader(HttpHeaders.AUTHORIZATION);
return splitClient(header)[0];
}
return null;
}
@NotNull
private static String[] splitClient(String header) {
if (header == null || !header.startsWith(BASIC_)) {
throw new CheckedException("请求头中client信息为空");
}
byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);
byte[] decoded;
try {
decoded = Base64.decode(base64Token);
}
catch (IllegalArgumentException e) {
throw new CheckedException("Failed to decode basic authentication token");
}
String token = new String(decoded, StandardCharsets.UTF_8);
int delim = token.indexOf(":");
if (delim == -1) {
throw new CheckedException("Invalid basic authentication token");
}
return new String[] { token.substring(0, delim), token.substring(delim + 1) };
}
/**
* 获取ip
*
* @return {String}
*/
public static String getIP() {
return getIP(WebUtils.getRequest().get());
}
/**
* 获取ip
*
* @param request HttpServletRequest
* @return {String}
*/
public static String getIP(HttpServletRequest request) {
Assert.notNull(request, "HttpServletRequest is null");
String ip = request.getHeader("X-Requested-For");
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return StringUtils.isBlank(ip) ? null : ip.split(",")[0];
}
/**
* 获取所有头部信息
* @Author pwang
* @Date 2021-07-01 15:50
* @param request
* @return
**/
public static Map<String, String> getHeadersInfo(HttpServletRequest request) {
Map<String, String> map = new HashMap<String, String>();
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
return map;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment