代码优化

pull/167/head
dqjdda 2019-10-24 09:34:39 +08:00
commit e3c3ebb1d0
58 changed files with 398 additions and 670 deletions

View File

@ -20,38 +20,35 @@ public @interface Query {
/**
* Userdept
* @return
*/
String joinName() default "";
/**
*
* @return
*/
Join join() default Join.LEFT;
/**
* String, @Query(blurry = "email,username")
* @return
*/
String blurry() default "";
enum Type {
/** jie 2019/6/4 相等 */
// jie 2019/6/4 相等
EQUAL
/** Dong ZhaoYang 2017/8/7 大于等于 */
// Dong ZhaoYang 2017/8/7 大于等于
, GREATER_THAN
/** Dong ZhaoYang 2017/8/7 小于等于 */
// Dong ZhaoYang 2017/8/7 小于等于
, LESS_THAN
/** Dong ZhaoYang 2017/8/7 中模糊查询 */
// Dong ZhaoYang 2017/8/7 中模糊查询
, INNER_LIKE
/** Dong ZhaoYang 2017/8/7 左模糊查询 */
// Dong ZhaoYang 2017/8/7 左模糊查询
, LEFT_LIKE
/** Dong ZhaoYang 2017/8/7 右模糊查询 */
// Dong ZhaoYang 2017/8/7 右模糊查询
, RIGHT_LIKE
/** Dong ZhaoYang 2017/8/7 小于 */
// Dong ZhaoYang 2017/8/7 小于
, LESS_THAN_NQ
//** jie 2019/6/4 包含 */
// jie 2019/6/4 包含
, IN
}

View File

@ -12,7 +12,6 @@ import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
@ -23,10 +22,13 @@ import java.lang.reflect.Method;
@Aspect
@Component
public class LimitAspect {
@Autowired
private RedisTemplate redisTemplate;
private final RedisTemplate redisTemplate;
private static final Logger logger = LoggerFactory.getLogger(LimitAspect.class);
public LimitAspect(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Pointcut("@annotation(me.zhengjie.annotation.Limit)")
public void pointcut() {
@ -41,12 +43,10 @@ public class LimitAspect {
LimitType limitType = limit.limitType();
String key = limit.key();
if (StringUtils.isEmpty(key)) {
switch (limitType) {
case IP:
key = StringUtils.getIP(request);
break;
default:
key = signatureMethod.getName();
if (limitType == LimitType.IP) {
key = StringUtils.getIP(request);
} else {
key = signatureMethod.getName();
}
}

View File

@ -1,7 +1,6 @@
package me.zhengjie.exception;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
@ -12,23 +11,17 @@ import java.util.stream.IntStream;
*/
public class EntityExistException extends RuntimeException {
public EntityExistException(Class clazz, Object... saveBodyParamsMap) {
super(EntityExistException.generateMessage(clazz.getSimpleName(), toMap(String.class, String.class, saveBodyParamsMap)));
public EntityExistException(Class clazz, String field, String val) {
super(EntityExistException.generateMessage(clazz.getSimpleName(), toMap(field, val)));
}
private static String generateMessage(String entity, Map<String, String> saveBodyParams) {
private static String generateMessage(String entity, Map<Object, Object> saveBodyParams) {
return StringUtils.capitalize(entity) +
" 已存在 " +
saveBodyParams;
}
private static <K, V> Map<K, V> toMap(
Class<K> keyType, Class<V> valueType, Object... entries) {
if (entries.length % 2 == 1)
throw new IllegalArgumentException("Invalid entries");
return IntStream.range(0, entries.length / 2).map(i -> i * 2)
.collect(HashMap::new,
(m, i) -> m.put(keyType.cast(entries[i]), valueType.cast(entries[i + 1])),
Map::putAll);
private static Map<Object, Object> toMap(String... entries) {
return new HashMap<Object, Object>(){{ put(entries[0], entries[1]); }};
}
}

View File

@ -12,24 +12,17 @@ import java.util.stream.IntStream;
*/
public class EntityNotFoundException extends RuntimeException {
public EntityNotFoundException(Class clazz, Object... searchParamsMap) {
super(EntityNotFoundException.generateMessage(clazz.getSimpleName(), toMap(String.class, String.class, searchParamsMap)));
public EntityNotFoundException(Class clazz, String field, String val) {
super(EntityNotFoundException.generateMessage(clazz.getSimpleName(), toMap(field, val)));
}
private static String generateMessage(String entity, Map<String, String> searchParams) {
private static String generateMessage(String entity, Map<Object, Object> searchParams) {
return StringUtils.capitalize(entity) +
" 不存在 " +
searchParams;
}
private static <K, V> Map<K, V> toMap(
Class<K> keyType, Class<V> valueType, Object... entries) {
if (entries.length % 2 == 1)
throw new IllegalArgumentException("Invalid entries");
return IntStream.range(0, entries.length / 2).map(i -> i * 2)
.collect(HashMap::new,
(m, i) -> m.put(keyType.cast(entries[i]), valueType.cast(entries[i + 1])),
Map::putAll);
private static Map<Object, Object> toMap(String... entries) {
return new HashMap<Object, Object>(){{ put(entries[0], entries[1]); }};
}
}

View File

@ -21,7 +21,7 @@ class ApiError {
timestamp = LocalDateTime.now();
}
public ApiError(Integer status,String message) {
ApiError(Integer status, String message) {
this();
this.status = status;
this.message = message;

View File

@ -11,6 +11,9 @@ import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Objects;
import static org.springframework.http.HttpStatus.*;
/**
@ -23,8 +26,6 @@ public class GlobalExceptionHandler {
/**
*
* @param e
* @return
*/
@ExceptionHandler(Throwable.class)
public ResponseEntity handleException(Throwable e){
@ -36,8 +37,6 @@ public class GlobalExceptionHandler {
/**
* 访AccessDeniedException
* @param e
* @return
*/
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity handleAccessDeniedException(AccessDeniedException e){
@ -49,8 +48,6 @@ public class GlobalExceptionHandler {
/**
*
* @param e
* @return
*/
@ExceptionHandler(value = BadRequestException.class)
public ResponseEntity<ApiError> badRequestException(BadRequestException e) {
@ -62,8 +59,6 @@ public class GlobalExceptionHandler {
/**
* EntityExist
* @param e
* @return
*/
@ExceptionHandler(value = EntityExistException.class)
public ResponseEntity<ApiError> entityExistException(EntityExistException e) {
@ -75,8 +70,6 @@ public class GlobalExceptionHandler {
/**
* EntityNotFound
* @param e
* @return
*/
@ExceptionHandler(value = EntityNotFoundException.class)
public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) {
@ -88,26 +81,20 @@ public class GlobalExceptionHandler {
/**
*
* @param e
* @returns
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
String[] str = e.getBindingResult().getAllErrors().get(0).getCodes()[1].split("\\.");
StringBuffer msg = new StringBuffer(str[1]+":");
msg.append(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
ApiError apiError = new ApiError(BAD_REQUEST.value(),msg.toString());
String[] str = Objects.requireNonNull(e.getBindingResult().getAllErrors().get(0).getCodes())[1].split("\\.");
ApiError apiError = new ApiError(BAD_REQUEST.value(), str[1] + ":" + e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return buildResponseEntity(apiError);
}
/**
*
* @param apiError
* @return
*/
private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus()));
return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
}
}

View File

@ -10,29 +10,21 @@ public interface EntityMapper<D, E> {
/**
* DTOEntity
* @param dto
* @return
*/
E toEntity(D dto);
/**
* EntityDTO
* @param entity
* @return
*/
D toDto(E entity);
/**
* DTOEntity
* @param dtoList
* @return
*/
List <E> toEntity(List<D> dtoList);
/**
* EntityDTO
* @param entityList
* @return
*/
List <D> toDto(List<E> entityList);
}

View File

@ -4,8 +4,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* Value
@ -15,11 +14,9 @@ import java.nio.charset.Charset;
*/
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) {
FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@ -29,7 +26,7 @@ public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8);
}
@Override
@ -37,7 +34,7 @@ public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
String str = new String(bytes, StandardCharsets.UTF_8);
return (T) JSON.parseObject(str, clazz);
}

View File

@ -28,7 +28,6 @@ import java.time.Duration;
@Slf4j
@Configuration
@EnableCaching
// 自动配置
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig extends CachingConfigurerSupport {
@ -36,7 +35,6 @@ public class RedisConfig extends CachingConfigurerSupport {
/**
* redis 1
* @cacheable
* @return
*/
@Bean
public RedisCacheConfiguration redisCacheConfiguration(){
@ -55,17 +53,16 @@ public class RedisConfig extends CachingConfigurerSupport {
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// 全局开启AutoType不建议使用
// ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// 全局开启AutoType这里方便开发使用全局的方式
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// 建议使用这种方式,小范围指定白名单
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.service.dto");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.service.dto");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.domain");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.quartz.domain");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.monitor.domain");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.security.security");
// ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain");
// ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.service.dto");
// ParserConfig.getGlobalInstance().addAccept("me.zhengjie.service.dto");
// ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.domain");
// ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.quartz.domain");
// ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.monitor.domain");
// ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.security.security");
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
@ -75,8 +72,6 @@ public class RedisConfig extends CachingConfigurerSupport {
/**
* key使
* 使 @Cacheable
* @return
*/
@Bean
@Override
@ -97,7 +92,7 @@ public class RedisConfig extends CachingConfigurerSupport {
public CacheErrorHandler errorHandler() {
// 异常处理当Redis发生异常时打印日志但是程序正常走
log.info("初始化 -> [{}]", "Redis CacheErrorHandler");
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
return new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
log.error("Redis occur handleCacheGetErrorkey -> [{}]", key, e);
@ -118,7 +113,6 @@ public class RedisConfig extends CachingConfigurerSupport {
log.error("Redis occur handleCacheClearError", e);
}
};
return cacheErrorHandler;
}
}

View File

@ -2,9 +2,10 @@ package me.zhengjie.redis;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import me.zhengjie.utils.StringUtils;
import org.springframework.data.redis.serializer.RedisSerializer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
*
@ -15,15 +16,11 @@ public class StringRedisSerializer implements RedisSerializer<Object> {
private final Charset charset;
private final String target = "\"";
private final String replacement = "";
public StringRedisSerializer() {
this(Charset.forName("UTF8"));
StringRedisSerializer() {
this(StandardCharsets.UTF_8);
}
public StringRedisSerializer(Charset charset) {
private StringRedisSerializer(Charset charset) {
Assert.notNull(charset, "Charset must not be null!");
this.charset = charset;
}
@ -36,10 +33,10 @@ public class StringRedisSerializer implements RedisSerializer<Object> {
@Override
public byte[] serialize(Object object) {
String string = JSON.toJSONString(object);
if (string == null) {
if (StringUtils.isBlank(string)) {
return null;
}
string = string.replace(target, replacement);
string = string.replace("\"", "");
return string.getBytes(charset);
}
}

View File

@ -55,7 +55,7 @@ public class SwaggerConfig {
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("eladmin 接口文档")
.version("2.1")
.version("2.2")
.build();
}

View File

@ -14,7 +14,7 @@ public class ElAdminConstant {
/**
* IP
*/
public static final String REGION = "内网IP|内网IP";
static final String REGION = "内网IP|内网IP";
/**
*

View File

@ -6,6 +6,7 @@ import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
/**
*
@ -27,23 +28,23 @@ public class EncryptUtils {
return null;
}
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes("UTF-8"));
DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(strParam.getBytes("UTF-8"));
IvParameterSpec iv = new IvParameterSpec(strParam.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return byte2hex(
cipher.doFinal(source.getBytes("UTF-8"))).toUpperCase();
cipher.doFinal(source.getBytes(StandardCharsets.UTF_8))).toUpperCase();
}
public static String byte2hex(byte[] inStr) {
private static String byte2hex(byte[] inStr) {
String stmp;
StringBuffer out = new StringBuffer(inStr.length * 2);
for (int n = 0; n < inStr.length; n++) {
stmp = Integer.toHexString(inStr[n] & 0xFF);
StringBuilder out = new StringBuilder(inStr.length * 2);
for (byte b : inStr) {
stmp = Integer.toHexString(b & 0xFF);
if (stmp.length() == 1) {
// 如果是0至F的单位字符串则添加0
out.append("0" + stmp);
out.append("0").append(stmp);
} else {
out.append(stmp);
}
@ -51,8 +52,7 @@ public class EncryptUtils {
return out.toString();
}
public static byte[] hex2byte(byte[] b) {
private static byte[] hex2byte(byte[] b) {
if ((b.length % 2) != 0){
throw new IllegalArgumentException("长度不是偶数");
}
@ -66,9 +66,6 @@ public class EncryptUtils {
/**
*
* @param source
* @return
* @throws Exception
*/
public static String desDecrypt(String source) throws Exception {
if (source == null || source.length() == 0){
@ -76,10 +73,10 @@ public class EncryptUtils {
}
byte[] src = hex2byte(source.getBytes());
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes("UTF-8"));
DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(strParam.getBytes("UTF-8"));
IvParameterSpec iv = new IvParameterSpec(strParam.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(src);
return new String(retByte);
@ -87,8 +84,6 @@ public class EncryptUtils {
/**
*
* @param password
* @return
*/
public static String encryptPassword(String password){
return DigestUtils.md5DigestAsHex(password.getBytes());

View File

@ -44,8 +44,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/**
* MultipartFileFile
* @param multipartFile
* @return
*/
public static File toFile(MultipartFile multipartFile){
// 获取文件名
@ -65,21 +63,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
}
/**
*
* @param files
*/
public static void deleteFile(File... files) {
for (File file : files) {
if (file.exists()) {
file.delete();
}
}
}
/**
*
* @param filename
* @return
* .
*/
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
@ -93,8 +77,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/**
* Java
* @param filename
* @return
*/
public static String getFileNameNoEx(String filename) {
if ((filename != null) && (filename.length() > 0)) {
@ -108,8 +90,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/**
*
* @param size
* @return
*/
public static String getSize(long size){
String resultSize = "";
@ -130,13 +110,9 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/**
* inputStream File
* @param ins
* @param name
* @return
* @throws Exception
*/
public static File inputStreamToFile(InputStream ins, String name) throws Exception{
File file = new File(System.getProperty("java.io.tmpdir") + name);
static File inputStreamToFile(InputStream ins, String name) throws Exception{
File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
if (file.exists()) {
return file;
}
@ -153,10 +129,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/**
*
*
* @param file
* @param filePath
* @return
*/
public static File upload(MultipartFile file, String filePath) {
Date date = new Date();
@ -170,7 +142,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
File dest = new File(path);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夹
dest.getParentFile().mkdirs();
}
String d = dest.getPath();
file.transferTo(dest);// 文件写入
@ -187,16 +159,12 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
base64=new Base64().encode(buffer);
String encoded = base64.replaceAll("[\\s*\t\n\r]", "");
return encoded;
base64=Base64.encode(buffer);
return base64.replaceAll("[\\s*\t\n\r]", "");
}
/**
* excel
* @param list
* @return
* @throws Exception
*/
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
@ -217,25 +185,26 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
}
public static String getFileType(String type) {
String documents = "txt doc pdf ppt pps xlsx xls";
String documents = "txt doc pdf ppt pps xlsx xls docx";
String music = "mp3 wav wma mpa ram ra aac aif m4a";
String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg";
String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg";
if(image.indexOf(type) != -1){
if(image.contains(type)){
return "图片";
} else if(documents.indexOf(type) != -1){
} else if(documents.contains(type)){
return "文档";
} else if(music.indexOf(type) != -1){
} else if(music.contains(type)){
return "音乐";
} else if(video.indexOf(type) != -1){
} else if(video.contains(type)){
return "视频";
} else return "其他";
}
public static String getFileTypeByMimeType(String type) {
String mimeType = new MimetypesFileTypeMap().getContentType("." + type);
return mimeType.split("\\/")[0];
return mimeType.split("/")[0];
}
public static void checkSize(long maxSize, long size) {
if(size > (maxSize * 1024 * 1024)){
throw new BadRequestException("文件超出规定大小");

View File

@ -12,10 +12,6 @@ public class PageUtil extends cn.hutool.core.util.PageUtil {
/**
* List
* @param page
* @param size
* @param list
* @return
*/
public static List toPage(int page, int size , List list) {
int fromIndex = page * size;
@ -32,8 +28,6 @@ public class PageUtil extends cn.hutool.core.util.PageUtil {
/**
* Page redis
* @param page
* @return
*/
public static Map toPage(Page page) {
Map<String,Object> map = new LinkedHashMap<>(2);
@ -43,9 +37,7 @@ public class PageUtil extends cn.hutool.core.util.PageUtil {
}
/**
* @param object
* @param totalElements
* @return
*
*/
public static Map toPage(Object object, Object totalElements) {
Map<String,Object> map = new LinkedHashMap<>(2);

View File

@ -15,18 +15,12 @@ import java.util.*;
@Slf4j
public class QueryHelp {
/**
* @ : Predicate
* @ : Dong ZhaoYang
* @ : 2017/8/7
* @ : 17:25
*/
@SuppressWarnings("unchecked")
public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<>();
if(query == null){
return cb.and(list.toArray(new Predicate[list.size()]));
return cb.and(list.toArray(new Predicate[0]));
}
try {
List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());
@ -62,14 +56,14 @@ public class QueryHelp {
for (String name : joinNames) {
switch (q.join()) {
case LEFT:
if(ObjectUtil.isNotEmpty(join)){
if(ObjectUtil.isNotNull(join)){
join = join.join(name, JoinType.LEFT);
} else {
join = root.join(name, JoinType.LEFT);
}
break;
case RIGHT:
if(ObjectUtil.isNotEmpty(join)){
if(ObjectUtil.isNotNull(join)){
join = join.join(name, JoinType.RIGHT);
} else {
join = root.join(name, JoinType.RIGHT);
@ -137,7 +131,7 @@ public class QueryHelp {
return true;
}
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}

View File

@ -3,6 +3,7 @@ package me.zhengjie.utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* HttpServletRequest
@ -12,6 +13,6 @@ import javax.servlet.http.HttpServletRequest;
public class RequestHolder {
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
}
}

View File

@ -28,8 +28,7 @@ public class SecurityUtils {
*/
public static String getUsername(){
Object obj = getUserDetails();
JSONObject json = new JSONObject(obj);
return json.get("username", String.class);
return new JSONObject(obj).get("username", String.class);
}
/**
@ -38,7 +37,6 @@ public class SecurityUtils {
*/
public static Long getUserId(){
Object obj = getUserDetails();
JSONObject json = new JSONObject(obj);
return json.get("id", Long.class);
return new JSONObject(obj).get("id", Long.class);
}
}

View File

@ -26,6 +26,7 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
/**
* applicationContextBean, .
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);

View File

@ -27,7 +27,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
* @param strs
* @return true
*/
public static boolean inString(String str, String... strs) {
static boolean inString(String str, String... strs) {
if (str != null) {
for (String s : strs) {
if (str.equals(trim(s))) {
@ -92,7 +92,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toUnderScoreCase(String s) {
static String toUnderScoreCase(String s) {
if (s == null) {
return null;
}
@ -125,10 +125,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
* ip
* @param request
* @return
*/
public static String getIP(HttpServletRequest request) {
public static String getIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
@ -145,32 +143,16 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
* ip
* @param ip
* @return
*/
public static String getCityInfo(String ip) {
try {
String path = "ip2region/ip2region.db";
String name = "ip2region.db";
int algorithm = DbSearcher.BTREE_ALGORITHM;
DbConfig config = new DbConfig();
File file = FileUtil.inputStreamToFile(new ClassPathResource(path).getStream(), name);
DbSearcher searcher = new DbSearcher(config, file.getPath());
Method method = null;
switch (algorithm) {
case DbSearcher.BTREE_ALGORITHM:
method = searcher.getClass().getMethod("btreeSearch", String.class);
break;
case DbSearcher.BINARY_ALGORITHM:
method = searcher.getClass().getMethod("binarySearch", String.class);
break;
case DbSearcher.MEMORY_ALGORITYM:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
default:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
}
method = searcher.getClass().getMethod("btreeSearch", String.class);
DataBlock dataBlock = null;
dataBlock = (DataBlock) method.invoke(searcher, ip);
String address = dataBlock.getRegion().replace("0|","");

View File

@ -2,30 +2,23 @@ package me.zhengjie.utils;
import me.zhengjie.exception.BadRequestException;
import org.hibernate.exception.ConstraintViolationException;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
*
* 2019-01-06
* @author Zheng Jie
* @date 2019-01-06
*/
public class ThrowableUtil {
/**
*
* @param throwable
* @return
*/
public static String getStackTrace(Throwable throwable){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
try (PrintWriter pw = new PrintWriter(sw)) {
throwable.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
}
@ -34,9 +27,10 @@ public class ThrowableUtil {
while ((t != null) && !(t instanceof ConstraintViolationException)) {
t = t.getCause();
}
if (t instanceof ConstraintViolationException) {
if (t != null) {
throw new BadRequestException(msg);
}
assert false;
throw new BadRequestException("删除失败:" + t.getMessage());
}
}

View File

@ -1,8 +1,6 @@
package me.zhengjie.utils;
import cn.hutool.json.JSONArray;
import lombok.var;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
@ -26,7 +24,7 @@ public class TranslatorUtil {
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
@ -39,14 +37,11 @@ public class TranslatorUtil {
}
private static String parseResult(String inputJson) throws Exception {
JSONArray jsonArray = new JSONArray(inputJson);
JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
String result ="";
for(var i = 0; i < jsonArray2.size(); i ++){
result += ((JSONArray) jsonArray2.get(i)).get(0).toString();
JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0);
StringBuilder result = new StringBuilder();
for (Object o : jsonArray2) {
result.append(((JSONArray) o).get(0).toString());
}
return result;
return result.toString();
}
}

View File

@ -12,7 +12,6 @@ public class ValidationUtil{
/**
*
* @param optional
*/
public static void isNull(Optional optional, String entity,String parameter , Object value){
if(!optional.isPresent()){
@ -25,14 +24,12 @@ public class ValidationUtil{
/**
*
* @param string
* @return
*/
public static boolean isEmail(String string) {
if (string == null){
return false;
}
String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
String regEx1 = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
return string.matches(regEx1);
}
}

View File

@ -22,7 +22,7 @@ spring:
redis:
#数据库索引
database: 0
database: 1
host: 127.0.0.1
port: 6379
password:

View File

@ -11,6 +11,7 @@ public class EladminSystemApplicationTests {
@Test
public void contextLoads() {
}
}

View File

@ -18,66 +18,46 @@ public class AlipayConfig implements Serializable {
@Id
private Long id;
/**
* ID,APPIDAPPID
*/
// 应用ID,APPID收款账号既是APPID对应支付宝账号
@NotBlank
@Column(name = "app_id")
private String appID;
/**
* PKCS8RSA2
*/
// 商户私钥您的PKCS8格式RSA2私钥
@NotBlank
@Column(name = "private_key", columnDefinition = "text")
private String privateKey;
/**
*
*/
// 支付宝公钥
@NotBlank
@Column(name = "public_key", columnDefinition = "text")
private String publicKey;
/**
*
*/
// 签名方式,固定格式
@Column(name = "sign_type")
private String signType="RSA2";
/**
*
*/
// 支付宝开放安全地址,一般不会变
@Column(name = "gateway_url")
private String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
/**
*
*/
// 编码,固定格式
private String charset= "utf-8";
/**
*
*/
// 异步通知地址
@NotBlank
@Column(name = "notify_url")
private String notifyUrl;
/**
*
*/
// 订单完成后返回的页面
@NotBlank
@Column(name = "return_url")
private String returnUrl;
/**
*
*/
// 类型,固定格式
private String format="JSON";
/**
*
*/
// 商户号
@NotBlank
@Column(name = "sys_service_provider_id")
private String sysServiceProviderId;

View File

@ -19,30 +19,22 @@ public class EmailConfig implements Serializable {
@Id
private Long id;
/**
*SMTP
*/
// 邮件服务器SMTP地址
@NotBlank
private String host;
/**
* SMTP
*/
// 邮件服务器SMTP端口
@NotBlank
private String port;
/**
*
*/
// 发件者用户名,默认为发件人邮箱前缀
@NotBlank
private String user;
@NotBlank
private String pass;
/**
*
*/
// 收件人
@NotBlank
@Column(name = "from_user")
private String fromUser;

View File

@ -32,9 +32,6 @@ public class Picture implements Serializable {
private String width;
/**
* delete URl
*/
@Column(name = "delete_url")
private String delete;

View File

@ -18,23 +18,17 @@ public class QiniuConfig implements Serializable {
@Id
private Long id;
/**
* (Access/Secret Key)
*/
// 一个账号最多拥有两对密钥(Access/Secret Key)
@NotBlank
@Column(name = "access_key", columnDefinition = "text")
private String accessKey;
/**
* (Access/Secret Key)
*/
// 一个账号最多拥有两对密钥(Access/Secret Key)
@NotBlank
@Column(name = "secret_key", columnDefinition = "text")
private String secretKey;
/**
* Bucket
*/
// 存储空间名称作为唯一的 Bucket 识别符
@NotBlank
private String bucket;
@ -49,14 +43,10 @@ public class QiniuConfig implements Serializable {
@NotBlank
private String zone;
/**
*
*/
// 外链域名,可自定义,需在七牛云绑定
@NotBlank
private String host;
/**
* /
*/
// 空间类型:公开/私有
private String type = "公开";
}

View File

@ -21,37 +21,25 @@ public class QiniuContent implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* qiniu.jpg
*/
// 文件名
@Column(name = "name",unique = false)
private String key;
/**
*
*/
// 空间名
private String bucket;
/**
*
*/
// 大小
private String size;
/**
*
*/
// 文件地址
private String url;
private String suffix;
/**
* /
*/
// 空间类型:公开/私有
private String type = "公开";
/**
*
*/
// 更新时间
@UpdateTimestamp
@Column(name = "update_time")
private Timestamp updateTime;

View File

@ -26,32 +26,21 @@ public class VerificationCode {
private String code;
/**
* 使
*/
// 使用场景,自己定义
private String scenes;
/**
* true false ++
*/
// true 为有效false 为无效,验证时状态+时间+具体的邮箱或者手机号
private Boolean status = true;
/**
* phone email
*/
// 类型 phone 和 email
@NotBlank
private String type;
/**
* phoneemail
*/
// 具体的phone与email
@NotBlank
private String value;
/**
*
*/
// 创建日期
@CreationTimestamp
@Column(name = "create_time")
private Timestamp createTime;

View File

@ -18,9 +18,7 @@ import java.util.List;
@NoArgsConstructor
public class EmailVo {
/**
*
*/
// 收件人,支持多个收件人,用逗号分隔
@NotEmpty
private List<String> tos;

View File

@ -15,51 +15,35 @@ import java.sql.Timestamp;
@Data
public class TradeVo {
/**
*
*/
// (必填)商品描述
@NotBlank
private String body;
/**
*
*/
// (必填)商品名称
@NotBlank
private String subject;
/**
*
*/
// (必填)商户订单号,应该由后台生成
@ApiModelProperty(hidden = true)
private String outTradeNo;
/**
*
*/
// (必填)第三方订单号
@ApiModelProperty(hidden = true)
private String tradeNo;
/**
*
*/
// (必填)价格
@NotBlank
private String totalAmount;
/**
* ,
*/
// 订单状态,已支付,未支付,作废
@ApiModelProperty(hidden = true)
private String state;
/**
*
*/
// 创建时间,存入数据库时需要
@ApiModelProperty(hidden = true)
private Timestamp createTime;
/**
*
*/
// 作废时间,存入数据库时需要
@ApiModelProperty(hidden = true)
private Date cancelTime;
}

View File

@ -8,5 +8,5 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @author Zheng Jie
* @date 2019-09-05
*/
public interface LocalStorageRepository extends JpaRepository<LocalStorage, Long>, JpaSpecificationExecutor {
public interface LocalStorageRepository extends JpaRepository<LocalStorage, Long>, JpaSpecificationExecutor<LocalStorage> {
}

View File

@ -8,5 +8,5 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @author Zheng Jie
* @date 2018-12-27
*/
public interface PictureRepository extends JpaRepository<Picture,Long>, JpaSpecificationExecutor {
public interface PictureRepository extends JpaRepository<Picture,Long>, JpaSpecificationExecutor<Picture> {
}

View File

@ -12,6 +12,6 @@ import org.springframework.data.jpa.repository.Query;
public interface QiNiuConfigRepository extends JpaRepository<QiniuConfig,Long> {
@Modifying
@Query(value = "update qiniu_content set type = ?1", nativeQuery = true)
@Query(value = "update QiniuConfig set type = ?1")
void update(String type);
}

View File

@ -8,12 +8,12 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @author Zheng Jie
* @date 2018-12-31
*/
public interface QiniuContentRepository extends JpaRepository<QiniuContent,Long>, JpaSpecificationExecutor {
public interface QiniuContentRepository extends JpaRepository<QiniuContent,Long>, JpaSpecificationExecutor<QiniuContent> {
/**
* key
* @param key
* @return
* @param key
* @return QiniuContent
*/
QiniuContent findByKey(String key);
}

View File

@ -1,5 +1,6 @@
package me.zhengjie.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.log.Log;
@ -16,6 +17,7 @@ import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
@ -24,22 +26,26 @@ import java.util.Map;
*/
@Slf4j
@RestController
@RequestMapping("/api")
@RequestMapping("/api/aliPay")
@Api(tags = "支付宝支付管理")
public class AliPayController {
@Autowired
AlipayUtils alipayUtils;
private final AlipayUtils alipayUtils;
@Autowired
private AlipayService alipayService;
private final AlipayService alipayService;
@GetMapping(value = "/aliPay")
public AliPayController(AlipayUtils alipayUtils, AlipayService alipayService) {
this.alipayUtils = alipayUtils;
this.alipayService = alipayService;
}
@GetMapping
public ResponseEntity<AlipayConfig> get(){
return new ResponseEntity<>(alipayService.find(),HttpStatus.OK);
}
@Log("配置支付宝")
@PutMapping(value = "/aliPay")
@PutMapping
public ResponseEntity payConfig(@Validated @RequestBody AlipayConfig alipayConfig){
alipayConfig.setId(1L);
alipayService.update(alipayConfig);
@ -48,7 +54,7 @@ public class AliPayController {
@Log("支付宝PC网页支付")
@ApiOperation(value = "PC网页支付")
@PostMapping(value = "/aliPay/toPayAsPC")
@PostMapping(value = "/toPayAsPC")
public ResponseEntity<String> toPayAsPC(@Validated@RequestBody TradeVo trade) throws Exception{
AlipayConfig alipay = alipayService.find();
trade.setOutTradeNo(alipayUtils.getOrderCode());
@ -58,7 +64,7 @@ public class AliPayController {
@Log("支付宝手机网页支付")
@ApiOperation(value = "手机网页支付")
@PostMapping(value = "/aliPay/toPayAsWeb")
@PostMapping(value = "/toPayAsWeb")
public ResponseEntity<String> toPayAsWeb(@Validated @RequestBody TradeVo trade) throws Exception{
AlipayConfig alipay = alipayService.find();
trade.setOutTradeNo(alipayUtils.getOrderCode());
@ -67,7 +73,7 @@ public class AliPayController {
}
@ApiIgnore
@GetMapping("/aliPay/return")
@GetMapping("/return")
@ApiOperation(value = "支付之后跳转的链接")
public ResponseEntity<String> returnPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
AlipayConfig alipay = alipayService.find();
@ -75,47 +81,39 @@ public class AliPayController {
//内容验签,防止黑客篡改参数
if(alipayUtils.rsaCheck(request,alipay)){
//商户订单号
String outTradeNo = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//支付宝交易号
String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
System.out.println("商户订单号"+outTradeNo+" "+"第三方交易号"+tradeNo);
/**
* OK
*/
// 根据业务需要返回数据这里统一返回OK
return new ResponseEntity<>("payment successful",HttpStatus.OK);
}else{
/**
*
*/
// 根据业务需要返回数据
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
@ApiIgnore
@RequestMapping("/aliPay/notify")
@RequestMapping("/notify")
@ApiOperation(value = "支付异步通知(要公网访问)接收异步通知检查通知内容app_id、out_trade_no、total_amount是否与请求中的一致根据trade_status进行后续业务处理")
public ResponseEntity notify(HttpServletRequest request) throws Exception{
AlipayConfig alipay = alipayService.find();
Map<String, String[]> parameterMap = request.getParameterMap();
StringBuilder notifyBuild = new StringBuilder("/****************************** pay notify ******************************/\n");
parameterMap.forEach((key, value) -> notifyBuild.append(key + "=" + value[0] + "\n") );
//内容验签,防止黑客篡改参数
if (alipayUtils.rsaCheck(request,alipay)) {
//交易状态
String tradeStatus = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
String tradeStatus = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
// 商户订单号
String outTradeNo = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//支付宝交易号
String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//付款金额
String totalAmount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//验证
if(tradeStatus.equals(AliPayStatusEnum.SUCCESS.getValue())||tradeStatus.equals(AliPayStatusEnum.FINISHED.getValue())){
/**
*
*/
}
// if(tradeStatus.equals(AliPayStatusEnum.SUCCESS.getValue())||tradeStatus.equals(AliPayStatusEnum.FINISHED.getValue())){
// // 验证通过后应该根据业务需要处理订单
// }
return new ResponseEntity(HttpStatus.OK);
}
return new ResponseEntity(HttpStatus.BAD_REQUEST);

View File

@ -1,11 +1,11 @@
package me.zhengjie.rest;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.domain.EmailConfig;
import me.zhengjie.domain.vo.EmailVo;
import me.zhengjie.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
@ -16,30 +16,34 @@ import org.springframework.web.bind.annotation.*;
* @author
* @date 2018/09/28 6:55:53
*/
@Slf4j
@RestController
@RequestMapping("api")
@RequestMapping("api/email")
@Api(tags = "邮件管理")
public class EmailController {
@Autowired
private EmailService emailService;
private final EmailService emailService;
@GetMapping(value = "/email")
public EmailController(EmailService emailService) {
this.emailService = emailService;
}
@GetMapping
public ResponseEntity get(){
return new ResponseEntity(emailService.find(),HttpStatus.OK);
return new ResponseEntity<>(emailService.find(),HttpStatus.OK);
}
@Log("配置邮件")
@PutMapping(value = "/email")
@PutMapping
@ApiOperation(value = "配置邮件")
public ResponseEntity emailConfig(@Validated @RequestBody EmailConfig emailConfig){
emailService.update(emailConfig,emailService.find());
return new ResponseEntity(HttpStatus.OK);
}
@Log("发送邮件")
@PostMapping(value = "/email")
@PostMapping
@ApiOperation(value = "发送邮件")
public ResponseEntity send(@Validated @RequestBody EmailVo emailVo) throws Exception {
log.warn("REST request to send Email : {}" +emailVo);
emailService.send(emailVo,emailService.find());
return new ResponseEntity(HttpStatus.OK);
}

View File

@ -4,7 +4,6 @@ import me.zhengjie.aop.log.Log;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.service.LocalStorageService;
import me.zhengjie.service.dto.LocalStorageQueryCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ -20,28 +19,31 @@ import org.springframework.web.multipart.MultipartFile;
*/
@Api(tags = "本地存储管理")
@RestController
@RequestMapping("api")
@RequestMapping("/api/localStorage")
public class LocalStorageController {
@Autowired
private LocalStorageService localStorageService;
private final LocalStorageService localStorageService;
public LocalStorageController(LocalStorageService localStorageService) {
this.localStorageService = localStorageService;
}
@ApiOperation(value = "查询文件")
@GetMapping(value = "/localStorage")
@GetMapping
@PreAuthorize("hasAnyRole('ADMIN','LOCALSTORAGE_ALL','LOCALSTORAGE_SELECT')")
public ResponseEntity getLocalStorages(LocalStorageQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(localStorageService.queryAll(criteria,pageable),HttpStatus.OK);
return new ResponseEntity<>(localStorageService.queryAll(criteria,pageable),HttpStatus.OK);
}
@ApiOperation(value = "上传文件")
@PostMapping(value = "/localStorage")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','LOCALSTORAGE_ALL','LOCALSTORAGE_CREATE')")
public ResponseEntity create(@RequestParam String name, @RequestParam("file") MultipartFile file){
return new ResponseEntity(localStorageService.create(name, file),HttpStatus.CREATED);
return new ResponseEntity<>(localStorageService.create(name, file),HttpStatus.CREATED);
}
@ApiOperation(value = "修改文件")
@PutMapping(value = "/localStorage")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','LOCALSTORAGE_ALL','LOCALSTORAGE_EDIT')")
public ResponseEntity update(@Validated @RequestBody LocalStorage resources){
localStorageService.update(resources);
@ -49,20 +51,16 @@ public class LocalStorageController {
}
@ApiOperation(value = "删除文件")
@DeleteMapping(value = "/localStorage/{id}")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','LOCALSTORAGE_ALL','LOCALSTORAGE_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
localStorageService.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
/**
*
* @param ids
* @return
*/
@Log("删除图片")
@DeleteMapping(value = "/localStorage")
@Log("多选删除")
@DeleteMapping
@ApiOperation(value = "多选删除")
public ResponseEntity deleteAll(@RequestBody Long[] ids) {
localStorageService.deleteAll(ids);
return new ResponseEntity(HttpStatus.OK);

View File

@ -1,11 +1,12 @@
package me.zhengjie.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.domain.Picture;
import me.zhengjie.service.PictureService;
import me.zhengjie.service.dto.PictureQueryCriteria;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ -20,28 +21,28 @@ import java.util.Map;
* @date 2018/09/20 14:13:32
*/
@RestController
@RequestMapping("/api")
@RequestMapping("/api/pictures")
@Api(tags = "免费图床管理")
public class PictureController {
@Autowired
private PictureService pictureService;
private final PictureService pictureService;
public PictureController(PictureService pictureService) {
this.pictureService = pictureService;
}
@Log("查询图片")
@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_SELECT')")
@GetMapping(value = "/pictures")
@GetMapping
@ApiOperation(value = "查询图片")
public ResponseEntity getRoles(PictureQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(pictureService.queryAll(criteria,pageable),HttpStatus.OK);
return new ResponseEntity<>(pictureService.queryAll(criteria,pageable),HttpStatus.OK);
}
/**
*
* @param file
* @return
* @throws Exception
*/
@Log("上传图片")
@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_UPLOAD')")
@PostMapping(value = "/pictures")
@PostMapping
@ApiOperation(value = "上传图片")
public ResponseEntity upload(@RequestParam MultipartFile file){
String userName = SecurityUtils.getUsername();
Picture picture = pictureService.upload(file,userName);
@ -49,30 +50,22 @@ public class PictureController {
map.put("errno",0);
map.put("id",picture.getId());
map.put("data",new String[]{picture.getUrl()});
return new ResponseEntity(map,HttpStatus.OK);
return new ResponseEntity<>(map,HttpStatus.OK);
}
/**
*
* @param id
* @return
*/
@Log("删除图片")
@ApiOperation(value = "删除图片")
@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')")
@DeleteMapping(value = "/pictures/{id}")
@DeleteMapping(value = "/{id}")
public ResponseEntity delete(@PathVariable Long id) {
pictureService.delete(pictureService.findById(id));
return new ResponseEntity(HttpStatus.OK);
}
/**
*
* @param ids
* @return
*/
@Log("删除图片")
@Log("多选删除图片")
@ApiOperation(value = "多选删除图片")
@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')")
@DeleteMapping(value = "/pictures")
@DeleteMapping
public ResponseEntity deleteAll(@RequestBody Long[] ids) {
pictureService.deleteAll(ids);
return new ResponseEntity(HttpStatus.OK);

View File

@ -1,12 +1,13 @@
package me.zhengjie.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.log.Log;
import me.zhengjie.domain.QiniuConfig;
import me.zhengjie.domain.QiniuContent;
import me.zhengjie.service.QiNiuService;
import me.zhengjie.service.dto.QiniuQueryCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ -24,17 +25,22 @@ import java.util.Map;
@Slf4j
@RestController
@RequestMapping("api")
@Api(tags = "七牛云存储管理")
public class QiniuController {
@Autowired
private QiNiuService qiNiuService;
private final QiNiuService qiNiuService;
public QiniuController(QiNiuService qiNiuService) {
this.qiNiuService = qiNiuService;
}
@GetMapping(value = "/qiNiuConfig")
public ResponseEntity get(){
return new ResponseEntity(qiNiuService.find(), HttpStatus.OK);
return new ResponseEntity<>(qiNiuService.find(), HttpStatus.OK);
}
@Log("配置七牛云存储")
@ApiOperation(value = "配置七牛云存储")
@PutMapping(value = "/qiNiuConfig")
public ResponseEntity emailConfig(@Validated @RequestBody QiniuConfig qiniuConfig){
qiNiuService.update(qiniuConfig);
@ -43,72 +49,51 @@ public class QiniuController {
}
@Log("查询文件")
@ApiOperation(value = "查询文件")
@GetMapping(value = "/qiNiuContent")
public ResponseEntity getRoles(QiniuQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(qiNiuService.queryAll(criteria,pageable),HttpStatus.OK);
return new ResponseEntity<>(qiNiuService.queryAll(criteria,pageable),HttpStatus.OK);
}
/**
*
* @param file
* @return
*/
@Log("上传文件")
@ApiOperation(value = "上传文件")
@PostMapping(value = "/qiNiuContent")
public ResponseEntity upload(@RequestParam MultipartFile file){
QiniuContent qiniuContent = qiNiuService.upload(file,qiNiuService.find());
Map map = new HashMap(3);
Map<String,Object> map = new HashMap<>(3);
map.put("id",qiniuContent.getId());
map.put("errno",0);
map.put("data",new String[]{qiniuContent.getUrl()});
return new ResponseEntity(map,HttpStatus.OK);
return new ResponseEntity<>(map,HttpStatus.OK);
}
/**
*
* @return
*/
@Log("同步七牛云数据")
@ApiOperation(value = "同步七牛云数据")
@PostMapping(value = "/qiNiuContent/synchronize")
public ResponseEntity synchronize(){
log.warn("REST request to synchronize qiNiu : {}");
qiNiuService.synchronize(qiNiuService.find());
return new ResponseEntity(HttpStatus.OK);
}
/**
*
* @param id
* @return
* @throws Exception
*/
@Log("下载文件")
@ApiOperation(value = "下载文件")
@GetMapping(value = "/qiNiuContent/download/{id}")
public ResponseEntity download(@PathVariable Long id){
Map map = new HashMap(1);
Map<String,Object> map = new HashMap<>(1);
map.put("url", qiNiuService.download(qiNiuService.findByContentId(id),qiNiuService.find()));
return new ResponseEntity(map,HttpStatus.OK);
return new ResponseEntity<>(map,HttpStatus.OK);
}
/**
*
* @param id
* @return
* @throws Exception
*/
@Log("删除文件")
@ApiOperation(value = "删除文件")
@DeleteMapping(value = "/qiNiuContent/{id}")
public ResponseEntity delete(@PathVariable Long id){
qiNiuService.delete(qiNiuService.findByContentId(id),qiNiuService.find());
return new ResponseEntity(HttpStatus.OK);
}
/**
*
* @param ids
* @return
*/
@Log("删除图片")
@Log("删除多张图片")
@ApiOperation(value = "删除多张图片")
@DeleteMapping(value = "/qiNiuContent")
public ResponseEntity deleteAll(@RequestBody Long[] ids) {
qiNiuService.deleteAll(ids, qiNiuService.find());

View File

@ -1,11 +1,12 @@
package me.zhengjie.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.domain.VerificationCode;
import me.zhengjie.domain.vo.EmailVo;
import me.zhengjie.service.EmailService;
import me.zhengjie.service.VerificationCodeService;
import me.zhengjie.utils.ElAdminConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ -18,19 +19,20 @@ import org.springframework.web.bind.annotation.*;
*/
@RestController
@RequestMapping("api")
@Api(tags = "验证码管理")
public class VerificationCodeController {
@Autowired
private VerificationCodeService verificationCodeService;
private final VerificationCodeService verificationCodeService;
@Autowired
@Qualifier("jwtUserDetailsService")
private UserDetailsService userDetailsService;
private final EmailService emailService;
@Autowired
private EmailService emailService;
public VerificationCodeController(VerificationCodeService verificationCodeService, @Qualifier("jwtUserDetailsService") UserDetailsService userDetailsService, EmailService emailService) {
this.verificationCodeService = verificationCodeService;
this.emailService = emailService;
}
@PostMapping(value = "/code/resetEmail")
@ApiOperation(value = "重置邮箱,发送验证码")
public ResponseEntity resetEmail(@RequestBody VerificationCode code) throws Exception {
code.setScenes(ElAdminConstant.RESET_MAIL);
EmailVo emailVo = verificationCodeService.sendEmail(code);
@ -39,6 +41,7 @@ public class VerificationCodeController {
}
@PostMapping(value = "/code/email/resetPass")
@ApiOperation(value = "重置密码,发送验证码")
public ResponseEntity resetPass(@RequestParam String email) throws Exception {
VerificationCode code = new VerificationCode();
code.setType("email");
@ -50,6 +53,7 @@ public class VerificationCodeController {
}
@GetMapping(value = "/code/validated")
@ApiOperation(value = "验证码验证")
public ResponseEntity validated(VerificationCode code){
verificationCodeService.validated(code);
return new ResponseEntity(HttpStatus.OK);

View File

@ -15,33 +15,33 @@ public interface AlipayService {
/**
* PC
* @param alipay
* @param trade
* @return
* @throws Exception
* @param alipay
* @param trade
* @return String
* @throws Exception
*/
String toPayAsPC(AlipayConfig alipay, TradeVo trade) throws Exception;
/**
*
* @param alipay
* @param trade
* @return
* @throws Exception
* @param alipay
* @param trade
* @return String
* @throws Exception
*/
String toPayAsWeb(AlipayConfig alipay, TradeVo trade) throws Exception;
/**
*
* @return
* @return AlipayConfig
*/
@Cacheable(key = "'1'")
AlipayConfig find();
/**
*
* @param alipayConfig
* @return
* @param alipayConfig
* @return AlipayConfig
*/
@CachePut(key = "'1'")
AlipayConfig update(AlipayConfig alipayConfig);

View File

@ -16,24 +16,24 @@ public interface EmailService {
/**
*
* @param emailConfig
* @param old
* @return
* @param emailConfig
* @param old
* @return EmailConfig
*/
@CachePut(key = "'1'")
EmailConfig update(EmailConfig emailConfig, EmailConfig old);
/**
*
* @return
* @return EmailConfig
*/
@Cacheable(key = "'1'")
EmailConfig find();
/**
*
* @param emailVo
* @param emailConfig
* @param emailVo
* @param emailConfig
* @throws Exception
*/
@Async

View File

@ -18,52 +18,56 @@ public interface LocalStorageService {
/**
* queryAll
* @param criteria
* @param pageable
* @return
* @param criteria
* @param pageable
* @return Object
*/
@Cacheable
Object queryAll(LocalStorageQueryCriteria criteria, Pageable pageable);
/**
* queryAll
* @param criteria
* @return
* @param criteria
* @return Object
*/
@Cacheable
public Object queryAll(LocalStorageQueryCriteria criteria);
Object queryAll(LocalStorageQueryCriteria criteria);
/**
* findById
* @param id
* @return
* @return LocalStorageDTO
*/
@Cacheable(key = "#p0")
LocalStorageDTO findById(Long id);
/**
* create
* @param name
* @param file
* @return
* @param name
* @param file
* @return LocalStorageDTO
*/
@CacheEvict(allEntries = true)
LocalStorageDTO create(String name, MultipartFile file);
/**
* update
* @param resources
* @param resources
*/
@CacheEvict(allEntries = true)
void update(LocalStorage resources);
/**
* delete
* @param id
* @param id ID
*/
@CacheEvict(allEntries = true)
void delete(Long id);
/**
*
* @param ids
*/
@CacheEvict(allEntries = true)
void deleteAll(Long[] ids);
}

View File

@ -16,17 +16,17 @@ public interface PictureService {
/**
*
* @param criteria
* @param pageable
* @return
* @param criteria
* @param pageable
* @return Object
*/
@Cacheable
Object queryAll(PictureQueryCriteria criteria, Pageable pageable);
/**
*
* @param file
* @param username
* @param file
* @param username
* @return
*/
@CacheEvict(allEntries = true)
@ -34,7 +34,7 @@ public interface PictureService {
/**
* ID
* @param id
* @param id ID
* @return
*/
@Cacheable(key = "#p0")
@ -42,14 +42,14 @@ public interface PictureService {
/**
*
* @param picture
* @param picture
*/
@CacheEvict(allEntries = true)
void delete(Picture picture);
/**
*
* @param ids
* @param ids ID
*/
@CacheEvict(allEntries = true)
void deleteAll(Long[] ids);

View File

@ -20,16 +20,16 @@ public interface QiNiuService {
/**
*
* @param criteria
* @param pageable
* @return
* @param criteria
* @param pageable
* @return Object
*/
@Cacheable
Object queryAll(QiniuQueryCriteria criteria, Pageable pageable);
/**
*
* @return
* @return Cacheable
*/
@Cacheable(cacheNames = "qiNiuConfig", key = "'1'")
QiniuConfig find();
@ -37,7 +37,7 @@ public interface QiNiuService {
/**
*
* @param qiniuConfig
* @return
* @return QiniuConfig
*/
@CachePut(cacheNames = "qiNiuConfig", key = "'1'")
QiniuConfig update(QiniuConfig qiniuConfig);
@ -46,7 +46,7 @@ public interface QiNiuService {
*
* @param file
* @param qiniuConfig
* @return
* @return QiniuContent
*/
@CacheEvict(allEntries = true)
QiniuContent upload(MultipartFile file, QiniuConfig qiniuConfig);
@ -54,7 +54,7 @@ public interface QiNiuService {
/**
*
* @param id
* @return
* @return QiniuContent
*/
@Cacheable(key = "'content:'+#p0")
QiniuContent findByContentId(Long id);
@ -63,34 +63,37 @@ public interface QiNiuService {
*
* @param content
* @param config
* @return
* @return String
*/
String download(QiniuContent content, QiniuConfig config);
/**
*
* @param content
* @param config
* @return
* @param content
* @param config
*/
@CacheEvict(allEntries = true)
void delete(QiniuContent content, QiniuConfig config);
/**
*
* @param config
* @param config
*/
@CacheEvict(allEntries = true)
void synchronize(QiniuConfig config);
/**
*
* @param ids
* @param config
* @param ids ID
* @param config
*/
@CacheEvict(allEntries = true)
void deleteAll(Long[] ids, QiniuConfig config);
/**
*
* @param type
*/
@CacheEvict(allEntries = true)
void update(String type);
}

View File

@ -11,13 +11,14 @@ public interface VerificationCodeService {
/**
*
* @param code
* @param code
* @return EmailVo
*/
EmailVo sendEmail(VerificationCode code);
/**
*
* @param code
* @param code
*/
void validated(VerificationCode code);
}

View File

@ -40,19 +40,13 @@ public class AlipayServiceImpl implements AlipayService {
double money = Double.parseDouble(trade.getTotalAmount());
/**
* APIrequest()
*/
// 创建API对应的request(电脑网页版)
AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
/**
*
*/
// 订单完成后返回的页面和异步通知地址
request.setReturnUrl(alipay.getReturnUrl());
request.setNotifyUrl(alipay.getNotifyUrl());
/**
*
*/
// 填充订单参数
request.setBizContent("{" +
" \"out_trade_no\":\""+trade.getOutTradeNo()+"\"," +
" \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
@ -63,10 +57,7 @@ public class AlipayServiceImpl implements AlipayService {
" \"sys_service_provider_id\":\""+alipay.getSysServiceProviderId()+"\"" +
" }"+
" }");//填充业务参数
/**
* SDK
* GETurl
*/
// 调用SDK生成表单, 通过GET方式口可以获取url
return alipayClient.pageExecute(request, "GET").getBody();
}
@ -82,20 +73,10 @@ public class AlipayServiceImpl implements AlipayService {
if(money <= 0 || money >= 5000){
throw new BadRequestException("测试金额过大");
}
/**
* APIrequest()
*/
// 创建API对应的request(手机网页版)
AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
/**
*
*/
request.setReturnUrl(alipay.getReturnUrl());
request.setNotifyUrl(alipay.getNotifyUrl());
/**
*
*/
request.setBizContent("{" +
" \"out_trade_no\":\""+trade.getOutTradeNo()+"\"," +
" \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
@ -106,21 +87,13 @@ public class AlipayServiceImpl implements AlipayService {
" \"sys_service_provider_id\":\""+alipay.getSysServiceProviderId()+"\"" +
" }"+
" }");//填充业务参数
/**
* SDK
* GETurl
*/
return alipayClient.pageExecute(request, "GET").getBody();
}
@Override
public AlipayConfig find() {
Optional<AlipayConfig> alipayConfig = alipayRepository.findById(1L);
if (alipayConfig.isPresent()){
return alipayConfig.get();
} else {
return new AlipayConfig();
}
return alipayConfig.orElseGet(AlipayConfig::new);
}
@Override

View File

@ -2,15 +2,12 @@ package me.zhengjie.service.impl;
import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import me.zhengjie.domain.EmailConfig;
import me.zhengjie.domain.vo.EmailVo;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.repository.EmailRepository;
import me.zhengjie.service.EmailService;
import me.zhengjie.utils.ElAdminConstant;
import me.zhengjie.utils.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@ -24,8 +21,11 @@ import java.util.Optional;
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class EmailServiceImpl implements EmailService {
@Autowired
private EmailRepository emailRepository;
private final EmailRepository emailRepository;
public EmailServiceImpl(EmailRepository emailRepository) {
this.emailRepository = emailRepository;
}
@Override
@Transactional(rollbackFor = Exception.class)
@ -44,11 +44,7 @@ public class EmailServiceImpl implements EmailService {
@Override
public EmailConfig find() {
Optional<EmailConfig> emailConfig = emailRepository.findById(1L);
if(emailConfig.isPresent()){
return emailConfig.get();
} else {
return new EmailConfig();
}
return emailConfig.orElseGet(EmailConfig::new);
}
@Override
@ -57,9 +53,7 @@ public class EmailServiceImpl implements EmailService {
if(emailConfig == null){
throw new BadRequestException("请先配置,再操作");
}
/**
*
*/
// 封装
MailAccount account = new MailAccount();
account.setHost(emailConfig.getHost());
account.setPort(Integer.parseInt(emailConfig.getPort()));
@ -71,15 +65,14 @@ public class EmailServiceImpl implements EmailService {
throw new BadRequestException(e.getMessage());
}
account.setFrom(emailConfig.getUser()+"<"+emailConfig.getFromUser()+">");
//ssl方式发送
// ssl方式发送
account.setSslEnable(true);
String content = emailVo.getContent();
/**
*
*/
// 发送
try {
int size = emailVo.getTos().size();
Mail.create(account)
.setTos(emailVo.getTos().toArray(new String[emailVo.getTos().size()]))
.setTos(emailVo.getTos().toArray(new String[size]))
.setTitle(emailVo.getSubject())
.setContent(content)
.setHtml(true)

View File

@ -1,19 +1,16 @@
package me.zhengjie.service.impl;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.*;
import me.zhengjie.repository.LocalStorageRepository;
import me.zhengjie.service.LocalStorageService;
import me.zhengjie.service.dto.LocalStorageDTO;
import me.zhengjie.service.dto.LocalStorageQueryCriteria;
import me.zhengjie.service.mapper.LocalStorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.util.Optional;
import org.springframework.data.domain.Page;
@ -28,11 +25,9 @@ import org.springframework.web.multipart.MultipartFile;
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class LocalStorageServiceImpl implements LocalStorageService {
@Autowired
private LocalStorageRepository localStorageRepository;
private final LocalStorageRepository localStorageRepository;
@Autowired
private LocalStorageMapper localStorageMapper;
private final LocalStorageMapper localStorageMapper;
@Value("${file.path}")
private String path;
@ -40,6 +35,11 @@ public class LocalStorageServiceImpl implements LocalStorageService {
@Value("${file.maxSize}")
private long maxSize;
public LocalStorageServiceImpl(LocalStorageRepository localStorageRepository, LocalStorageMapper localStorageMapper) {
this.localStorageRepository = localStorageRepository;
this.localStorageMapper = localStorageMapper;
}
@Override
public Object queryAll(LocalStorageQueryCriteria criteria, Pageable pageable){
Page<LocalStorage> page = localStorageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
@ -85,11 +85,6 @@ public class LocalStorageServiceImpl implements LocalStorageService {
}
}
public static void main(String[] args) {
File file = new File("C:\\Users\\Jie\\Pictures\\Saved Pictures\\demo1.jpg");
System.out.println(FileUtil.getType(file));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(LocalStorage resources) {

View File

@ -30,14 +30,17 @@ import java.util.Optional;
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class PictureServiceImpl implements PictureService {
@Autowired
private PictureRepository pictureRepository;
private final PictureRepository pictureRepository;
public static final String SUCCESS = "success";
private static final String SUCCESS = "success";
public static final String CODE = "code";
private static final String CODE = "code";
public static final String MSG = "message";
private static final String MSG = "message";
public PictureServiceImpl(PictureRepository pictureRepository) {
this.pictureRepository = pictureRepository;
}
@Override
public Object queryAll(PictureQueryCriteria criteria, Pageable pageable){
@ -60,7 +63,7 @@ public class PictureServiceImpl implements PictureService {
}
//转成实体类
picture = JSON.parseObject(jsonObject.get("data").toString(), Picture.class);
picture.setSize(FileUtil.getSize(Integer.valueOf(picture.getSize())));
picture.setSize(FileUtil.getSize(Integer.parseInt(picture.getSize())));
picture.setUsername(username);
picture.setFilename(FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename())+"."+FileUtil.getExtensionName(multipartFile.getOriginalFilename()));
pictureRepository.save(picture);

View File

@ -1,6 +1,6 @@
package me.zhengjie.service.impl;
import com.google.gson.Gson;
import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
@ -16,7 +16,11 @@ import me.zhengjie.repository.QiNiuConfigRepository;
import me.zhengjie.repository.QiniuContentRepository;
import me.zhengjie.service.QiNiuService;
import me.zhengjie.service.dto.QiniuQueryCriteria;
import me.zhengjie.utils.*;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QiNiuUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
@ -24,6 +28,8 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
import java.util.Optional;
/**
@ -34,17 +40,18 @@ import java.util.Optional;
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class QiNiuServiceImpl implements QiNiuService {
@Autowired
private QiNiuConfigRepository qiNiuConfigRepository;
private final QiNiuConfigRepository qiNiuConfigRepository;
@Autowired
private QiniuContentRepository qiniuContentRepository;
private final QiniuContentRepository qiniuContentRepository;
public QiNiuServiceImpl(QiNiuConfigRepository qiNiuConfigRepository, QiniuContentRepository qiniuContentRepository) {
this.qiNiuConfigRepository = qiNiuConfigRepository;
this.qiniuContentRepository = qiniuContentRepository;
}
@Value("${qiniu.max-size}")
private Long maxSize;
private final String TYPE = "公开";
@Override
public Object queryAll(QiniuQueryCriteria criteria, Pageable pageable){
return PageUtil.toPage(qiniuContentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable));
@ -53,11 +60,7 @@ public class QiNiuServiceImpl implements QiNiuService {
@Override
public QiniuConfig find() {
Optional<QiniuConfig> qiniuConfig = qiNiuConfigRepository.findById(1L);
if(qiniuConfig.isPresent()){
return qiniuConfig.get();
} else {
return new QiniuConfig();
}
return qiniuConfig.orElseGet(QiniuConfig::new);
}
@Override
@ -77,9 +80,7 @@ public class QiNiuServiceImpl implements QiNiuService {
if(qiniuConfig.getId() == null){
throw new BadRequestException("请先添加相应配置,再操作");
}
/**
* Zone
*/
// 构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(QiNiuUtil.getRegion(qiniuConfig.getZone()));
UploadManager uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
@ -91,7 +92,8 @@ public class QiNiuServiceImpl implements QiNiuService {
}
Response response = uploadManager.put(file.getBytes(), key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
//存入数据库
QiniuContent qiniuContent = new QiniuContent();
qiniuContent.setSuffix(FileUtil.getExtensionName(putRet.key));
@ -116,13 +118,12 @@ public class QiNiuServiceImpl implements QiNiuService {
@Override
public String download(QiniuContent content,QiniuConfig config){
String finalUrl = null;
String TYPE = "公开";
if(TYPE.equals(content.getType())){
finalUrl = content.getUrl();
} else {
Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
/**
* 1
*/
// 1小时可以自定义链接过期时间
long expireInSeconds = 3600;
finalUrl = auth.privateDownloadUrl(content.getUrl(), expireInSeconds);
}

View File

@ -17,6 +17,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.*;
/**
@ -45,12 +46,12 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
if(verificationCode == null){
code.setCode(RandomUtil.randomNumbers (6));
content = template.render(Dict.create().set("code",code.getCode()));
emailVo = new EmailVo(Arrays.asList(code.getValue()),"eladmin后台管理系统",content);
emailVo = new EmailVo(Collections.singletonList(code.getValue()),"eladmin后台管理系统",content);
timedDestruction(verificationCodeRepository.save(code));
// 存在就再次发送原来的验证码
} else {
content = template.render(Dict.create().set("code",verificationCode.getCode()));
emailVo = new EmailVo(Arrays.asList(verificationCode.getValue()),"eladmin后台管理系统",content);
emailVo = new EmailVo(Collections.singletonList(verificationCode.getValue()),"eladmin后台管理系统",content);
}
return emailVo;
}
@ -68,7 +69,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
/**
*
* @param verifyCode
* @param verifyCode
*/
private void timedDestruction(VerificationCode verifyCode) {
//以下示例为程序调用结束继续运行

View File

@ -27,11 +27,9 @@ public enum AliPayStatusEnum {
*/
CLOSED("交易关闭", "TRADE_CLOSED");
private String name;
private String value;
AliPayStatusEnum(String name, String value) {
this.name = name;
this.value = value;
}

View File

@ -22,7 +22,6 @@ public class AlipayUtils {
/**
*
* @return
*/
public String getOrderCode() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@ -35,24 +34,19 @@ public class AlipayUtils {
String[] split1 = s.split(" ");
String s1 = split1[0] + split1[1];
String[] split2 = s1.split(":");
String s2 = split2[0] + split2[1] + split2[2] + a;
return s2;
return split2[0] + split2[1] + split2[2] + a;
}
/**
*
* @param request
* @return
*/
public boolean rsaCheck(HttpServletRequest request, AlipayConfig alipay){
/**
* POST
*/
// 获取支付宝POST过来反馈信息
Map<String,String> params = new HashMap<>(1);
Map requestParams = request.getParameterMap();
for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
for (Object o : requestParams.keySet()) {
String name = (String) o;
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
@ -63,11 +57,10 @@ public class AlipayUtils {
}
try {
boolean verifyResult = AlipaySignature.rsaCheckV1(params,
return AlipaySignature.rsaCheckV1(params,
alipay.getPublicKey(),
alipay.getCharset(),
alipay.getSignType());
return verifyResult;
} catch (AlipayApiException e) {
return false;
}

View File

@ -11,18 +11,16 @@ import java.util.Date;
*/
public class QiNiuUtil {
public static final String HUAD = "华东";
private static final String HUAD = "华东";
public static final String HUAB = "华北";
private static final String HUAB = "华北";
public static final String HUAN = "华南";
private static final String HUAN = "华南";
public static final String BEIM = "北美";
private static final String BEIM = "北美";
/**
*
* @param zone
* @return
*/
public static Region getRegion(String zone){
@ -42,17 +40,13 @@ public class QiNiuUtil {
/**
* keyhash
* @param file
* @return
*/
public static String getKey(String file){
StringBuffer key = new StringBuffer(FileUtil.getFileNameNoEx(file));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
key.append("-");
key.append(sdf.format(date));
key.append(".");
key.append(FileUtil.getExtensionName(file));
return key.toString();
return FileUtil.getFileNameNoEx(file) + "-" +
sdf.format(date) +
"." +
FileUtil.getExtensionName(file);
}
}