add file
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
package cn.pluss.platform.annotation;
|
||||
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* @功能描述 防止重复提交标记注解
|
||||
* @author www.gaozz.club
|
||||
*
|
||||
*/
|
||||
@Target(ElementType.METHOD) // 作用到方法上
|
||||
@Retention(RetentionPolicy.RUNTIME) // 运行时有效
|
||||
public @interface NoRepeatSubmit {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package cn.pluss.platform.annotation;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import org.mapstruct.Mapping;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
/**
|
||||
* @author DJH
|
||||
*/
|
||||
@Retention(RetentionPolicy.CLASS)
|
||||
@Mapping(target = "id", ignore = true)
|
||||
@Mapping(target = "page", ignore = true)
|
||||
@Mapping(target = "size", ignore = true)
|
||||
public @interface ToEntity {
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package cn.pluss.platform.aop;
|
||||
|
||||
import cn.pluss.platform.annotation.NoRepeatSubmit;
|
||||
import cn.pluss.platform.api.ResultGenerator;
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import com.google.common.cache.Cache;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* @功能描述 aop解析注解
|
||||
*
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class NoRepeatSubmitAop {
|
||||
|
||||
|
||||
@Autowired
|
||||
private Cache<String, Integer> cache;
|
||||
|
||||
@Around("execution(* cn.pluss.platform.controller..*Controller.*(..)) && @annotation(nrs)")
|
||||
public Object arround(ProceedingJoinPoint pjp, NoRepeatSubmit nrs) {
|
||||
try {
|
||||
System.out.println("进入了切点:==================================>");
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
String key = sessionId + "-" + request.getServletPath();
|
||||
if (cache.getIfPresent(key) == null) {// 如果缓存中有这个url视为重复提交
|
||||
Object o = pjp.proceed();
|
||||
cache.put(key, 0);
|
||||
return o;
|
||||
} else {
|
||||
System.out.println("重复提交!!");
|
||||
return null;
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
e.printStackTrace();
|
||||
if (e instanceof MsgException) {
|
||||
throw (MsgException) e;
|
||||
}
|
||||
return ResultGenerator.genSuccessResult("验证重复提交时出现未知异常!", null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
20
pluss-common-bundle/src/main/java/cn/pluss/platform/aop/cache/UrlCache.java
vendored
Normal file
20
pluss-common-bundle/src/main/java/cn/pluss/platform/aop/cache/UrlCache.java
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
package cn.pluss.platform.aop.cache;
|
||||
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Configuration
|
||||
/**
|
||||
* @功能描述 内存缓存
|
||||
*
|
||||
*/
|
||||
public class UrlCache {
|
||||
@Bean
|
||||
public Cache<String, Integer> getCache() {
|
||||
return CacheBuilder.newBuilder().expireAfterWrite(5L, TimeUnit.SECONDS).build();// 缓存有效期为5秒
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package cn.pluss.platform.api;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class PageInfo<T> {
|
||||
|
||||
private Long count;
|
||||
private Long pageCount;
|
||||
private Long currPage ;
|
||||
private Long pageSize ;
|
||||
private List<T> data;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package cn.pluss.platform.api;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author DJH
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class PageVO<T> {
|
||||
|
||||
private int count;
|
||||
private int pageCount;
|
||||
private int currPage ;
|
||||
private int pageSize ;
|
||||
private T data;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package cn.pluss.platform.api;
|
||||
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 统一API响应结果封装
|
||||
* @author DJH
|
||||
*/
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class Result<T> {
|
||||
private int code;
|
||||
private String message;
|
||||
private T data;
|
||||
private String respCode;
|
||||
|
||||
private T list;
|
||||
|
||||
private String totalCount;
|
||||
|
||||
private String timestamp;
|
||||
|
||||
public Result<T> setCode(ResultCode resultCode) {
|
||||
this.code = resultCode.code();
|
||||
return this;
|
||||
}
|
||||
|
||||
public Result(ResultCode resultCode, String message) {
|
||||
this(resultCode, message, null);
|
||||
}
|
||||
|
||||
public Result(ResultCode resultCode, String message, T data) {
|
||||
this.code = resultCode.code();
|
||||
this.message = message;
|
||||
this.data = data;
|
||||
timestamp = DateUtil.format(new Date(), "yyyyMMddHHmmss");
|
||||
}
|
||||
|
||||
public Result(int code, String message, T data) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
this.data = data;
|
||||
timestamp = DateUtil.format(new Date(), "yyyyMMddHHmmss");
|
||||
}
|
||||
|
||||
public Result(int code, String message) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
timestamp = DateUtil.format(new Date(), "yyyyMMddHHmmss");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JSON.toJSONString(this);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package cn.pluss.platform.api;
|
||||
|
||||
/**
|
||||
* 响应码枚举,参考HTTP状态码的语义
|
||||
*/
|
||||
public enum ResultCode {
|
||||
//成功
|
||||
SUCCESS(200),
|
||||
//失败
|
||||
FAIL(400),
|
||||
//未认证(签名错误)
|
||||
UNAUTHORIZED(401),
|
||||
//未认证(签名错误)
|
||||
PARAM_ERROR(422),
|
||||
// 403
|
||||
FORBIDDEN(403),
|
||||
//接口不存在
|
||||
NOT_FOUND(404),
|
||||
//服务器内部错误
|
||||
INTERNAL_SERVER_ERROR(500),
|
||||
// 服务不可达
|
||||
SERVICE_UNAVAILABLE(503),
|
||||
//未认证(签名错误)
|
||||
NOT_TOKEN(401),
|
||||
//无数据
|
||||
UNDEFINDE(201),
|
||||
/**
|
||||
* 交易未知 查询交易结果
|
||||
*/
|
||||
TRANSUNKNOW(202);
|
||||
|
||||
private final int code;
|
||||
|
||||
ResultCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public int code() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package cn.pluss.platform.api;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.apache.poi.ss.formula.functions.T;
|
||||
|
||||
/**
|
||||
* 响应结果生成工具
|
||||
*/
|
||||
public class ResultGenerator {
|
||||
public static final String DEFAULT_SUCCESS_MESSAGE = "操作成功";
|
||||
public static final String DEFAULT_FAIL_MESSAGE = "操作失败!";
|
||||
|
||||
public static <T> Result<T> genSuccessResult() {
|
||||
return new Result()
|
||||
.setCode(ResultCode.SUCCESS)
|
||||
.setMessage(DEFAULT_SUCCESS_MESSAGE);
|
||||
}
|
||||
|
||||
public static Result genUndefinedResult(String message) {
|
||||
return new Result()
|
||||
.setCode(ResultCode.UNDEFINDE)
|
||||
.setMessage(message);
|
||||
}
|
||||
|
||||
public static <T> Result<T> genSuccessResult(String msg, T data) {
|
||||
return new Result<>(ResultCode.SUCCESS, msg, data);
|
||||
}
|
||||
|
||||
public static <T> Result<T> genSuccessResult(T data) {
|
||||
return new Result<>(ResultCode.SUCCESS, DEFAULT_SUCCESS_MESSAGE, data);
|
||||
}
|
||||
|
||||
public static <T> Result<T> genResult(String data) {
|
||||
return new Result<>(ResultCode.SUCCESS, data);
|
||||
}
|
||||
|
||||
public static Result genTransunKonwResult(String message) {
|
||||
return new Result<T>().setCode(ResultCode.TRANSUNKNOW).setMessage(message);
|
||||
}
|
||||
|
||||
public static <T> Result<T> genTransunKonwResult(String message,T data){
|
||||
return new Result<>(ResultCode.TRANSUNKNOW, message, data);
|
||||
}
|
||||
|
||||
public static <T> Result<T> genFailResult(String message) {
|
||||
return new Result<>(ResultCode.FAIL, message, null);
|
||||
}
|
||||
|
||||
public static <T> Result<T> genFailResult(String message,T data) {
|
||||
return new Result<>(ResultCode.FAIL, message, data);
|
||||
}
|
||||
|
||||
|
||||
public static <T> Result<T> genFailResult(T data) {
|
||||
return new Result<>(ResultCode.FAIL, DEFAULT_FAIL_MESSAGE, data);
|
||||
}
|
||||
|
||||
public static JSONObject genFailJsonResult(String message) {
|
||||
JSONObject result = new JSONObject();
|
||||
result.put("code",ResultCode.FAIL.code());
|
||||
result.put("message",message);
|
||||
result.put("data",null);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static JSONObject genSuccessJsonResult(String message,Object data) {
|
||||
JSONObject result = new JSONObject();
|
||||
result.put("code",ResultCode.SUCCESS.code());
|
||||
result.put("message",message);
|
||||
result.put("data",data);
|
||||
return result;
|
||||
}
|
||||
public static JSONObject genSuccessJsonResult(Object data) {
|
||||
JSONObject result = new JSONObject();
|
||||
result.put("code",ResultCode.SUCCESS.code());
|
||||
result.put("message","请求成功");
|
||||
result.put("data",data);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package cn.pluss.platform.base;
|
||||
|
||||
import cn.pluss.platform.api.Result;
|
||||
import cn.pluss.platform.api.ResultGenerator;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.OrderItem;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author djh
|
||||
*/
|
||||
@Slf4j
|
||||
public class BaseModelController<S extends IService<T>, T> {
|
||||
|
||||
@Autowired
|
||||
protected S baseService;
|
||||
|
||||
@GetMapping("/one")
|
||||
@ResponseBody
|
||||
public Result<T> get(T condition) {
|
||||
QueryWrapper<T> queryWrapper = new QueryWrapper<>(condition);
|
||||
T one = baseService.getOne(queryWrapper);
|
||||
return ResultGenerator.genSuccessResult(one);
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
@ResponseBody
|
||||
public Result<List<T>> list(T condition, OrderItem orderItem) {
|
||||
QueryWrapper<T> queryWrapper = new QueryWrapper<>(condition);
|
||||
|
||||
if (orderItem != null && StringUtils.isNotBlank(orderItem.getColumn())) {
|
||||
queryWrapper.orderBy(true, orderItem.isAsc(), orderItem.getColumn());
|
||||
}
|
||||
|
||||
List<T> list;
|
||||
try {
|
||||
queryWrapper = queryWrapper.orderByDesc("createTime");
|
||||
list = baseService.list(queryWrapper);
|
||||
return ResultGenerator.genSuccessResult(list);
|
||||
} catch (Exception e){
|
||||
list = baseService.list(queryWrapper);
|
||||
return ResultGenerator.genSuccessResult(list);
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/page")
|
||||
@ResponseBody
|
||||
public Result<Page<T>> page(Page<T> page, T condition, OrderItem orderItem) {
|
||||
page.getOrders().clear();
|
||||
page.getOrders().add(orderItem);
|
||||
Page<T> pageData = baseService.page(page, new QueryWrapper<>(condition));
|
||||
return ResultGenerator.genSuccessResult(pageData);
|
||||
}
|
||||
|
||||
@DeleteMapping("/del/{id}")
|
||||
@ResponseBody
|
||||
public Result<String> delete(@PathVariable String id) {
|
||||
baseService.removeById(id);
|
||||
return ResultGenerator.genSuccessResult("删除成功", null);
|
||||
}
|
||||
|
||||
@DeleteMapping("/del")
|
||||
@ResponseBody
|
||||
public Result<String> delete(T condition) {
|
||||
baseService.removeById(new QueryWrapper<>(condition));
|
||||
return ResultGenerator.genSuccessResult("删除成功", null);
|
||||
}
|
||||
|
||||
@PostMapping("/save")
|
||||
@ResponseBody
|
||||
public Result<String> save(@RequestBody @Validated T entity) {
|
||||
baseService.saveOrUpdate(entity);
|
||||
return ResultGenerator.genSuccessResult("保存成功", null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/**
|
||||
* 项目启动检查数据库连接
|
||||
* @author DJH
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class ApplicationContextHelper implements ApplicationContextAware {
|
||||
|
||||
private static ApplicationContext context;
|
||||
|
||||
public ApplicationContext getApplicationContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
try {
|
||||
context = applicationContext;
|
||||
// 项目初始化完成后,手动检验数据库
|
||||
DataSource dataSource = (DataSource) context.getBean("dataSource");
|
||||
dataSource.getConnection().close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
log.error("数据库连接失败");
|
||||
// 当检测数据库连接失败时, 停止项目启动
|
||||
System.exit(-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.http.converter.FormHttpMessageConverter;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Configuration
|
||||
public class BeanConfig {
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate() {
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout(600000);
|
||||
// 超时时间设置为5秒
|
||||
factory.setReadTimeout(20000);
|
||||
RestTemplate restTemplate = new RestTemplate(factory);
|
||||
// 设置编码集
|
||||
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
|
||||
// 设置JSON转换器
|
||||
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
|
||||
fastJsonHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM, MediaType.TEXT_PLAIN, MediaType.TEXT_HTML));
|
||||
restTemplate.getMessageConverters().add(fastJsonHttpMessageConverter);
|
||||
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
|
||||
|
||||
// ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
|
||||
// @Override
|
||||
// public boolean hasError(ClientHttpResponse response) throws IOException {
|
||||
// return false;
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void handleError(ClientHttpResponse response) throws IOException {
|
||||
// }
|
||||
// };
|
||||
// restTemplate.setErrorHandler(responseErrorHandler);
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ExecutorService executorService() {
|
||||
return new ThreadPoolExecutor(4,
|
||||
4, 1L
|
||||
, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), Thread::new, new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
}
|
||||
|
||||
@Bean("executorService2")
|
||||
public ExecutorService executorService2() {
|
||||
return new ThreadPoolExecutor(4,
|
||||
4, 1L
|
||||
, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), Thread::new, new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import com.alibaba.druid.support.http.StatViewServlet;
|
||||
import com.alibaba.druid.support.http.WebStatFilter;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 这样的方式不需要在启动类头上添加注解:@ServletComponentScan
|
||||
*/
|
||||
@Configuration
|
||||
public class DruidConfiguration {
|
||||
|
||||
/**
|
||||
* 注册一个StatViewServlet
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public ServletRegistrationBean DruidStatViewServle(){
|
||||
|
||||
//org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
|
||||
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
|
||||
|
||||
//添加初始化参数:initParams
|
||||
|
||||
//白名单:
|
||||
servletRegistrationBean.addInitParameter("allow","127.0.0.1");
|
||||
|
||||
// //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
|
||||
// servletRegistrationBean.addInitParameter("deny","192.168.0.114");
|
||||
|
||||
// //登录查看信息的账号密码.
|
||||
// servletRegistrationBean.addInitParameter("loginUsername","admin");
|
||||
// servletRegistrationBean.addInitParameter("loginPassword","123456");
|
||||
|
||||
//是否能够重置数据.
|
||||
servletRegistrationBean.addInitParameter("resetEnable","false");
|
||||
return servletRegistrationBean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册一个:filterRegistrationBean
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public FilterRegistrationBean druidStatFilter(){
|
||||
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
|
||||
|
||||
//添加过滤规则.
|
||||
filterRegistrationBean.addUrlPatterns("/*");
|
||||
|
||||
//添加不需要忽略的格式信息.
|
||||
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
|
||||
|
||||
return filterRegistrationBean;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@PropertySource("classpath:config/application-common.yml")
|
||||
public class GetuiConfig {
|
||||
|
||||
public String domain = "https://restapi.getui.com/v2/lcpLtzlX1IAVVHaMzO7rI9";
|
||||
|
||||
public static String token = null;
|
||||
|
||||
public static Long expireTime = null;
|
||||
|
||||
/**
|
||||
* 获取鉴权token
|
||||
*/
|
||||
public String auth = "/auth";
|
||||
|
||||
/**
|
||||
* 按照别名单推
|
||||
*/
|
||||
public static String singleAlias = "/push/single/alias";
|
||||
|
||||
public static String singleCid = "/push/single/cid";
|
||||
|
||||
public static String createMsg = "/push/list/message";
|
||||
|
||||
/**
|
||||
* 按照别名批量推
|
||||
*/
|
||||
public static String listAlias = "/push/list/alias";
|
||||
|
||||
/**
|
||||
* 执行cid批量推
|
||||
*/
|
||||
public static String listCid = "/push/list/cid";
|
||||
|
||||
/**
|
||||
* 全量推送
|
||||
*/
|
||||
public static String all = "/push/all";
|
||||
|
||||
public static String tag = "/push/tag";
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
auth = domain + auth;
|
||||
singleAlias = domain + singleAlias;
|
||||
singleCid = domain + singleCid;
|
||||
|
||||
all = domain + all;
|
||||
tag = domain + tag;
|
||||
listAlias = domain + listAlias;
|
||||
listCid = domain + listCid;
|
||||
createMsg = domain + createMsg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import cn.pluss.platform.api.Result;
|
||||
import cn.pluss.platform.api.ResultCode;
|
||||
import cn.pluss.platform.api.ResultGenerator;
|
||||
import cn.pluss.platform.exception.ForbiddenException;
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import cn.pluss.platform.exception.ThirdException;
|
||||
import cn.pluss.platform.exception.UnauthorizedException;
|
||||
import cn.pluss.platform.service.UnknownExceptionService;
|
||||
import cn.pluss.platform.util.ParamsCheckUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 全局的的异常拦截器(拦截所有的控制器)(带有@RequestMapping注解的方法上都会拦截)
|
||||
*
|
||||
* @author Djh
|
||||
*/
|
||||
@ControllerAdvice
|
||||
@Order(-1)
|
||||
@Slf4j
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private static final String EXCEPTION_TIP = "异常信息: {}";
|
||||
|
||||
@Resource
|
||||
private UnknownExceptionService unknownExceptionService;
|
||||
|
||||
/**
|
||||
* 异常信息要传给前端的异常
|
||||
*/
|
||||
@ExceptionHandler(SQLException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Result<Object> business(SQLException e) {
|
||||
StringWriter sw = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(sw, true));
|
||||
log.error(EXCEPTION_TIP, sw);
|
||||
return ResultGenerator.genFailResult("参数包含非法字符");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 异常信息要传给前端的异常
|
||||
*/
|
||||
@ExceptionHandler(UnauthorizedException.class)
|
||||
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
@ResponseBody
|
||||
public Result<Object> business(UnauthorizedException e) {
|
||||
return new Result<>(ResultCode.SERVICE_UNAVAILABLE, e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 异常信息要传给前端的异常
|
||||
*/
|
||||
@ExceptionHandler(MsgException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Result<Object> business(MsgException e) {
|
||||
StringWriter sw = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(sw, true));
|
||||
log.error(EXCEPTION_TIP, sw);
|
||||
return new Result<>(e.getCode(), e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 异常信息要传给前端的异常
|
||||
*/
|
||||
@ExceptionHandler(ThirdException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Result<Object> business(ThirdException e) {
|
||||
StringWriter sw = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(sw, true));
|
||||
log.error(EXCEPTION_TIP, sw);
|
||||
return new Result<>(ResultCode.FAIL, e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 异常信息要传给前端的异常
|
||||
*/
|
||||
@ExceptionHandler(ForbiddenException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Result<Object> business(ForbiddenException e) {
|
||||
StringWriter sw = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(sw, true));
|
||||
log.error(EXCEPTION_TIP, sw);
|
||||
return new Result<>(ResultCode.FORBIDDEN, e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 异常信息要传给前端的异常
|
||||
*/
|
||||
@ExceptionHandler(DuplicateKeyException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Result<Object> business(DuplicateKeyException e) {
|
||||
StringWriter sw = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(sw, true));
|
||||
log.error(EXCEPTION_TIP, sw);
|
||||
return ResultGenerator.genFailResult("插入失败", null);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 参数校验错误异常
|
||||
*/
|
||||
@ExceptionHandler(BindException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Result<Object> errorParams(BindException e) {
|
||||
BindingResult bindingResult = e.getBindingResult();
|
||||
log.error("参数校验异常:", e);
|
||||
return new Result<>(ResultCode.PARAM_ERROR, ParamsCheckUtil.getErrorMsg(bindingResult));
|
||||
}
|
||||
|
||||
/**
|
||||
* 参数校验错误异常
|
||||
*/
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Result<Object> errorParams2(MethodArgumentNotValidException e) {
|
||||
BindingResult bindingResult = e.getBindingResult();
|
||||
log.error("参数校验异常:", e);
|
||||
return new Result<>(ResultCode.PARAM_ERROR, ParamsCheckUtil.getErrorMsg(bindingResult));
|
||||
}
|
||||
|
||||
@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Result<Object> unusedException() {
|
||||
return ResultGenerator.genFailResult("不支持的请求方式", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截未知的运行时异常
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Result<Object> commonError(HttpServletRequest request, Exception e) {
|
||||
log.error("通用异常 URI: {}", request.getRequestURI());
|
||||
log.error("通用异常 headers: {}", JSON.toJSONString(getHeaderInfo(request)));
|
||||
try {
|
||||
InputStream is = request.getInputStream();
|
||||
StringBuilder responseStrBuilder = new StringBuilder();
|
||||
BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
|
||||
String inputStr;
|
||||
while ((inputStr = streamReader.readLine()) != null) {
|
||||
responseStrBuilder.append(inputStr);
|
||||
}
|
||||
log.error("通用异常 body: {}", responseStrBuilder);
|
||||
} catch (Exception ignored) {
|
||||
// 不处理
|
||||
}
|
||||
Map<String, Object> parameterInfo = getParameterInfo(request);
|
||||
log.error("通用异常 params: {}", JSON.toJSONString(parameterInfo));
|
||||
// 将异常信息保存到数据库中
|
||||
try {
|
||||
e.printStackTrace();
|
||||
unknownExceptionService.save(request, e);
|
||||
} catch (Exception ignored) {
|
||||
ignored.printStackTrace();
|
||||
}
|
||||
return new Result<>(ResultCode.PARAM_ERROR, "系统繁忙,请稍后再试");
|
||||
}
|
||||
|
||||
/**
|
||||
* 拦截 @RequestParam 必传参数不存在的异常
|
||||
* @param e 异常信息
|
||||
* @return r
|
||||
*/
|
||||
@ExceptionHandler(MissingServletRequestParameterException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Result<Object> missParam(MissingServletRequestParameterException e) {
|
||||
StringWriter sw = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(sw, true));
|
||||
log.error(EXCEPTION_TIP, sw);
|
||||
return new Result<>(ResultCode.PARAM_ERROR, "参数错误,或缺少必要参数");
|
||||
}
|
||||
|
||||
private Map<String, Object> getParameterInfo(HttpServletRequest request) {
|
||||
Map<String, Object> parameter = new HashMap<>(8);
|
||||
Map<String, String[]> parameterMap = request.getParameterMap();
|
||||
|
||||
for (Map.Entry<String, String[]> entry: parameterMap.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
String[] parameterValues = entry.getValue();
|
||||
if (parameterValues.length == 1) {
|
||||
parameter.put(key, parameterValues[0]);
|
||||
} else {
|
||||
parameter.put(key, Arrays.toString(parameterValues));
|
||||
}
|
||||
}
|
||||
return parameter;
|
||||
}
|
||||
|
||||
private Map<String, Object> getHeaderInfo(HttpServletRequest request) {
|
||||
Map<String, Object> parameter = new HashMap<>(8);
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String key = headerNames.nextElement();
|
||||
parameter.put(key, request.getHeader(key));
|
||||
}
|
||||
|
||||
return parameter;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import com.google.code.kaptcha.impl.DefaultKaptcha;
|
||||
import com.google.code.kaptcha.util.Config;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
*
|
||||
*图形验证码配置类
|
||||
*@author: bzg
|
||||
*@time: 2021/12/20 10:18
|
||||
*/
|
||||
@Configuration
|
||||
public class KaptchaConfig {
|
||||
|
||||
@Bean
|
||||
public DefaultKaptcha getDefaultKaptcha() {
|
||||
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
|
||||
Properties properties = new Properties();
|
||||
// 图片边框
|
||||
properties.setProperty("kaptcha.border", "no");
|
||||
// 边框颜色
|
||||
properties.setProperty("kaptcha.border.color", "black");
|
||||
//边框厚度
|
||||
properties.setProperty("kaptcha.border.thickness", "1");
|
||||
// 图片宽
|
||||
properties.setProperty("kaptcha.image.width", "150");
|
||||
// 图片高
|
||||
properties.setProperty("kaptcha.image.height", "50");
|
||||
//图片实现类
|
||||
properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");
|
||||
//文本实现类
|
||||
properties.setProperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.DefaultTextCreator");
|
||||
//文本集合,验证码值从此集合中获取
|
||||
properties.setProperty("kaptcha.textproducer.char.string", "ABCDEFGOPQRSXYZ01234567890");
|
||||
//验证码长度
|
||||
properties.setProperty("kaptcha.textproducer.char.length", "4");
|
||||
//字体
|
||||
properties.setProperty("kaptcha.textproducer.font.names", "宋体");
|
||||
|
||||
properties.setProperty("kaptcha.textproducer.font.size", "35");
|
||||
//字体颜色
|
||||
properties.setProperty("kaptcha.textproducer.font.color", "black");
|
||||
//文字间隔
|
||||
properties.setProperty("kaptcha.textproducer.char.space", "5");
|
||||
//干扰实现类
|
||||
properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");
|
||||
//干扰颜色
|
||||
properties.setProperty("kaptcha.noise.color", "blue");
|
||||
//干扰图片样式
|
||||
properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
|
||||
//背景实现类
|
||||
properties.setProperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.DefaultBackground");
|
||||
//背景颜色渐变,结束颜色
|
||||
properties.setProperty("kaptcha.background.clear.to", "white");
|
||||
//文字渲染器
|
||||
properties.setProperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.DefaultWordRenderer");
|
||||
Config config = new Config(properties);
|
||||
defaultKaptcha.setConfig(config);
|
||||
return defaultKaptcha;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author admin
|
||||
* @desc 阿里云MQTT配置参数类
|
||||
*
|
||||
*/
|
||||
@Data
|
||||
@Component("mqttConfig")
|
||||
@PropertySource("classpath:config/application-common.yml")
|
||||
public class MqttConfig {
|
||||
|
||||
/**
|
||||
* 节点
|
||||
*/
|
||||
@Value("${mqtt.region-id}")
|
||||
private String regionId;
|
||||
|
||||
/**
|
||||
* key
|
||||
*/
|
||||
@Value("${mqtt.keyid}")
|
||||
private String keyId;
|
||||
|
||||
/**
|
||||
* secret
|
||||
*/
|
||||
@Value("${mqtt.keysecret}")
|
||||
private String keySecret;
|
||||
|
||||
/**
|
||||
* 实例ID
|
||||
*/
|
||||
@Value("${mqtt.instance-id}")
|
||||
private String instanceId;
|
||||
|
||||
/**
|
||||
* topic
|
||||
*/
|
||||
@Value("${mqtt.topic}")
|
||||
private String topic;
|
||||
|
||||
/**
|
||||
* groupId
|
||||
*/
|
||||
@Value("${mqtt.groupid}")
|
||||
private String groupId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import cn.pluss.platform.util.StringUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.aliyuncs.DefaultAcsClient;
|
||||
import com.aliyuncs.IAcsClient;
|
||||
import com.aliyuncs.exceptions.ClientException;
|
||||
import com.aliyuncs.onsmqtt.model.v20200420.SendMessageRequest;
|
||||
import com.aliyuncs.onsmqtt.model.v20200420.SendMessageResponse;
|
||||
import com.aliyuncs.profile.DefaultProfile;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.DependsOn;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
@DependsOn("mqttConfig")
|
||||
public class MqttSendMessage {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
@Autowired
|
||||
private MqttConfig mqttConfig;
|
||||
|
||||
private DefaultProfile profile;
|
||||
|
||||
private IAcsClient client;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
if(profile == null){
|
||||
profile = DefaultProfile.getProfile(mqttConfig.getRegionId(), mqttConfig.getKeyId(), mqttConfig.getKeySecret());
|
||||
}
|
||||
if(client == null){
|
||||
client = new DefaultAcsClient(profile);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String,String> sendMqttMessage(String deviceNo, JSONObject payload){
|
||||
logger.info("==============>推送Mqtt消息开始,推送设备编号:{},推送消息内容:{}<===============",deviceNo,payload);
|
||||
if(StringUtil.isEmpty(deviceNo)){
|
||||
logger.info("==============>推送Mqtt消息失败,推送设备编号为空!<=================");
|
||||
return null;
|
||||
}
|
||||
if(StringUtil.isEmpty(payload)){
|
||||
logger.info("==============>推送Mqtt消息失败,推送消息内容为空!<=================");
|
||||
return null;
|
||||
}
|
||||
SendMessageRequest request = new SendMessageRequest();
|
||||
request.setRegionId(mqttConfig.getRegionId());
|
||||
request.setInstanceId(mqttConfig.getInstanceId());
|
||||
request.setPayload(payload.toJSONString());
|
||||
String sendTopic = mqttConfig.getTopic() + "/order/" + mqttConfig.getGroupId() + "@@@" + deviceNo;
|
||||
logger.info("==============>推送Mqtt消息topic参数:{}<=================",sendTopic);
|
||||
request.setMqttTopic(sendTopic);
|
||||
try {
|
||||
SendMessageResponse response = client.getAcsResponse(request);
|
||||
if(response != null){
|
||||
return JSONObject.parseObject(JSON.toJSONString(response),Map.class);
|
||||
}
|
||||
} catch (ClientException e) {
|
||||
logger.info("==============>推送Mqtt消息失败,失败原因:{}<=================",e.getErrMsg());
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClient;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import lombok.Data;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@PropertySource("classpath:config/application-common.yml")
|
||||
public class OssConfig {
|
||||
|
||||
@Value("${aliyun.oss.endpoint}")
|
||||
private String endpoint; //连接区域地址
|
||||
@Value("${aliyun.keyid}")
|
||||
private String keyid; //连接keyId
|
||||
@Value("${aliyun.keysecret}")
|
||||
private String keysecret; //连接秘钥
|
||||
@Value("${aliyun.oss.bucketname}")
|
||||
private String bucketname; //需要存储的bucketName
|
||||
@Value("${aliyun.region-id}")
|
||||
private String regionId;
|
||||
@Value("${aliyun.oss.callback}")
|
||||
private String callback;
|
||||
|
||||
@Bean
|
||||
@Scope("prototype")
|
||||
public OSS ossClient(){
|
||||
return new OSSClientBuilder().build(endpoint, keyid, keysecret);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import cn.pluss.platform.util.ParametersUtil;
|
||||
import cn.pluss.platform.util.RyxConfig;
|
||||
import cn.pluss.platform.util.SxfConfg;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
/**
|
||||
* @author Djh
|
||||
* 配置参数接收实体类
|
||||
*/
|
||||
@Component
|
||||
public class ParameterConfig {
|
||||
|
||||
@Value("${sxf.domain}")
|
||||
public String sxfDomain;
|
||||
|
||||
@Value("${sxf.orgId}")
|
||||
public String orgId;
|
||||
|
||||
@Value("${sxf.publicKey}")
|
||||
public String publicKey;
|
||||
|
||||
@Value("${ryx.auditDomain}")
|
||||
public String ryxAuditDomain;
|
||||
|
||||
@Value("${ryx.payDomain}")
|
||||
public String ryxPayDomain;
|
||||
|
||||
@Value("${ryx.accessId}")
|
||||
public String ryxAccessId;
|
||||
|
||||
@Value("${ryx.subAccessId}")
|
||||
public String ryxSubAccessId;
|
||||
|
||||
@Value("${ryx.subAccessPubKey}")
|
||||
public String ryxSubAccessPubKey;
|
||||
|
||||
@Value("${ryx.cooperatorPriKey}")
|
||||
public String ryxCooperatorPriKey;
|
||||
|
||||
@Value("${ryx.cooperatorPubKey}")
|
||||
public String ryxCooperatorPubKey;
|
||||
|
||||
@Value("${ryx.accessPubKey}")
|
||||
public String ryxAccessPubKey;
|
||||
|
||||
@Value("${ryx.smzfPubKey}")
|
||||
public String ryxSmzfPubKey;
|
||||
|
||||
@Value("${ryx.payCooperator}")
|
||||
public String ryxPayCooperator;
|
||||
|
||||
/**
|
||||
* 上传图片保存路径
|
||||
*/
|
||||
@Value("${parameter.upload_save_path}")
|
||||
public String upload_save_path;
|
||||
/**
|
||||
* 上传图片访问路径
|
||||
*/
|
||||
@Value("${parameter.upload_visit_path}")
|
||||
public String upload_visit_path;
|
||||
/**
|
||||
* 获取支付宝授权token
|
||||
*/
|
||||
@Value("${parameter.ALI_APP_AUTH_TOKEN}")
|
||||
public String ALI_APP_AUTH_TOKEN;
|
||||
/**
|
||||
* 支付宝费率
|
||||
*/
|
||||
@Value("${parameter.ALI_RATE}")
|
||||
public Double ALI_RATE;
|
||||
/**
|
||||
* 微信费率
|
||||
*/
|
||||
@Value("${parameter.WECHAT_RATE}")
|
||||
public Double WECHAT_RATE;
|
||||
/**
|
||||
* 微信支付appid
|
||||
*/
|
||||
@Value("${parameter.APPID}")
|
||||
public String APPID;
|
||||
/**
|
||||
* 付款小程序APPID
|
||||
*/
|
||||
@Value("${parameter.APPLETS_APPID}")
|
||||
public String APPLETS_APPID;
|
||||
/**
|
||||
* AppSecret
|
||||
*/
|
||||
@Value("${parameter.APPSECRET}")
|
||||
public String APPSECRET;
|
||||
/**
|
||||
* 商户号
|
||||
*/
|
||||
@Value("${parameter.PID}")
|
||||
public String PID;
|
||||
/**
|
||||
* 秘钥
|
||||
*/
|
||||
@Value("${parameter.KEY}")
|
||||
public String KEY;
|
||||
/**
|
||||
* 微信支付回调地址
|
||||
*/
|
||||
@Value("${parameter.wechatCallback}")
|
||||
public String wechatCallback;
|
||||
/**
|
||||
* 支付宝Appid
|
||||
*/
|
||||
@Value("${parameter.ALI_APP_ID}")
|
||||
public String ALI_APP_ID;
|
||||
/**
|
||||
* 支付宝私钥
|
||||
*/
|
||||
@Value("${parameter.PRI}")
|
||||
public String PRI;
|
||||
/**
|
||||
* 支付宝公钥
|
||||
*/
|
||||
@Value("${parameter.PUB}")
|
||||
public String PUB;
|
||||
/**
|
||||
* 支付宝授权回调地址
|
||||
*/
|
||||
@Value("${parameter.ALI_RETURN_URL}")
|
||||
public String ALI_RETURN_URL;
|
||||
/**
|
||||
* 服务器域名
|
||||
*/
|
||||
@Value("${parameter.domain}")
|
||||
public String domain;
|
||||
/**
|
||||
* 乐刷代理商编号
|
||||
*/
|
||||
@Value("${parameter.agentId}")
|
||||
public String agentId;
|
||||
/**
|
||||
* 乐刷进件和交易请求密钥(key
|
||||
*/
|
||||
@Value("${parameter.leshuapaykey}")
|
||||
public String leshuapaykey;
|
||||
/**
|
||||
* 交易异步通知回调密钥
|
||||
*/
|
||||
@Value("${parameter.leshuaCallBackKey}")
|
||||
public String leshuaCallBackKey;
|
||||
/**
|
||||
* 粉丝分润比例
|
||||
*/
|
||||
@Value("${parameter.fans_profit}")
|
||||
public Double fans_profit;
|
||||
/**
|
||||
* 乐刷费率
|
||||
*/
|
||||
@Value("${parameter.leshuarate}")
|
||||
public Double leshuarate;
|
||||
/**
|
||||
* 下载apk地址
|
||||
*/
|
||||
@Value("${parameter.apk_dowload_url}")
|
||||
public String apk_dowload_url;
|
||||
/**
|
||||
* apk版本号
|
||||
*/
|
||||
@Value("${parameter.versions}")
|
||||
public String versions;
|
||||
/**
|
||||
* 官网获取的 API Key OCR
|
||||
*/
|
||||
@Value("${parameter.baiduAK}")
|
||||
public String baiduAK;
|
||||
/**
|
||||
* 官网获取的 Secret Key OCR
|
||||
*/
|
||||
@Value("${parameter.baiduSK}")
|
||||
public String baiduSK;
|
||||
|
||||
/**
|
||||
* 百度人脸识别
|
||||
* 官网获取的 API Key OCR
|
||||
*/
|
||||
@Value("${parameter.baiduAK2}")
|
||||
public String baiduAK2;
|
||||
|
||||
/**
|
||||
* 百度人脸识别
|
||||
* 官网获取的 Secret Key OCR
|
||||
*/
|
||||
@Value("${parameter.baiduSK2}")
|
||||
public String baiduSK2;
|
||||
|
||||
/**
|
||||
* 身份证OCR接口地址
|
||||
*/
|
||||
@Value("${parameter.idCardOCRUrl}")
|
||||
public String idCardOCRUrl;
|
||||
/**
|
||||
* 银行卡OCR接口地址
|
||||
*/
|
||||
@Value("${parameter.bankCardOCRUrl}")
|
||||
public String bankCardOCRUrl;
|
||||
/**
|
||||
* 营业执照OCR接口地址
|
||||
*/
|
||||
@Value("${parameter.blCardOCRUrl}")
|
||||
public String blCardOCRUrl;
|
||||
/**
|
||||
* 阿里自用型应用appid
|
||||
*/
|
||||
@Value("${parameter.ZY_ALI_APP_ID}")
|
||||
public String ZY_ALI_APP_ID;
|
||||
/**
|
||||
* 阿里自用型应用私钥
|
||||
*/
|
||||
@Value("${parameter.ZY_PRI}")
|
||||
public String ZY_PRI;
|
||||
/**
|
||||
* 阿里自用型应用公钥
|
||||
*/
|
||||
@Value("${parameter.ZY_PUB}")
|
||||
public String ZY_PUB;
|
||||
/**
|
||||
* 刘思义本人的乐刷的商户编号 用来收推广人升级的钱
|
||||
*/
|
||||
@Value("${parameter.LESHUALIU}")
|
||||
public String LESHUALIU;
|
||||
|
||||
/**
|
||||
* 收银呗微信普通商户APPID
|
||||
*/
|
||||
@Value("${parameter.MERCHANT_APPID}")
|
||||
public String MERCHANT_APPID;
|
||||
|
||||
/**
|
||||
* 收银呗微信普通商户Appsecret
|
||||
*/
|
||||
@Value("${parameter.MERCHANT_APPSECRET}")
|
||||
public String MERCHANT_APPSECRET;
|
||||
|
||||
/**
|
||||
* 收银呗微信普通商户号
|
||||
*/
|
||||
@Value("${parameter.MERCHANT_PID}")
|
||||
public String MERCHANT_PID;
|
||||
|
||||
/**
|
||||
* 收银呗微信普通商户key
|
||||
*/
|
||||
@Value("${parameter.MERCHANT_KEY}")
|
||||
public String MERCHANT_KEY;
|
||||
|
||||
@Value("${parameter.LESHUA_API}")
|
||||
public String LESHUA_API;
|
||||
|
||||
@Value("${parameter.SJ_APPID}")
|
||||
public String SJ_APPID;
|
||||
|
||||
@Value("${parameter.SJ_APPSECRET}")
|
||||
public String SJ_APPSECRET;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
ParametersUtil.upload_save_path = upload_save_path;
|
||||
ParametersUtil.upload_visit_path = upload_visit_path;
|
||||
ParametersUtil.ALI_APP_AUTH_TOKEN = ALI_APP_AUTH_TOKEN;
|
||||
ParametersUtil.ALI_RATE = ALI_RATE;
|
||||
ParametersUtil.WECHAT_RATE = WECHAT_RATE;
|
||||
ParametersUtil.APPID = APPID;
|
||||
ParametersUtil.APPLETS_APPID = APPLETS_APPID;
|
||||
ParametersUtil.APPSECRET = APPSECRET;
|
||||
ParametersUtil.PID = PID;
|
||||
ParametersUtil.KEY = KEY;
|
||||
ParametersUtil.wechatCallback = wechatCallback;
|
||||
ParametersUtil.ALI_APP_ID = ALI_APP_ID;
|
||||
ParametersUtil.PRI = PRI;
|
||||
ParametersUtil.PUB = PUB;
|
||||
ParametersUtil.ALI_RETURN_URL = ALI_RETURN_URL;
|
||||
ParametersUtil.domain = domain;
|
||||
ParametersUtil.agentId = agentId;
|
||||
ParametersUtil.leshuapaykey = leshuapaykey;
|
||||
ParametersUtil.leshuaCallBackKey = leshuaCallBackKey;
|
||||
ParametersUtil.fans_profit = fans_profit;
|
||||
ParametersUtil.leshuarate = leshuarate;
|
||||
ParametersUtil.apk_dowload_url = apk_dowload_url;
|
||||
ParametersUtil.versions = versions;
|
||||
ParametersUtil.baiduAK = baiduAK;
|
||||
ParametersUtil.baiduSK = baiduSK;
|
||||
ParametersUtil.baiduAK2 = baiduAK2;
|
||||
ParametersUtil.baiduSK2 = baiduSK2;
|
||||
ParametersUtil.idCardOCRUrl = idCardOCRUrl;
|
||||
ParametersUtil.bankCardOCRUrl = bankCardOCRUrl;
|
||||
ParametersUtil.blCardOCRUrl = blCardOCRUrl;
|
||||
ParametersUtil.ZY_ALI_APP_ID = ZY_ALI_APP_ID;
|
||||
ParametersUtil.ZY_PRI = ZY_PRI;
|
||||
ParametersUtil.ZY_PUB = ZY_PUB;
|
||||
ParametersUtil.LESHUALIU = LESHUALIU;
|
||||
ParametersUtil.MERCHANT_APPID=MERCHANT_APPID;
|
||||
ParametersUtil.MERCHANT_APPSECRET=MERCHANT_APPSECRET;
|
||||
ParametersUtil.MERCHANT_PID=MERCHANT_PID;
|
||||
ParametersUtil.MERCHANT_KEY=MERCHANT_KEY;
|
||||
ParametersUtil.LESHUA_API=LESHUA_API;
|
||||
ParametersUtil.SJ_APPID = SJ_APPID;
|
||||
ParametersUtil.SJ_APPSECRET = SJ_APPSECRET;
|
||||
|
||||
SxfConfg.init(sxfDomain, publicKey, orgId);
|
||||
|
||||
RyxConfig.init(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@PropertySource("classpath:config/application-common.yml")
|
||||
public class StsConfig {
|
||||
@Value("${aliyun.sts.endpoint}")
|
||||
private String endpoint; //连接区域地址
|
||||
@Value("${aliyun.keyid}")
|
||||
private String keyid; //连接keyId
|
||||
@Value("${aliyun.keysecret}")
|
||||
private String keysecret; //连接秘钥
|
||||
@Value("${aliyun.region-id}")
|
||||
private String regionId;
|
||||
@Value("${aliyun.sts.role-arn}")
|
||||
private String roleArn;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cn.pluss.platform.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 java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* @author djh
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
public class TaskExecutorConfig implements AsyncConfigurer {
|
||||
|
||||
@Override
|
||||
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
|
||||
return new SimpleAsyncUncaughtExceptionHandler();
|
||||
}
|
||||
|
||||
static class SimpleAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
|
||||
|
||||
@Override
|
||||
public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
|
||||
log.error("异步回调失败了, 错误信息: " + throwable.getMessage());
|
||||
throwable.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package cn.pluss.platform.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.multipart.MultipartResolver;
|
||||
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
|
||||
|
||||
@Configuration
|
||||
public class UploadConfig {
|
||||
@Bean(name = "multipartResolver")
|
||||
public MultipartResolver multipartResolver() {
|
||||
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
|
||||
resolver.setDefaultEncoding("UTF-8");
|
||||
//resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常
|
||||
resolver.setResolveLazily(true);
|
||||
resolver.setMaxInMemorySize(40960);
|
||||
//上传文件大小 50M 5*10*1024*1024
|
||||
resolver.setMaxUploadSize(5* 10 * 1024 * 1024);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package cn.pluss.platform.config.mybatis;
|
||||
|
||||
public class SqlConditionExtra {
|
||||
|
||||
public static final String GT = "%s > #{%s}";
|
||||
|
||||
public static final String GE = "%s >= #{%s}";
|
||||
|
||||
public static final String LT = "%s < #{%s}";
|
||||
|
||||
public static final String LE = "%s <= #{%s}";
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package cn.pluss.platform.constants;
|
||||
|
||||
/**
|
||||
* 这里存一些通用的异常术语
|
||||
* @author SSS
|
||||
*/
|
||||
public class CommonError {
|
||||
|
||||
private CommonError(){}
|
||||
|
||||
public static final String NO_AUTHORIZATION = "拒绝访问";
|
||||
|
||||
public static final String NO_LOGIN = "请先登录账号";
|
||||
|
||||
public static final String NO_EXIST_ACCOUNT = "账号不存在";
|
||||
|
||||
public static final String PHONE_HAS_REGISTER = "手机号已被注册!";
|
||||
|
||||
public static final String NO_LEGAL_ID_CARD_INFO = "请填写法人身份证信息";
|
||||
|
||||
public static final String NO_ACC_ID_CARD_INFO = "请填写结算人身份证信息";
|
||||
|
||||
public static final String NO_USER_ID = "缺少userId";
|
||||
|
||||
public static final String NO_BANK_PHONE = "缺少银行卡预留手机号";
|
||||
|
||||
public static final String NO_ACCOUNT_ID_CARD = "缺少结算身份证信息";
|
||||
|
||||
public static final String NO_PART_ACCOUNT_ID_CARD = "结算身份证信息不全";
|
||||
|
||||
public static final String NO_PART_ACCOUNT_ID_CARD_HEAD = "缺少结算身份证信息人头面";
|
||||
|
||||
public static final String NO_PART_ACCOUNT_ID_CARD_EMBLEM = "缺少结算身份证信息国徽面";
|
||||
|
||||
public static final String NO_ACCOUNT_BANK_CARD = "缺少结算银行卡信息";
|
||||
|
||||
public static final String NO_ACCOUNT_BANK_CARD_LICENSE = "对公结算卡缺少开户许可证";
|
||||
|
||||
public static final String NO_ACCOUNT_BANK_CARD_IMG = "对私结算卡缺少银行卡卡号面图";
|
||||
|
||||
public static final String NO_PART_ACCOUNT_BANK_CARD = "结算银行卡信息不全";
|
||||
|
||||
public static final String NO_ILLEGAL_ACCOUNT_CERTIFICATE_URL = "非法人结算缺少非法人结算授权函";
|
||||
|
||||
public static final String CHANNEL_TYPE_ILLEGAL = "通道类型错误";
|
||||
|
||||
public static final String BANK_NAME_EMPTY = "缺少银行名称";
|
||||
|
||||
public static final String BANK_BRANCH_PROVINCE_EMPTY = "缺少开户支行所在省份";
|
||||
|
||||
public static final String BANK_BRANCH_CITY_EMPTY = "缺少开户支行所在市";
|
||||
|
||||
public static final String BANK_BRANCH_AREA_EMPTY = "缺少开户支行所在县/区";
|
||||
|
||||
public static final String BANK_BRANCH_NAME_EMPTY = "缺少开户支行名称";
|
||||
|
||||
public static final String BANK_BRANCH_CNAPS_EMPTY = "缺少开户支行联行号";
|
||||
|
||||
public static final String ACCOUNT_EMPTY = "缺少结算信息";
|
||||
|
||||
public static final String ERROR_STATUS = "当前状态不允许操作";
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package cn.pluss.platform.constants;
|
||||
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class Constant {
|
||||
|
||||
|
||||
public static String INDUSTRY_TYPE = "industry";
|
||||
public static String VIDEO_TYPE = "video";
|
||||
public static String REQUST_RETIRN_JUMP = "";
|
||||
public static String session_user = "session_user";
|
||||
|
||||
public static String MESSAGE_TYPE_BACK = "back";//回执
|
||||
public static String MESSAGE_TYPE_MESSAGE = "message";//消息
|
||||
public static String MESSAGE_TYPE_PING = "ping";//心跳
|
||||
public static String MESSAGE_TYPE_BIND = "bind";//绑定
|
||||
public static String MESSAGE_TYPE_RECEIVE = "receive";//暂存消息 收取
|
||||
public static String QR_LIMIT_SCENE = "QR_LIMIT_SCENE";//微信创建二维码 永久 int
|
||||
|
||||
public static String RESULT_CODE_SUCCESS = "SUCCESS";//返回结果成功
|
||||
public static String RESULT_CODE_FAIL = "FAIL";//返回结果失败
|
||||
public static String RESULT_CODE_NONE = "NONE";//收到回执 什么不用做
|
||||
public static String RESULT_CODE_OK = "OK";//服务端已接受
|
||||
|
||||
public static String FILE_SAVE_PATH = "/home/trade/talkfile/save";//服务端已接受
|
||||
|
||||
|
||||
public static long MESSAGE_PING_CLOCK = 30;//心跳时钟 单位是秒
|
||||
|
||||
|
||||
//支付状态
|
||||
public static String PAY_RESULT_CODE_SUCCESS = "1";
|
||||
public static String PAY_RESULT_CODE_FAIL = "2";
|
||||
public static String PAY_RESULT_CODE_NONE = "0";
|
||||
|
||||
|
||||
//支付方式
|
||||
public static final String PAY_TYPE_WECHAT = "wechatPay";
|
||||
public static final String PAY_TYPE_NAME_WECHAT = "微信";
|
||||
public static final String PAY_TYPE_ALIPAY = "aliPay";
|
||||
public static final String PAY_TYPE_NAME_ALIPAY = "支付宝";
|
||||
|
||||
public static final String PAY_TYPE_YSFPAY = "bank";
|
||||
|
||||
public static final String PAY_TYPE_NAME_YSFPAY = "云闪付";
|
||||
|
||||
//订单号前缀
|
||||
public final static String PREFIX_ORDER = "11";
|
||||
//日期格式
|
||||
public final static String WECHATDATEFORMAT = "yyyyMMddHHmmss";
|
||||
|
||||
public final static String WEIXIN_PAY_UNIFIED_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
|
||||
|
||||
public final static String TENCENT_GET_ADDRESS_URL = "https://apis.map.qq.com/ws/geocoder/v1";
|
||||
|
||||
public static String sync_type_dml = "dml";//同步类型
|
||||
public static String sync_type_ddl = "ddl";//同步类型
|
||||
public static String sync_definition_action_insert = "insert";
|
||||
public static String sync_definition_action_update = "update";
|
||||
public static String sync_definition_action_delete = "delete";
|
||||
public static String sync_definition_action_alter = "alter";
|
||||
public static String sync_definition_action_create = "create";
|
||||
public static String sync_definition_action_save = "save";
|
||||
|
||||
|
||||
public static String sync_definition_entity_MerchantProductCategory = "MerchantProductCategory";
|
||||
public static String sync_definition_entity_MerchantProductCombo = "MerchantProductCombo";
|
||||
public static String sync_definition_entity_MerchantProduct = "MerchantProduct";
|
||||
public static String sync_definition_entity_MerchantRole = "MerchantRole";
|
||||
public static String sync_definition_entity_MerchantRoleMenu = "MerchantRoleMenu";
|
||||
public static String sync_definition_entity_MerchantRoleUser = "MerchantRoleUser";
|
||||
public static String sync_definition_entity_MerchantBaseInfo = "MerchantBaseInfo";
|
||||
public static String sync_definition_entity_MerchantArea = "MerchantArea";
|
||||
public static String sync_definition_entity_MerchantAreaClass = "MerchantAreaClass";
|
||||
|
||||
/**
|
||||
* 百度短信模板
|
||||
*/
|
||||
//注册成功
|
||||
public static String baidu_template_regist_success = "smsTpl:6c248ad7-921b-417a-869b-e43a78795700";
|
||||
//带评阅
|
||||
public static String baidu_template_waitfor_read = "smsTpl:e8e3651a-d7b7-4870-a70a-eeefd18f90eb";
|
||||
//参赛成
|
||||
public static String baidu_template_join_batter = "smsTpl:c7bcd897-6bee-4822-8823-be0e506ff334";
|
||||
//中榜
|
||||
public static String baidu_template_on_list = "smsTpl:466d88ca-317e-4af1-875d-d1ebe2258304";
|
||||
//评阅成功
|
||||
public static String baidu_template_read_success = "smsTpl:591e7f62-8a13-49b8-88b9-7dc9f9f6cf8f";
|
||||
/**
|
||||
* 微信公众号模板
|
||||
*/
|
||||
/**
|
||||
* 注册成功
|
||||
*/
|
||||
public static String wechat_template_regist_success = " UNeuf5QpriPfLVCJvXLhneBq3NVNQi2KKXIhCIjkz8Y";
|
||||
/**
|
||||
* 待评阅
|
||||
*/
|
||||
public static String wechat_template_waitfor_read = "ncbyBjSDhvF3NQ-25OStNS7lohq_ZI_QLBjpS2Bj7NA";
|
||||
/**
|
||||
* 活动报名成功
|
||||
*/
|
||||
public static String wechat_template_join_batter = "OKX7nmg0YPAicELVQn3DXMtHWowVS1jc0ZdAjmuYVqs";
|
||||
/**
|
||||
* 中榜
|
||||
*/
|
||||
public static String wechat_template_on_list = "9TWvGm19CuV1Wk4fuGu-SUfkuKsR9Yi77OXm234w8Tw";
|
||||
/**
|
||||
* 评阅成功
|
||||
*/
|
||||
public static String wechat_template_read_success = "D6eGbZ8GO36KCXCAe6CwNjG7RRHZxcDDxkOCbeYcIRk";
|
||||
/**
|
||||
* 登录成功提醒
|
||||
*/
|
||||
public static String wechat_template_login_success = "iZugTWBgboOdqttfmHvgv_NR_QTFjp88GREmu5JUC7c";
|
||||
|
||||
/**
|
||||
* 充值成功
|
||||
*/
|
||||
public static String wechat_template_pay_success = "3TzSZHbyRMxG3e5x5KxTCMD_BTP8hJHTGllOnSaCpf0";
|
||||
/**
|
||||
* 消费成功
|
||||
*/
|
||||
public static String wechat_consume_success = "JFIaSWscb_KKCHN_3cCO4ctlDrbsRs0MywjScpYk0bA";
|
||||
|
||||
/**
|
||||
* 图形验证码key
|
||||
* @date: 2021/12/20 10:24
|
||||
*/
|
||||
public static final String LOGIN_VALIDATE_CODE = "login_validate_code";
|
||||
|
||||
/**
|
||||
* 用户最高等级等级LV10
|
||||
* @date: 2022/1/22 15:16
|
||||
*/
|
||||
public static final String USER_MAX_LEVEL_CODE = "LV10";
|
||||
|
||||
/**
|
||||
* 最小结算底价
|
||||
* @date: 2022/3/9 18:08
|
||||
*/
|
||||
public static final BigDecimal MIX_SETTLE_RATE = BigDecimal.valueOf(21);
|
||||
|
||||
/**
|
||||
* 缴费通
|
||||
* @date: 2022/3/9 18:08
|
||||
*/
|
||||
public static final BigDecimal JFT_MIX_SETTLE_RATE = BigDecimal.valueOf(28);
|
||||
|
||||
/**
|
||||
* 默认收款商户号
|
||||
*/
|
||||
public static final String DEFUALT_CASHIER_MERCHANT = "M80020220111357490";
|
||||
|
||||
/**
|
||||
* 默认收款商户属性key
|
||||
*/
|
||||
public static final String SYSTEM_MERCHANT_KEY = "cashier_merchant";
|
||||
|
||||
/**
|
||||
* 默认通道
|
||||
*/
|
||||
public static final Integer DEFAULT_CHANNEL = 4;
|
||||
|
||||
/**
|
||||
* 支付宝H5支付前缀
|
||||
*/
|
||||
public static final String ALIPAY_H5_PAY_URL_PRIFIX = "alipays://platformapi/startapp?appId=20000067&url=";
|
||||
|
||||
/**
|
||||
* 收款通道类型
|
||||
*/
|
||||
public static final String PAYMENT_CHANNEL_TYPE = "payment_channel_type";
|
||||
|
||||
/**
|
||||
* 原生通道
|
||||
*/
|
||||
public static final Integer PRIMORDIAL_CHANNEL = 5;
|
||||
|
||||
/**
|
||||
* 小程序默认支付路径
|
||||
*/
|
||||
public static final String DEFAULT_APPLET_PATH = "/pages/pay/index";
|
||||
|
||||
/**
|
||||
* 小程序默认支付参数名
|
||||
*/
|
||||
public static final String DEFAULT_APPLET_PARAM_NAME_PREFIX = "orderId=";
|
||||
|
||||
/**
|
||||
* 积分商城用户同步URL
|
||||
*/
|
||||
public static final String JF_SHOP_USER_SYNC_URL = "http://jf.shouyinbei.com/addons/shopro/syb_merchant/sysnmerchant";
|
||||
|
||||
/**
|
||||
* 生活圈会员卡默认过期时间 5(单位分钟)
|
||||
*/
|
||||
public static final Integer DEFAULT_LIFE_MEMBER_CARD_REFRESH_TIME = 5;
|
||||
|
||||
/**
|
||||
* 缴费通成本费率
|
||||
*/
|
||||
public static final BigDecimal DEFAULT_JFT_COST_RATE = BigDecimal.valueOf(30);
|
||||
|
||||
/**
|
||||
* 缴费通固定提现费率
|
||||
*/
|
||||
public static final BigDecimal DEFAULT_JFT_CASH_RATE = BigDecimal.valueOf(0.001);
|
||||
|
||||
/**
|
||||
* 缴费通固定提现费
|
||||
*/
|
||||
public static final BigDecimal DEFAULT_JFT_CASH_FEE = BigDecimal.valueOf(0.01);
|
||||
|
||||
|
||||
/**
|
||||
* 银盛交易回传字段key
|
||||
*/
|
||||
public static final String YS_PAY_ECHO_KEY_NAME = "extra_common_param";
|
||||
|
||||
/**
|
||||
* 随行付回传字段key
|
||||
*/
|
||||
public static final String SXF_PAY_ECHO_KEY_NAME = "extend";
|
||||
|
||||
/**
|
||||
* 瑞银信交易回传字段
|
||||
*/
|
||||
public static final String RYX_PAY_ECHO_KEY_NAME = "extend1";
|
||||
|
||||
/**
|
||||
* 默认秘钥设置
|
||||
*/
|
||||
public static final String DEFAULT_MD5_KEY = "4c8d277b0f274604af68e590cc0b3e6b";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package cn.pluss.platform.constants;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 项目常量
|
||||
*/
|
||||
public final class ProjectConstant {
|
||||
/**
|
||||
* 生成代码所在的基础包名称,可根据自己的项目修改(注意:这个配置修改之后需要手工修改src目录项目默认的包路径,使其保持一致,不然会找不到类)
|
||||
**/
|
||||
public static final String BASE_PACKAGE = "cn.pluss.platform";
|
||||
/**
|
||||
* 生成的Model所在包
|
||||
*/
|
||||
public static final String MODEL_PACKAGE = BASE_PACKAGE + ".dto.entity";
|
||||
/**
|
||||
* 生成的Mapper所在包
|
||||
*/
|
||||
public static final String MAPPER_PACKAGE = BASE_PACKAGE + ".dao";
|
||||
/**
|
||||
* 生成的Service所在包
|
||||
*/
|
||||
public static final String SERVICE_PACKAGE = BASE_PACKAGE + ".service";
|
||||
/**
|
||||
* 生成的ServiceImpl所在包
|
||||
*/
|
||||
public static final String SERVICE_IMPL_PACKAGE = SERVICE_PACKAGE + ".impl";
|
||||
/**
|
||||
* 生成的Controller所在包
|
||||
*/
|
||||
public static final String CONTROLLER_PACKAGE = BASE_PACKAGE + ".controller";
|
||||
/**
|
||||
* Mapper插件基础接口的完全限定名
|
||||
*/
|
||||
public static final String MAPPER_INTERFACE_REFERENCE = BASE_PACKAGE + ".core.Mapper";
|
||||
|
||||
public static final int BYTE_BUFFER = 1024;
|
||||
|
||||
public static final int BUFFER_MULTIPLE = 10;
|
||||
|
||||
public static final Integer PAGE_SIZE = 10;
|
||||
|
||||
public static Set<String> METHOD_URL_SET = new HashSet<>();
|
||||
public static boolean isPass = false;
|
||||
|
||||
public static class FilePostFix {
|
||||
public static final String ZIP_FILE = ".zip";
|
||||
public static final String[] IMAGES = { "jpg", "jpeg", "JPG", "JPEG", "gif", "GIF", "bmp", "BMP", "png" };
|
||||
public static final String[] ZIP = { "ZIP", "zip", "rar", "RAR" };
|
||||
public static final String[] VIDEO = { "mp4", "MP4", "mpg", "mpe", "mpa", "m15", "m1v", "mp2", "rmvb" };
|
||||
public static final String[] APK = { "apk", "exe" };
|
||||
public static final String[] OFFICE = { "xls", "xlsx", "docx", "doc", "ppt", "pptx" };
|
||||
|
||||
}
|
||||
|
||||
public class FileType {
|
||||
public static final int FILE_IMG = 1;
|
||||
public static final int FILE_ZIP = 2;
|
||||
public static final int FILE_VEDIO = 3;
|
||||
public static final int FILE_APK = 4;
|
||||
public static final int FIVE_OFFICE = 5;
|
||||
public static final String FILE_IMG_DIR = "/img/";
|
||||
public static final String FILE_ZIP_DIR = "/zip/";
|
||||
public static final String FILE_VEDIO_DIR = "/video/";
|
||||
public static final String FILE_APK_DIR = "/apk/";
|
||||
public static final String FIVE_OFFICE_DIR = "/office/";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package cn.pluss.platform.constants;
|
||||
|
||||
public class ServiceConstants {
|
||||
|
||||
/**
|
||||
* 微信支付
|
||||
*/
|
||||
public static final String PAYMENT_PLATFORM_WECHAT = "wechatPay";
|
||||
|
||||
/**
|
||||
* 支付宝支付
|
||||
*/
|
||||
public static final String PAYMENT_PLATFORM_ALIPAY = "aliPay";
|
||||
|
||||
|
||||
|
||||
public final static String FAIL="FAIL";
|
||||
public final static String SUCCESS="SUCCESS";
|
||||
|
||||
public final static String SERVICE_NOT_FOUNDE="未找该业务接口";
|
||||
public final static String SESSION_USER="session_user";
|
||||
public final static String SESSION_MERCHANT="session_merchant";
|
||||
public final static String SESSION_MERCHANT_ENTITY="session_merchant_entity";
|
||||
public final static String SESSION_MERCHANT_OBJECT="session_merchant_object";
|
||||
|
||||
public final static String DEFAULT_HREF="www.baidu.com";
|
||||
|
||||
public final static String REQUST_RETIRN_LOACL="1";
|
||||
public final static String REQUST_RETIRN_JUMP="2";
|
||||
|
||||
public final static String CALL_WAP="wap";
|
||||
public final static String CALL_WEB="web";
|
||||
|
||||
public final static String DATEFORMAT="yyyy-MM-dd HH:mm:ss";
|
||||
public final static String WECHATDATEFORMAT="yyyyMMddHHmmss";
|
||||
public final static String DATEONLY="yyyyMMdd";
|
||||
public final static String TABLETYPE="hhmmss";
|
||||
|
||||
public final static String IMAGE_PRODUCT_MOUDLE="product";
|
||||
public final static String IMAGE_PRODUCT_MOUDLE_DESC="列表图片";
|
||||
|
||||
public final static String IMAGE_MERCHANT_MOUDLE="merchant";
|
||||
public final static String IMAGE_MERCHANT_MOUDLE_DESC="商户图片";
|
||||
|
||||
public final static String IMAGE_INDEX_ACTIVITY_MOUDLE="index_activity";
|
||||
public final static String IMAGE_INDEX_ACTIVITY_MOUDLE_DESC="首页活动图";
|
||||
|
||||
public final static String IMAGE_BRAND_MOUDLE="brand";
|
||||
public final static String IMAGE_BRAND_MOUDLE_DESC="品牌图片";
|
||||
|
||||
public final static String IMAGE_PRODUCT_DETAILS_MOUDLE="details";
|
||||
public final static String IMAGE_PRODUCT_DETAILS_MOUDLE_DESC="详情图片";
|
||||
|
||||
public final static String WEIXIN_PAY_UNIFIED_URL="https://api.mch.weixin.qq.com/pay/unifiedorder";
|
||||
|
||||
public final static String WEIXIN_PAY_MICROPAY_URL="https://api.mch.weixin.qq.com/pay/micropay";
|
||||
|
||||
|
||||
public final static String WEIXIN_PAY_ORDER_INFO_QUERY_URL="https://api.mch.weixin.qq.com/pay/orderquery";
|
||||
|
||||
public final static String WEIXIN_PAY_AGREEMENT_SUCCESS="SUCCESS";
|
||||
public final static String WEIXIN_PAY_DATA_SUCCESS="SUCCESS";
|
||||
|
||||
public final static String WEIXIN_PAY_SUCCESS="SUCCESS";
|
||||
|
||||
public final static String WEIXIN_PAY_FAIL="FAIL";
|
||||
|
||||
public final static String SHOP_CHANNEL="13";
|
||||
|
||||
//订单号前缀
|
||||
public final static String PREFIX_ORDER="11";
|
||||
|
||||
public final static String RETURNPAGEURL = "returnPageUrl";
|
||||
|
||||
public final static String PAYMENTURL = "paymentUrl";
|
||||
|
||||
public final static String NOTIFYURL = "notifyUrl";
|
||||
|
||||
public final static Integer ONLINE = 1;
|
||||
|
||||
public final static Integer CASH = 2;
|
||||
|
||||
public final static String PRODUCTNUM = "productNum";
|
||||
|
||||
public final static String REMOTETELEPHONE = "remoteTelephone";
|
||||
|
||||
public final static String PHONEMAC = "phoneMac";
|
||||
|
||||
public final static String BOXMAC = "boxMac";
|
||||
|
||||
public final static String SKIPFLAG = "skipFlag";
|
||||
|
||||
public final static String SKIPMERCHANTCODE = "skipMerchantCode";
|
||||
|
||||
public final static String GWADDRESS = "gwAddress";
|
||||
|
||||
public final static String BOXPORT = "boxPort";
|
||||
|
||||
public final static String TOKEN = "token";
|
||||
|
||||
//支付宝RSA公钥
|
||||
public final static String ALIPAY_PUBLIC_KEY="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDUJ8o7gFbWZlw6xVjnEjVBTt/9iM9gFAdg+lmRFfyaDTXcHkVeUs+R99RB7mkzZjp/TrwhNMtN6Bn98tt66vWQ0MffWgsOb0zkRTxoqr2CQD1CdCd+FdunED/Z/JS3H2rctUMvSpoyYxLmquAm75S2O395Y2y1yopntKMzTt5PewIDAQAB";
|
||||
//商家RSA私钥
|
||||
public final static String ALIPAY_PRIVATE_KEY="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANQnyjuAVtZmXDrFWOcSNUFO3/2Iz2AUB2D6WZEV/JoNNdweRV5Sz5H31EHuaTNmOn9OvCE0y03oGf3y23rq9ZDQx99aCw5vTORFPGiqvYJAPUJ0J34V26cQP9n8lLcfaty1Qy9KmjJjEuaq4CbvlLY7f3ljbLXKime0ozNO3k97AgMBAAECgYA/Q6pLugarIpUINYdASK62zeV/fkeQuAhHRABngm30JlJUVHaNHRamyYdzLbwTRr3U7s6s/EhP8BGoJ76JVf1p6cmQns6s4IlYdq61y+GQCQEM1rGx3gdM6zGFHo/dsJwEM3+r9wTmWMnf1re6kGj2PdqdlUhqs0ZwB0syTdzdIQJBAOrIn8v4V5X6yyIqO3y4acbSnx7CwgUOn/KUGZdv7xKiJz4mOqFgLes2MPIKqo3DU8ItL99g7rPBkwOQBR71AjECQQDnU7G5SKyq/6NSQ/ym8rfmD6pRoIM33GGCAYWT/K5eeagtAw1iLX1drHhN/QrIcbY4Y9Wj+24R75nQU7MoVnVrAkEA0y3JremevmRqujxKbZBidFeWkFCVu37AF61mp3QjEhuQOLKiIe0k4GBJ/ivh5MlAWXPTj5TcoAsJdTbhpEq0wQJAFkTbVg/l92w2p8O9vcCd7XrSlZsTJryDcoV8+3sWuieSBgtGLY5dhDgHONLER/mSZilONsQMm5NqRkDYfWidUwJAYZapzIvzmbqFajsSvk52GppXThi7FdJLDMO5f51VvzQ0J3LRH90G7vPyRi1HtmDWgPfwJnNzAP18Yqaimh/fcw==";
|
||||
|
||||
|
||||
public final static String USER_INFO_USERNAME = "userName";
|
||||
public final static String USER_INFO_PHONE = "userPhone";
|
||||
public final static String ACTIVITY_CODE = "activity_code";
|
||||
public final static String CURRENT_USER = "CURRENT_USER";
|
||||
public final static String SESSION_USER_OPENID = "openId";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package cn.pluss.platform.constants.jft;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* TODO
|
||||
* 缴费通基础常量配置
|
||||
* @author crystal
|
||||
* @date 2022/6/16 15:59
|
||||
*/
|
||||
public class JftConstant {
|
||||
|
||||
/**
|
||||
* 跳转小程序收款单页面url 或者是h5支付连接
|
||||
*/
|
||||
public static final String JUMP_JFT_APPLET_URL =
|
||||
"https://XXXXXX/wap/jft/auth?tk=TOKEN";
|
||||
|
||||
/**
|
||||
* 收款单最少支付金额
|
||||
*/
|
||||
public static final BigDecimal JFT_MIN_PAY_AMT = BigDecimal.valueOf(0.5);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package cn.pluss.platform.entitiy;
|
||||
|
||||
/**
|
||||
* @author yuchen
|
||||
* @Description
|
||||
*/
|
||||
public class ActionInfo {
|
||||
|
||||
private Scene scene;
|
||||
|
||||
public Scene getScene() {
|
||||
return scene;
|
||||
}
|
||||
|
||||
public void setScene(Scene scene) {
|
||||
this.scene = scene;
|
||||
}
|
||||
|
||||
|
||||
public ActionInfo(Scene scene) {
|
||||
this.scene = scene;
|
||||
}
|
||||
public ActionInfo() {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package cn.pluss.platform.entitiy;
|
||||
|
||||
import cn.pluss.platform.config.mybatis.SqlConditionExtra;
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@Data
|
||||
@TableName("tb_pluss_req_records")
|
||||
public class ReqRecords {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private String uri;
|
||||
|
||||
private Long userId;
|
||||
|
||||
private String loginName;
|
||||
|
||||
private String ip;
|
||||
|
||||
private String phone;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField(value = "createTime", fill = FieldFill.INSERT)
|
||||
private Date createTime;
|
||||
|
||||
/**
|
||||
* 创建时间 开始时间
|
||||
*/
|
||||
@TableField(select = false, value = "createTime", condition = SqlConditionExtra.GT)
|
||||
private Date createTimeStart;
|
||||
|
||||
/**
|
||||
* 创建时间 截止时间
|
||||
*/
|
||||
@TableField(select = false, value = "createTime", condition = SqlConditionExtra.LT)
|
||||
private Date createTimeEnd;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package cn.pluss.platform.entitiy;
|
||||
|
||||
/**
|
||||
* @author yuchen
|
||||
*
|
||||
* @Description
|
||||
*/
|
||||
public class Scene {
|
||||
|
||||
private String scene_str;
|
||||
|
||||
public String getScene_str() {
|
||||
return scene_str;
|
||||
}
|
||||
|
||||
public void setScene_str(String scene_str) {
|
||||
this.scene_str = scene_str;
|
||||
}
|
||||
|
||||
public Scene(String scene_str) {
|
||||
this.scene_str = scene_str;
|
||||
}
|
||||
public Scene() {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package cn.pluss.platform.entitiy;
|
||||
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
|
||||
/**
|
||||
* 结算类型枚举
|
||||
* @author Administrator
|
||||
* @date 2021/07/12
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum SettleTypeEnum {
|
||||
|
||||
D0("D0",0,"D0实时结算"),
|
||||
D1("D1",1,"D1次日结算");
|
||||
|
||||
private String code;
|
||||
|
||||
private Integer value;
|
||||
|
||||
private String name;
|
||||
|
||||
public static boolean checkValues(String code) {
|
||||
SettleTypeEnum[] settleTypeEnums = values();
|
||||
boolean flag = false;
|
||||
for (SettleTypeEnum businessModeEnum : settleTypeEnums) {
|
||||
if(businessModeEnum.getCode().equals(code)){
|
||||
flag = true;
|
||||
}
|
||||
}
|
||||
if(!flag){
|
||||
MsgException.throwException("结算参数有误!");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package cn.pluss.platform.entitiy;
|
||||
|
||||
import cn.pluss.platform.util.StringUtil;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
/**
|
||||
* 自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息.
|
||||
*/
|
||||
@Data
|
||||
public class ShiroUser implements Serializable {
|
||||
private static final long serialVersionUID = -1373760761780840081L;
|
||||
private String loginName;
|
||||
private String name;
|
||||
private Long id;
|
||||
private Long areaId;
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 当前登录的用户类型 merchant:商家,promoter:推广人 staff:员工 (不是管理员时的用户类型)
|
||||
*/
|
||||
private String userType;
|
||||
|
||||
private String staffType;
|
||||
/**
|
||||
* 商户code
|
||||
*/
|
||||
private String merchantCode;
|
||||
|
||||
/**
|
||||
* 本函数输出将作为默认的<shiro:principal/>输出.
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return loginName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 重载equals,只计算loginName;
|
||||
*/
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.loginName.hashCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* 重载equals,只比较loginName
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == null || !(obj instanceof ShiroUser))
|
||||
return false;
|
||||
ShiroUser o = (ShiroUser) obj;
|
||||
return StringUtil.equals(loginName, o.loginName);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package cn.pluss.platform.entitiy;
|
||||
|
||||
/**
|
||||
* @author yuchen
|
||||
*
|
||||
* @Description
|
||||
*/
|
||||
public class SystemConfig {
|
||||
private int id;
|
||||
private String propertyKey;
|
||||
private String propertyValue;
|
||||
private String propertyDesc;
|
||||
private int propertyIndex;
|
||||
private String systemId;
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SystemConfigEntity [id=" + id + ", propertyKey=" + propertyKey
|
||||
+ ", propertyValue=" + propertyValue + ", propertyDesc="
|
||||
+ propertyDesc + ", propertyIndex=" + propertyIndex
|
||||
+ ", systemId=" + systemId + "]";
|
||||
}
|
||||
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
public String getPropertyKey() {
|
||||
return propertyKey;
|
||||
}
|
||||
public void setPropertyKey(String propertyKey) {
|
||||
this.propertyKey = propertyKey;
|
||||
}
|
||||
public String getPropertyValue() {
|
||||
return propertyValue;
|
||||
}
|
||||
public void setPropertyValue(String propertyValue) {
|
||||
this.propertyValue = propertyValue;
|
||||
}
|
||||
public String getPropertyDesc() {
|
||||
return propertyDesc;
|
||||
}
|
||||
public void setPropertyDesc(String propertyDesc) {
|
||||
this.propertyDesc = propertyDesc;
|
||||
}
|
||||
public String getSystemId() {
|
||||
return systemId;
|
||||
}
|
||||
public void setSystemId(String systemId) {
|
||||
this.systemId = systemId;
|
||||
}
|
||||
public int getPropertyIndex() {
|
||||
return propertyIndex;
|
||||
}
|
||||
public void setPropertyIndex(int propertyIndex) {
|
||||
this.propertyIndex = propertyIndex;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package cn.pluss.platform.entitiy;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import lombok.Data;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* CREATE TABLE `tb_pluss_unknown_exception` (
|
||||
* `id` int(11) NOT NULL,
|
||||
* `name` varchar(255) NOT NULL,
|
||||
* `desc` longtext COMMENT '异常内容',
|
||||
* `createTime` datetime DEFAULT NULL COMMENT '创建时间',
|
||||
* PRIMARY KEY (`id`)
|
||||
* ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
*/
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
public class UnknownException {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String uri;
|
||||
|
||||
private Long userId;
|
||||
|
||||
private String params;
|
||||
|
||||
@TableField("`desc`")
|
||||
private String desc;
|
||||
|
||||
private Date createTime;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package cn.pluss.platform.entitiy;
|
||||
|
||||
/**
|
||||
* @author yuchen
|
||||
*
|
||||
* @Description
|
||||
*/
|
||||
public class WechatQRCode {
|
||||
|
||||
// 获取的二维码
|
||||
private String ticket;
|
||||
// 二维码的有效时间,单位为秒,最大不超过2592000(即30天)
|
||||
private int expire_seconds;
|
||||
|
||||
private String url;
|
||||
|
||||
public String getTicket() {
|
||||
return ticket;
|
||||
}
|
||||
public void setTicket(String ticket) {
|
||||
this.ticket = ticket;
|
||||
}
|
||||
public int getExpire_seconds() {
|
||||
return expire_seconds;
|
||||
}
|
||||
public void setExpire_seconds(int expire_seconds) {
|
||||
this.expire_seconds = expire_seconds;
|
||||
}
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package cn.pluss.platform.exception;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.ToString;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
/**
|
||||
* 该异常用于统计后台数据异常信息,定时任务类错误信息,
|
||||
* 此类报错无前端显示
|
||||
* @author DJH
|
||||
*/
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@ToString(callSuper = true)
|
||||
public class BackDataErrorException extends RuntimeException {
|
||||
|
||||
public BackDataErrorException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package cn.pluss.platform.exception;
|
||||
|
||||
public class ForbiddenException extends RuntimeException {
|
||||
|
||||
public ForbiddenException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package cn.pluss.platform.exception;
|
||||
|
||||
import cn.pluss.platform.api.ResultCode;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.ToString;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 一般异常信息的异常,全局捕获会抛出异常信息给前端
|
||||
* @author Djh
|
||||
*/
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@ToString(callSuper = true)
|
||||
public class MsgException extends RuntimeException {
|
||||
|
||||
private final Serializable obj;
|
||||
private final ResultCode code;
|
||||
|
||||
public MsgException(String msg) {
|
||||
this(msg, null);
|
||||
}
|
||||
|
||||
public MsgException(String msg, Serializable obj) {
|
||||
this(ResultCode.FAIL, msg, obj);
|
||||
}
|
||||
|
||||
public MsgException(ResultCode code, String msg, Serializable obj) {
|
||||
super(msg);
|
||||
this.code = code;
|
||||
this.obj = obj;
|
||||
}
|
||||
|
||||
public static void throwException(String msg) throws MsgException {
|
||||
throw new MsgException(msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param result
|
||||
* @param errMsg
|
||||
*
|
||||
* @throws MsgException 为空的时候抛出异常
|
||||
*/
|
||||
public static void check(boolean result, String errMsg) throws MsgException {
|
||||
if (result) {
|
||||
throw new MsgException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param obj1
|
||||
* @param errMsg
|
||||
*/
|
||||
public static void checkNull(Object obj1, String errMsg) throws MsgException {
|
||||
if (obj1 == null) {
|
||||
throw new MsgException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkEquals(Object obj1, Object obj2, String errMsg) {
|
||||
if (obj1.equals(obj2)) {
|
||||
throw new MsgException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkUnequals(Object obj1, Object obj2, String errMsg) {
|
||||
if (!obj1.equals(obj2)) {
|
||||
throw new MsgException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkNonNull(Object obj1, String errMsg) throws MsgException {
|
||||
if (obj1 != null) {
|
||||
throw new MsgException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public static void checkBlank(String field, String errMsg) throws MsgException {
|
||||
if (StringUtils.isBlank(field)) {
|
||||
throw new MsgException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void checkBlank(List<T> dataList, String errMsg) throws MsgException {
|
||||
if (dataList == null || dataList.isEmpty()) {
|
||||
throw new MsgException(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void checkNonBlank(List<T> dataList, String errMsg) throws MsgException {
|
||||
if (dataList != null && !dataList.isEmpty()) {
|
||||
throw new MsgException(errMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package cn.pluss.platform.exception;
|
||||
|
||||
/**
|
||||
* 支付风险异常
|
||||
*/
|
||||
public class PayRiskException extends Exception {
|
||||
|
||||
public PayRiskException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package cn.pluss.platform.exception;
|
||||
|
||||
/**
|
||||
* 费率未发生变更的异常信息
|
||||
*/
|
||||
public class RateNoChangeException extends MsgException {
|
||||
|
||||
public RateNoChangeException() {
|
||||
super("未修改费率");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package cn.pluss.platform.exception;
|
||||
|
||||
public class ThirdException extends RuntimeException {
|
||||
|
||||
public ThirdException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package cn.pluss.platform.exception;
|
||||
|
||||
/**
|
||||
* 未授权异常
|
||||
* @author SSS
|
||||
*/
|
||||
public class UnauthorizedException extends RuntimeException {
|
||||
|
||||
public UnauthorizedException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package cn.pluss.platform.filter;
|
||||
|
||||
import com.alibaba.druid.support.http.WebStatFilter;
|
||||
|
||||
import javax.servlet.annotation.WebFilter;
|
||||
import javax.servlet.annotation.WebInitParam;
|
||||
|
||||
@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
|
||||
initParams={
|
||||
@WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源
|
||||
}
|
||||
)
|
||||
public class DruidStatFilter extends WebStatFilter {
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package cn.pluss.platform.interceptor;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author DJH
|
||||
*/
|
||||
@Slf4j
|
||||
public class RequestInfoInterceptor implements HandlerInterceptor {
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
|
||||
// 所有请求第一个进入的方法
|
||||
String ip = httpServletRequest.getRemoteHost();
|
||||
InputStream is = httpServletRequest.getInputStream();
|
||||
StringBuilder responseStrBuilder = new StringBuilder();
|
||||
BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
|
||||
String inputStr;
|
||||
while ((inputStr = streamReader.readLine()) != null) {
|
||||
responseStrBuilder.append(inputStr);
|
||||
}
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
httpServletRequest.setAttribute("startTime", startTime);
|
||||
|
||||
Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
|
||||
Map<String, Object> headers = new HashMap<>();
|
||||
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String key = headerNames.nextElement();
|
||||
String value = httpServletRequest.getHeader(key);
|
||||
headers.put(key, value);
|
||||
}
|
||||
|
||||
if (handler instanceof HandlerMethod) {
|
||||
StringBuilder sb = new StringBuilder(1000);
|
||||
String header = httpServletRequest.getHeader("user-agent");
|
||||
System.out.println("Header info : " + header);
|
||||
sb.append("------------------------------------------------------------\n");
|
||||
HandlerMethod h = (HandlerMethod) handler;
|
||||
String typeName = h.getBean().getClass().getTypeName();
|
||||
typeName = typeName.replaceAll("(\\w)\\w*\\.", "$1.");
|
||||
int end = typeName.indexOf("$");
|
||||
if (end == -1) {
|
||||
end = typeName.length();
|
||||
}
|
||||
|
||||
//Controller 的包名
|
||||
sb.append("Controller: ").append(typeName, 0, end).append("\n");
|
||||
//方法名称
|
||||
sb.append("Method : ").append(h.getMethod().getName()).append("\n");
|
||||
//所有的请求参数
|
||||
sb.append("Params : ").append(getParameterInfo(httpServletRequest)).append("\n");
|
||||
|
||||
if (responseStrBuilder.length() > 1000) {
|
||||
sb.append("body: ").append(responseStrBuilder.substring(0, 1000)).append("\n");
|
||||
} else {
|
||||
sb.append("body: ").append(responseStrBuilder).append("\n");
|
||||
}
|
||||
sb.append("headers : ").append(JSONObject.toJSONString(headers)).append("\n");
|
||||
//部分请求链接
|
||||
sb.append("URI : ").append(httpServletRequest.getRequestURI()).append("\n");
|
||||
|
||||
log.info("request info : \n {}", sb);
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
|
||||
|
||||
}
|
||||
|
||||
private Map<String, Object> getParameterInfo(HttpServletRequest request) {
|
||||
Map<String, Object> parameter = new HashMap<>();
|
||||
Map<String, String[]> parameterMap = request.getParameterMap();
|
||||
|
||||
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
String[] parameterValues = entry.getValue();
|
||||
if (parameterValues.length == 1) {
|
||||
int length = parameterValues[0].length();
|
||||
if (length > 255) {
|
||||
parameter.put(key, parameterValues[0].substring(0, 255) + "...");
|
||||
} else {
|
||||
parameter.put(key, parameterValues[0]);
|
||||
}
|
||||
} else {
|
||||
parameter.put(key, Arrays.toString(parameterValues));
|
||||
}
|
||||
}
|
||||
|
||||
return parameter;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package cn.pluss.platform.interceptor.filter;
|
||||
|
||||
import cn.pluss.platform.interceptor.wrapper.RequestWrapper;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 用于替换默认的 HttpServletRequest
|
||||
* @author Djh
|
||||
*/
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class WrapFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
|
||||
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
|
||||
// String contentType = httpServletRequest.getContentType();
|
||||
// String method = "multipart/form-data";
|
||||
|
||||
// if (contentType != null && contentType.contains(method)) {
|
||||
// // 将转化后的 request 放入过滤链中
|
||||
// httpServletRequest = new StandardServletMultipartResolver().resolveMultipart(httpServletRequest);
|
||||
// }
|
||||
|
||||
|
||||
ServletRequest requestWrapper = new RequestWrapper(httpServletRequest);
|
||||
filterChain.doFilter(requestWrapper, servletResponse);
|
||||
|
||||
// filterChain.doFilter(servletRequest, servletResponse);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package cn.pluss.platform.interceptor.wrapper;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
import javax.servlet.ReadListener;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletRequestWrapper;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
@Slf4j
|
||||
public class RequestWrapper extends HttpServletRequestWrapper {
|
||||
|
||||
private Map<String, String[]> params = new HashMap<>();
|
||||
|
||||
/**
|
||||
* 用于将流保存下来
|
||||
*/
|
||||
private byte[] requestBody = null;
|
||||
|
||||
private final Map<String, String> headers = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public Map<String, String[]> getParameterMap() {
|
||||
Map<String, String[]> result = new HashMap<>();
|
||||
result.putAll(super.getParameterMap());
|
||||
result.putAll(params);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enumeration<String> getParameterNames() {
|
||||
Map<String, String[]> result = new HashMap<>();
|
||||
result.putAll(super.getParameterMap());
|
||||
result.putAll(params);
|
||||
|
||||
Vector<String> l = new Vector<>(result.keySet());
|
||||
return l.elements();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getParameterValues(String name) {
|
||||
Object v = params.get(name);
|
||||
|
||||
if (v == null) {
|
||||
return super.getParameterValues(name);
|
||||
} else {
|
||||
return (String[]) v;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getParameter(String name) {
|
||||
Object v = params.get(name);
|
||||
if (v == null) {
|
||||
return super.getParameter(name);
|
||||
} else {
|
||||
String[] strArr = (String[]) v;
|
||||
if (strArr.length > 0) {
|
||||
return strArr[0];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addParam(String key, String... value) {
|
||||
params.put(key, value);
|
||||
}
|
||||
|
||||
public void addHeader(String name,String value){
|
||||
headers.put(name, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enumeration<String> getHeaderNames() {
|
||||
List<String> names= Collections.list(super.getHeaderNames());
|
||||
names.addAll(headers.keySet());
|
||||
|
||||
return Collections.enumeration(names);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enumeration<String> getHeaders(String name) {
|
||||
List<String> list= Collections.list(super.getHeaders(name));
|
||||
|
||||
if (headers.containsKey(name)){
|
||||
list.add(headers.get(name));
|
||||
}
|
||||
|
||||
return Collections.enumeration(list);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHeader(String name) {
|
||||
String value=super.getHeader(name);
|
||||
|
||||
if (headers.containsKey(name)){
|
||||
value=headers.get(name);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setRequestBody(String requestBody) {
|
||||
this.requestBody = requestBody.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public RequestWrapper(HttpServletRequest request) {
|
||||
super(request);
|
||||
try {
|
||||
String contentType = request.getContentType();
|
||||
// 这里排除表单请求
|
||||
if (contentType != null && !contentType.contains("x-www-form-urlencoded")) {
|
||||
requestBody = StreamUtils.copyToByteArray(request.getInputStream());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ServletInputStream getInputStream() {
|
||||
if (requestBody == null) {
|
||||
requestBody = new byte[0];
|
||||
}
|
||||
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);
|
||||
return new ServletInputStream() {
|
||||
|
||||
@Override
|
||||
public int read() {
|
||||
return byteArrayInputStream.read();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setReadListener(ReadListener listener) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFinished() {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public BufferedReader getReader() throws IOException {
|
||||
return new BufferedReader(new InputStreamReader(getInputStream()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package cn.pluss.platform.jty;
|
||||
|
||||
import cn.pluss.platform.entitiy.SettleTypeEnum;
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* TODO
|
||||
* 佳天亿通知类型枚举
|
||||
* @author crystal
|
||||
* @date 2022/3/17 16:45
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum JtyNoticeEnum {
|
||||
|
||||
TEXT("1001","text","文本消息"),
|
||||
SUCCESS("1002","pay","成功消息"),
|
||||
CANCEL("1003","cancel","取消消息");
|
||||
|
||||
private String code;
|
||||
|
||||
private String name;
|
||||
|
||||
private String desc;
|
||||
|
||||
public static String getConverCode(String name) {
|
||||
JtyNoticeEnum[] noticeEnums = values();
|
||||
for (JtyNoticeEnum notice : noticeEnums) {
|
||||
if(notice.getName().equals(name)){
|
||||
return notice.getCode();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package cn.pluss.platform.jty;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* TODO
|
||||
* 佳天亿响应参数封装
|
||||
* @author crystal
|
||||
* @date 2022/3/17 16:00
|
||||
*/
|
||||
@Data
|
||||
public class JtyResponse {
|
||||
|
||||
private String code;
|
||||
|
||||
private String message;
|
||||
|
||||
private Object result;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package cn.pluss.platform.jty;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* TODO
|
||||
* 佳天意授权返回结果参数封装
|
||||
* @author crystal
|
||||
* @date 2022/3/17 16:02
|
||||
*/
|
||||
@Data
|
||||
public class JtyResult {
|
||||
|
||||
private String authSign;
|
||||
|
||||
private Long expirationTime;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package cn.pluss.platform.jty;
|
||||
|
||||
import cn.pluss.platform.jty.constant.JtyConstant;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 佳天亿音箱授权实体类分装
|
||||
* @author bzg
|
||||
*/
|
||||
@Data
|
||||
public class JtyYxApiAuth {
|
||||
|
||||
/**
|
||||
* appId
|
||||
*/
|
||||
private String appId;
|
||||
|
||||
/**
|
||||
* appSecret
|
||||
*/
|
||||
private String appSecret;
|
||||
|
||||
/**
|
||||
* 版本号
|
||||
*/
|
||||
private String apiVersion;
|
||||
|
||||
|
||||
public JtyYxApiAuth(String appId,String appSecret) {
|
||||
this.appId = appId;
|
||||
this.appSecret = appSecret;
|
||||
this.apiVersion = JtyConstant.VERSION;
|
||||
}
|
||||
|
||||
public JtyYxApiAuth() {
|
||||
this.appId = JtyConstant.APPID;
|
||||
this.appSecret = JtyConstant.SECRET;
|
||||
this.apiVersion = JtyConstant.VERSION;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package cn.pluss.platform.jty;
|
||||
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import cn.pluss.platform.jty.constant.JtyConstant;
|
||||
import cn.pluss.platform.util.StringUtil;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* TODO
|
||||
* 佳天亿音箱播报参数封装
|
||||
* @author crystal
|
||||
* @date 2022/3/17 15:32
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class JtyYxPayNotice {
|
||||
|
||||
/**
|
||||
* 设备号
|
||||
*/
|
||||
private String deviceNum;
|
||||
|
||||
/**
|
||||
* 通知类型,1001(普通文本);1002(支付成功消息);1003(支付失败消息)
|
||||
*/
|
||||
private String noticeType;
|
||||
/**
|
||||
* 支付方式
|
||||
* 10001 支付宝
|
||||
* 10002 微信
|
||||
* 10003 收银呗
|
||||
*/
|
||||
private String payType;
|
||||
|
||||
/**
|
||||
* 对应产品编码
|
||||
*/
|
||||
private String productNum;
|
||||
|
||||
/**
|
||||
* 支付金额单位元
|
||||
*/
|
||||
private BigDecimal payAmount;
|
||||
|
||||
/**
|
||||
* 请求唯一标识
|
||||
*/
|
||||
private String requestId;
|
||||
|
||||
public JtyYxPayNotice(String deviceNum, String type, BigDecimal payAmount) {
|
||||
this.deviceNum = deviceNum;
|
||||
String noticeType = JtyNoticeEnum.getConverCode(type);
|
||||
if(StringUtil.isEmpty(noticeType)){
|
||||
MsgException.throwException("消息类型配置异常");
|
||||
}
|
||||
this.noticeType = noticeType;
|
||||
this.payAmount = payAmount;
|
||||
this.requestId = UUID.randomUUID().toString();
|
||||
this.payType = "1003";
|
||||
this.productNum = JtyConstant.PRODUCT_REQ_NUM;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package cn.pluss.platform.jty.constant;
|
||||
|
||||
/**
|
||||
* TODO
|
||||
* 佳天亿静态配置参数
|
||||
* @author crystal
|
||||
* @date 2022/3/17 15:15
|
||||
*/
|
||||
public class JtyConstant {
|
||||
|
||||
public static final String APPID = "Y2VzaGlnb25nc2k=";
|
||||
|
||||
public static final String SECRET = "NTE0YTFmMGY0YjU3NGQ3NTkwMzE0MzFhZTRkNDBkNzU=";
|
||||
|
||||
public static final String VERSION = "1.0";
|
||||
|
||||
public static final String API_TEST_DOMAIN = "http://101.132.171.8:17002";
|
||||
|
||||
public static final String PRODUCT_REQ_NUM = "fb_auth_0001";
|
||||
|
||||
public static final String TEST_DEVICE_NUM = "fb_a_d_10001";
|
||||
|
||||
public static final String PAY_NOTICE_METHOD = "/fbplatform/cloudHorn/payNotice";
|
||||
|
||||
public static final String API_AUTH_METHOD = "/fbplatform/auth/apiAuth";
|
||||
|
||||
public static final String CACHE_KEY_CODE_PRIFIX = "jty:authToken:";
|
||||
|
||||
public static final String SUCCESS_CODE = "00000";
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package cn.pluss.platform.mapper;
|
||||
|
||||
import cn.pluss.platform.entitiy.ReqRecords;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
|
||||
public interface ReqRecordsMapper extends BaseMapper<ReqRecords> {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package cn.pluss.platform.mapper;
|
||||
|
||||
import cn.pluss.platform.entitiy.UnknownException;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface UnknownExceptionMapper extends BaseMapper<UnknownException> {
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package cn.pluss.platform.service;
|
||||
|
||||
import lombok.Setter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.compress.utils.IOUtils;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import javax.mail.internet.MimeUtility;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* 发送电子邮件相关的功能service
|
||||
* @author nb2020
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class EmailService {
|
||||
|
||||
@Value("${spring.mail.nickname}")
|
||||
private String nickname;
|
||||
|
||||
@Value("${spring.mail.username}")
|
||||
private String username;
|
||||
|
||||
|
||||
public EmailService() {
|
||||
System.setProperty("mail.mime.splitlongparameters", "false");
|
||||
}
|
||||
|
||||
@Setter(onMethod_ = {@Autowired})
|
||||
private JavaMailSender mailSender;
|
||||
|
||||
/**
|
||||
* 发送邮件
|
||||
* @param tos 接收人邮箱数组
|
||||
* @param ccs 抄送人邮箱数组
|
||||
* @param title 邮件主题
|
||||
* @param content 邮件内容
|
||||
* @param workBook 附件excel
|
||||
*/
|
||||
public void sendEmail(String[] tos, String[] ccs, String title, String content, XSSFWorkbook workBook, String workBookName) {
|
||||
MimeMessage mimeMessage = mailSender.createMimeMessage();
|
||||
|
||||
MimeMessageHelper mimeMessageHelper;
|
||||
|
||||
try {
|
||||
mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
|
||||
mimeMessageHelper.setTo(tos);
|
||||
if (ccs != null) {
|
||||
mimeMessageHelper.setCc(ccs);
|
||||
}
|
||||
|
||||
mimeMessageHelper.setFrom(nickname + "<" + username + ">");
|
||||
mimeMessageHelper.setSubject(title);
|
||||
mimeMessageHelper.setText(content);
|
||||
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
workBook.write(out);
|
||||
byte[] bookByteArr = out.toByteArray();
|
||||
InputStream in = new ByteArrayInputStream(bookByteArr);
|
||||
String newFileName = MimeUtility.encodeWord(workBookName, "utf-8", "B");
|
||||
mimeMessageHelper.addAttachment(newFileName, new ByteArrayResource(IOUtils.toByteArray(in), "application/vnd.ms-excel;charset=UTF-8"));
|
||||
|
||||
} catch (IOException | MessagingException e) {
|
||||
log.error("邮件发送失败");
|
||||
e.printStackTrace();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
mailSender.send(mimeMessage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package cn.pluss.platform.service;
|
||||
|
||||
import cn.pluss.platform.entitiy.ReqRecords;
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import cn.pluss.platform.mapper.ReqRecordsMapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* @author DJH
|
||||
*/
|
||||
@Service
|
||||
public class ReqRecordsService extends ServiceImpl<ReqRecordsMapper, ReqRecords> {
|
||||
|
||||
/**
|
||||
* 检查请求限制
|
||||
* @param reqRecords 请求相关参数, 手机号, 用户id, ip等
|
||||
* @param duringTime 请求限制间隔时间
|
||||
*/
|
||||
@Transactional(propagation = Propagation.NOT_SUPPORTED)
|
||||
public void checkLimit(ReqRecords reqRecords, long duringTime) {
|
||||
LambdaQueryWrapper<ReqRecords> qWrapper = Wrappers.lambdaQuery();
|
||||
|
||||
boolean andFlag = StringUtils.isNotEmpty(reqRecords.getIp())
|
||||
|| (reqRecords.getUserId() != null)
|
||||
|| StringUtils.isNotEmpty(reqRecords.getPhone())
|
||||
|| StringUtils.isNotEmpty(reqRecords.getLoginName());
|
||||
qWrapper.eq(ReqRecords::getUri, reqRecords.getUri())
|
||||
.and(andFlag, wrapper -> wrapper
|
||||
.or(StringUtils.isNotEmpty(reqRecords.getIp()), wrapper2 -> wrapper2.eq(ReqRecords::getIp, reqRecords.getIp()))
|
||||
.or(reqRecords.getUserId() != null, wrapper2 -> wrapper2.eq(ReqRecords::getUserId, reqRecords.getUserId()))
|
||||
.or(StringUtils.isNotEmpty(reqRecords.getPhone()), wrapper2 -> wrapper2.eq(ReqRecords::getPhone, reqRecords.getPhone()))
|
||||
.or(StringUtils.isNotEmpty(reqRecords.getLoginName()), wrapper2 -> wrapper2.eq(ReqRecords::getLoginName, reqRecords.getLoginName())))
|
||||
.orderByDesc(ReqRecords::getCreateTime)
|
||||
.last("limit 1");
|
||||
|
||||
long nextLimitTime = System.currentTimeMillis() - duringTime;
|
||||
|
||||
ReqRecords lastReqRecords = getBaseMapper().selectOne(qWrapper);
|
||||
if (lastReqRecords != null && lastReqRecords.getCreateTime().getTime() > nextLimitTime) {
|
||||
throw new MsgException("请求过于频繁,请稍后再试");
|
||||
}
|
||||
|
||||
save(reqRecords);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package cn.pluss.platform.service;
|
||||
|
||||
import cn.jiguang.common.utils.StringUtils;
|
||||
import cn.pluss.platform.entitiy.UnknownException;
|
||||
import cn.pluss.platform.mapper.UnknownExceptionMapper;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
|
||||
@Service
|
||||
public class UnknownExceptionService extends ServiceImpl<UnknownExceptionMapper, UnknownException> {
|
||||
|
||||
/**
|
||||
* 保存异常信息到数据库
|
||||
* @param e
|
||||
*/
|
||||
public void save(HttpServletRequest request, Exception e) {
|
||||
String body = null;
|
||||
try {
|
||||
InputStream is = request.getInputStream();
|
||||
StringBuilder responseStrBuilder = new StringBuilder();
|
||||
BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
|
||||
String inputStr;
|
||||
while ((inputStr = streamReader.readLine()) != null) {
|
||||
responseStrBuilder.append(inputStr);
|
||||
}
|
||||
body = responseStrBuilder.toString();
|
||||
} catch (Exception ignored) {
|
||||
// 不处理
|
||||
}
|
||||
|
||||
Map<String, Object> parameterInfo = getParameterInfo(request);
|
||||
StringWriter sw = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(sw, true));
|
||||
UnknownException unknownException = new UnknownException();
|
||||
unknownException.setCreateTime(new Date());
|
||||
unknownException.setName(e.getClass().getName());
|
||||
String desc = sw.toString();
|
||||
|
||||
Map<String, Object> headerInfo = getHeaderInfo(request);
|
||||
try {
|
||||
String userId = headerInfo.get("userId") + "";
|
||||
unknownException.setUserId(Long.parseLong(userId));
|
||||
} catch (Exception e2) {
|
||||
log.warn("没有userId");
|
||||
}
|
||||
|
||||
if (StringUtils.isNotEmpty(body)) {
|
||||
unknownException.setParams(body);
|
||||
} else {
|
||||
unknownException.setParams(JSON.toJSONString(parameterInfo));
|
||||
}
|
||||
unknownException.setUri(request.getRequestURI());
|
||||
unknownException.setDesc(desc);
|
||||
baseMapper.insert(unknownException);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存异常信息到数据库
|
||||
* @param e 异常信息
|
||||
*/
|
||||
public void save(Exception e) {
|
||||
String desc = getStackTrace(e);
|
||||
UnknownException unknownException = new UnknownException();
|
||||
unknownException.setCreateTime(new Date());
|
||||
unknownException.setName(e.getClass().getName());
|
||||
unknownException.setDesc(desc);
|
||||
baseMapper.insert(unknownException);
|
||||
}
|
||||
|
||||
private String getStackTrace(Exception e) {
|
||||
StringWriter sw = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(sw, true));
|
||||
return sw.toString();
|
||||
}
|
||||
|
||||
private Map<String, Object> getParameterInfo(HttpServletRequest request) {
|
||||
Map<String, Object> parameter = new HashMap<>();
|
||||
Map<String, String[]> parameterMap = request.getParameterMap();
|
||||
for (Map.Entry<String, String[]> entry: parameterMap.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
String[] parameterValues = entry.getValue();
|
||||
if (parameterValues.length == 1) {
|
||||
parameter.put(key, parameterValues[0]);
|
||||
} else {
|
||||
parameter.put(key, Arrays.toString(parameterValues));
|
||||
}
|
||||
}
|
||||
return parameter;
|
||||
}
|
||||
|
||||
private Map<String, Object> getHeaderInfo(HttpServletRequest request) {
|
||||
Map<String, Object> parameter = new HashMap<>(8);
|
||||
Enumeration<String> headerNames = request.getHeaderNames();
|
||||
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String key = headerNames.nextElement();
|
||||
parameter.put(key, request.getHeader(key));
|
||||
}
|
||||
|
||||
return parameter;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cn.pluss.platform.ty;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* @description:音箱4G音箱枚举参数
|
||||
* @author: Administrator
|
||||
* @DATE: 2021/12/6 18:21
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum Ys4GEnum {
|
||||
|
||||
/**
|
||||
* @description:博实结4G
|
||||
* @date: 2021/12/6 18:24
|
||||
*/
|
||||
BSJ_4G_YYS("ZF042","2021bsjZF042","https://ioe.car900.com/v1/openApi/dev/controlDevice.json"),
|
||||
/**
|
||||
* @description:天喻4G正式环境
|
||||
* @date: 2021/12/6 18:25
|
||||
*/
|
||||
TY_4G_YYS("IOT_ACCOUNT_PROD_SYB","SbjErK1z5gZ34dfHSH7k6Y6=","https://voice.typos.com.cn/api/bank/pushmsg");
|
||||
|
||||
private String appId;
|
||||
|
||||
private String secret;
|
||||
|
||||
private String domain;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package cn.pluss.platform.ty;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 4g音箱类型枚举
|
||||
* @author: Administrator
|
||||
* @DATE: 2021/12/10 11:37
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum Ys4GTypeEnum {
|
||||
|
||||
BSJ("BSJ","博实结"),
|
||||
TY("TY","天喻");
|
||||
|
||||
private String code;
|
||||
|
||||
private String name;
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import com.alipay.api.internal.util.codec.Base64;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
/**
|
||||
* @author ryx
|
||||
* AES加密工具类
|
||||
*/
|
||||
public class AESEncrypt {
|
||||
|
||||
public static final String KEY_ALGORITHM_PADDING = "AES/CBC/PKCS5Padding";
|
||||
private static final String KEY_ALGORITHM = "AES";
|
||||
public static SecureRandom random = new SecureRandom();
|
||||
|
||||
public static final String KEY_ALGORITHM_ECB_PADDING = "AES/ECB/PKCS5Padding";
|
||||
|
||||
/**
|
||||
* 生成二进制密钥
|
||||
*
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static byte[] initKey() throws Exception {
|
||||
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
|
||||
kg.init(256);
|
||||
return kg.generateKey().getEncoded();
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param key 密钥
|
||||
* @param ivParam 向量
|
||||
* @return 加密数据
|
||||
* @throws Exception
|
||||
*/
|
||||
public static byte[] encrypt(byte[] data, byte[] key, String ivParam) throws Exception {
|
||||
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
|
||||
// 创建密码器
|
||||
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_PADDING);
|
||||
if (StringUtils.trimToNull(ivParam) != null) {
|
||||
//使用CBC模式,需要一个向量iv,可增加加密算法的强度
|
||||
IvParameterSpec iv = new IvParameterSpec(ivParam.getBytes());
|
||||
// 初始化
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
|
||||
} else {
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
|
||||
}
|
||||
// 加密
|
||||
return cipher.doFinal(data);
|
||||
}
|
||||
|
||||
public static byte[] encryptEcb(byte[] data, byte[] key, String ivParam) throws Exception {
|
||||
// 创建密码器
|
||||
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_ECB_PADDING);
|
||||
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
|
||||
if (StringUtils.trimToNull(ivParam) != null) {
|
||||
//使用CBC模式,需要一个向量iv,可增加加密算法的强度
|
||||
IvParameterSpec iv = new IvParameterSpec(ivParam.getBytes());
|
||||
// 初始化
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
|
||||
} else {
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
|
||||
}
|
||||
// 加密
|
||||
return cipher.doFinal(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据加密
|
||||
*
|
||||
* @param data 待加密数据
|
||||
* @param key 密钥
|
||||
* @param ivParam 向量
|
||||
* @return 加密数据
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String encryptToString(byte[] data, byte[] key, String ivParam) throws Exception {
|
||||
return Base64.encodeBase64String(encrypt(data, key, ivParam));
|
||||
}
|
||||
|
||||
public static String encryptEcbToString(byte[] data, byte[] key, String ivParam) throws Exception {
|
||||
return Base64.encodeBase64String(encryptEcb(data, key, ivParam));
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据解密
|
||||
*
|
||||
* @param data 待解密数据
|
||||
* @param key 密钥
|
||||
* @param ivParam 向量
|
||||
* @return 解密数据
|
||||
* @throws Exception
|
||||
*/
|
||||
public static byte[] decrypt(byte[] data, byte[] key, String ivParam) throws Exception {
|
||||
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
|
||||
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_PADDING);// 创建密码器
|
||||
IvParameterSpec iv = new IvParameterSpec(ivParam.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);// 初始化
|
||||
byte[] result = cipher.doFinal(data);
|
||||
return result; // 加密
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据加密钥
|
||||
*
|
||||
* @param data 待解密数据
|
||||
* @param key 密钥
|
||||
* @param ivParam 向量
|
||||
* @return 解密数据
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String decryptToString(byte[] data, byte[] key, String ivParam) throws Exception {
|
||||
return new String(decrypt(data, key, ivParam), "utf-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据加密钥
|
||||
*
|
||||
* @param data 待解密数据
|
||||
* @param key 密钥
|
||||
* @param ivParam 向量
|
||||
* @return 解密数据
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String decryptEcbToString(byte[] data, byte[] key, String ivParam) throws Exception {
|
||||
return new String(decryptEcb(data, key, ivParam), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static byte[] decryptEcb(byte[] encryptedBytes, byte[] keyBytes, String IV) throws Exception{
|
||||
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_ECB_PADDING);
|
||||
SecretKey secretKey = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
|
||||
if (IV != null && StringUtils.trimToNull(IV) != null) {
|
||||
IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
|
||||
} else {
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey);
|
||||
}
|
||||
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
|
||||
return decryptedBytes;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param length
|
||||
* @return
|
||||
*/
|
||||
public static String getIVParam(int length) {
|
||||
StringBuilder ret = new StringBuilder();
|
||||
for (int i = 0; i < length; i++) {
|
||||
boolean isChar = (random.nextInt(2) % 2 == 0);// 输出字母还是数字
|
||||
if (isChar) { // 字符串
|
||||
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
|
||||
ret.append((char) (choice + random.nextInt(26)));
|
||||
} else { // 数字
|
||||
ret.append(Integer.toString(random.nextInt(10)));
|
||||
}
|
||||
}
|
||||
return ret.toString();
|
||||
}
|
||||
|
||||
public static String decryptEcb(String content, String sKey) {
|
||||
try {
|
||||
//实例化
|
||||
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_ECB_PADDING);
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(sKey.getBytes(StandardCharsets.UTF_8), "AES"));
|
||||
byte[] encrypted = java.util.Base64.getDecoder().decode(content); // 先用base64解密
|
||||
byte[] original = cipher.doFinal(encrypted);
|
||||
return new String(original, StandardCharsets.UTF_8);
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// public static void main(String[] args) {
|
||||
// String aa = "name=123&age=234";
|
||||
// try {
|
||||
// String p = AESEncrypt.encryptDefaultToString(aa);
|
||||
// System.out.println("p=>"+p);
|
||||
// String s = Base64.encodeBase64String(p.getBytes(StandardCharsets.UTF_8));
|
||||
// System.out.println("s=>"+s);
|
||||
// byte[] bytes = Base64.decodeBase64String(s);
|
||||
// String str = new String(bytes, "UTF-8");
|
||||
// System.out.println("=======str=>"+str);
|
||||
// String cc = AESEncrypt.decryptDefaultToString(str);
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
|
||||
// public static void main(String[] args) {
|
||||
// String aa = "name=123&age=234";
|
||||
// try {
|
||||
// String pa = AESEncrypt.encryptDefaultBaseToString(aa);
|
||||
// System.out.println("pa=>"+pa);
|
||||
// String cp = StringUtil.base64Encoder(pa);
|
||||
// System.out.println("cp=>"+cp);
|
||||
//
|
||||
// String de = StringUtil.base64Decoder(cp);
|
||||
// System.out.println("de=>"+de);
|
||||
// String cd = decryptDefaultBaseToString(de);
|
||||
// System.out.println("cd=>"+cd);
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.AlipayClient;
|
||||
import com.alipay.api.DefaultAlipayClient;
|
||||
import com.alipay.api.request.AlipayOpenAgentCreateRequest;
|
||||
import com.alipay.api.response.AlipayOpenAgentCreateResponse;
|
||||
|
||||
public class AliMerchantBatchNoUtil {
|
||||
|
||||
private static final String PRIVATE_KEY_STRING = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCN1NubOHroItIz7eLWWBDprPzToDr1cggn/V90ghPaoBWgmnZhD/CejX+KxHmQVQLEBVN6ehQgNSVGBj0hSHxkj1OCCU7Eu9qAIqRzkWY1RkZKoKOIcJbU+yL20XTs3kATgNm5jx8ejVQDsNqekS1bBrRX6xlU/mjMVFtKoZC/Vpv8yAmP6R9onkum4O0OgCWARKC40NuYVp9hPUgRpWJ/NIPSlO4j8zIPYFkjfsh84c8moVLZdhYDDbbEY3vnHutDa0A3d5f4MI4qXBZ6tW5wO5WG93U5E5jat73RUzBOc0zN+3U/Rsk+gq722ChLj4/ifp0NLqgjbKecs4wlM8A3AgMBAAECggEAQ1QjuAjU17QIA1zPTR9bUAKttqyesHukgY9XLBC/6g4KlkYdIjCV8j6LqE1iw/CHMpSwrziaqztvaVF23YDyhC5B3z4Z5Wyj6iYH2VDRq0KkBbNCTnfcMljRnUeLcRKEan3FXcAibrd6hZIEBjg2xrplDENvsBhhmXYGLGSMOTfoRFlc1DhvPdr3qxR9mljD2YcvIrxDVDPZ3P4wTcsIM6xZmXGrsFbI0sGxgm4a4fzMLUYxSvuMtc+auwasQ/393Le/kjdVBWr/hBJZbGIU5/NQN0EesOJD6dIFU07wDDuy4LYLVVjSN3EiynWfMJIrvLbnR1sMgKJ775wY61hIaQKBgQC/mFKwZdZvzsqnEMQmUfkUT5+v8BJvS4JApPpt+O2GMUAKoynk220U0rJW/QyEkTz6A/lR8ZStT6TyM14ulpOYDMJquZqSCoIHMrIdjhZRMqAVONUJHsYVvpLQLbJaDDEaCksnWE+77ULBstZaevkBgLmNsy6V4CxwLJKj0xMDEwKBgQC9giRaS4t2J5ZcNycuDEBhwPteSoFun/6bX4yPsZYdeB88NGs7j1oOk9MXrvQq69X0uXE8zv2DHrDvuoGI920m56bU/4wCuKoqpnLi0xFM1al0na12He6UmFKWa+kGBkH5p5BggPyaCFMwJI/qL3gZft56aWjliviwWSmI8pvOzQKBgHZw8d0+d1vTGJBC2x9dWX9m4a7f2GWY5kKUOoQ1eJCWbaKlz0Y9J6fRwJHqCQ0CxBFC16QClgi1zaA0hSqDx2YdrSpQ5u8VM+DDRDzlE4LKqw+zfG8Q6R+UGio7tZ/ZHZmdd2wxOclRGQ2pQr3Ye4qkSxEADfJ1DMOjqltAJualAoGALafl9C8RGVUuP2c2NDzVYfepV60hg7JeF7asWY4SOWVQOSPz1bSSoMJyb9lBj/mjYUMwCdNgdi91tzu6q3HYxS+4HMa4R4uPy5iwQv9Qwq8TFTpLqRJLAVe1RfIXgNEPIgOBoA5TTRTGXenhFi17hMDw/pLYp7yUb3/7pre0W90CgYAWb86ocBIpS8cKhZY2fcrHALzKh4cuxl68sNQcOxevt3tIak0KG+o/5/5l0uBW2qYSOJOl2u831VWuOWEJBk+h5brYCtTNIsa6lKdknhRP/NfAfWUiWEesPV5nfYKL85s8bf2x/gFv9Ah0S5K4cI+SCMVIzaQzQ2dN+cmlvM8rfQ==";
|
||||
private static final String PUBLIC_KEY_STRING = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjdTbmzh66CLSM+3i1lgQ6az806A69XIIJ/1fdIIT2qAVoJp2YQ/wno1/isR5kFUCxAVTenoUIDUlRgY9IUh8ZI9TgglOxLvagCKkc5FmNUZGSqCjiHCW1Psi9tF07N5AE4DZuY8fHo1UA7DanpEtWwa0V+sZVP5ozFRbSqGQv1ab/MgJj+kfaJ5LpuDtDoAlgESguNDbmFafYT1IEaVifzSD0pTuI/MyD2BZI37IfOHPJqFS2XYWAw22xGN75x7rQ2tAN3eX+DCOKlwWerVucDuVhvd1OROY2re90VMwTnNMzft1P0bJPoKu9tgoS4+P4n6dDS6oI2ynnLOMJTPANwIDAQAB";
|
||||
public static void getBatchNo() {
|
||||
|
||||
Map<String, Object> dataMap = new HashMap<String, Object>();
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","2019092467786259",PRIVATE_KEY_STRING,"json","GBK",PUBLIC_KEY_STRING,"RSA2");
|
||||
AlipayOpenAgentCreateRequest request = new AlipayOpenAgentCreateRequest();
|
||||
request.setBizContent("{" +
|
||||
"\"account\":\"test@alipay.com\"," +
|
||||
"\"contact_info\":{" +
|
||||
"\"contact_name\":\"张三\"," +
|
||||
"\"contact_mobile\":\"18866668888\"," +
|
||||
"\"contact_email\":\"zhangsan@alipy.com\"" +
|
||||
" }," +
|
||||
"\"order_ticket\":\"00ee2d475f374ad097ee0f1ac223fX00\"" +
|
||||
" }");
|
||||
AlipayOpenAgentCreateResponse response = null;
|
||||
try {
|
||||
response = alipayClient.execute(request);
|
||||
} catch (AlipayApiException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
if(response.isSuccess()){
|
||||
System.out.println("调用成功:"+response.getBatchNo());
|
||||
} else {
|
||||
System.out.println("调用失败");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import org.springframework.core.ReactiveAdapterRegistry;
|
||||
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.AlipayClient;
|
||||
import com.alipay.api.DefaultAlipayClient;
|
||||
import com.alipay.api.FileItem;
|
||||
import com.alipay.api.request.AlipayOpenAgentFacetofaceSignRequest;
|
||||
import com.alipay.api.response.AlipayOpenAgentFacetofaceSignResponse;
|
||||
|
||||
public class AliMerchantRegistUtil {
|
||||
|
||||
public static void regist() throws AlipayApiException {
|
||||
|
||||
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "app_id",
|
||||
"your private_key", "json", "GBK", "alipay_public_key", "RSA2");
|
||||
AlipayOpenAgentFacetofaceSignRequest request = new AlipayOpenAgentFacetofaceSignRequest();
|
||||
request.setBatchNo("2017110616474516400082883");
|
||||
request.setMccCode("A_A03_4582");
|
||||
FileItem SpecialLicensePic = new FileItem(
|
||||
"C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
|
||||
request.setSpecialLicensePic(SpecialLicensePic);
|
||||
request.setBusinessLicenseNo("1532501100006302");
|
||||
FileItem BusinessLicensePic = new FileItem(
|
||||
"C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
|
||||
request.setBusinessLicensePic(BusinessLicensePic);
|
||||
FileItem BusinessLicenseAuthPic = new FileItem(
|
||||
"C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
|
||||
request.setBusinessLicenseAuthPic(BusinessLicenseAuthPic);
|
||||
request.setLongTerm(true);
|
||||
request.setDateLimitation("2017-11-11");
|
||||
FileItem ShopScenePic = new FileItem("C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
|
||||
request.setShopScenePic(ShopScenePic);
|
||||
FileItem ShopSignBoardPic = new FileItem(
|
||||
"C:/Downloads/ooopic_963991_7eea1f5426105f9e6069/16365_1271139700.jpg");
|
||||
request.setShopSignBoardPic(ShopSignBoardPic);
|
||||
AlipayOpenAgentFacetofaceSignResponse response = alipayClient.execute(request);
|
||||
if (response.isSuccess()) {
|
||||
System.out.println("调用成功");
|
||||
} else {
|
||||
System.out.println("调用失败");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
/**
|
||||
* @author yuchen
|
||||
*
|
||||
* @Description
|
||||
*/
|
||||
public class AliPayParam {
|
||||
private final static String APP_ID="2019092467786259";
|
||||
private final static String PRI="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQChPC+LD4DlsOeLLaJI6FxKi2RsMmwGmtLXhK70OzkzOC5OP9M5Ev6NECWD3TxJaQESJraZ6KAnM1kjitsq8sEGxyRrXHZcL/a0/t43gQgVzoJ913o3/KIvE7OfoOP4lIDF2+Rffhb4ENP8DmFToKzxmwa2CiNHG4PSxbFNnj80h2JLtm8EdhtZG7WQplqVVoZhme/AF34KDZsDN6Tl3FL9WY/8PMLvlUGufV2dzbjJqgWBqiqLipgaUB6dkzlH36czQY20Fz1e56AALCQY3fNjykRx2mshMJWxO5TVTYCWXXAv00+iCMcCn2E+YsV9f4TiivbMDjDXrf64c1V4fJpxAgMBAAECggEAVpCrreuK9sb96Zl8kcw/EL66EeUYXottO8y+6d2KHlfBdL2LuA7cn/vVSHDVV0yLCKXET+m3YpSM/Sol9W8T94Gfqgygd2pA+HgF8qLSJnMTWGEB+2El6kSXodKN0v5YDOK8QBDAYDsYtTE7S9zuPWFQPxg+TIUXR2hggx29LYPOyao38SMRubT4CrNvc2F5pq6fyiaEBAeVQyORrhyWZpHGjqtCbUViCVRKWnik6u/w1FPgZw28zs8bch980BIOb87DG1mwSrEigHSlP1YXEJl6EPVnz+VHVg021YImD47Dow36UKhp87IPuDSt6XsOBcw9MUAcZM2T4D0j+RhBqQKBgQDj0GGH/0gin43UI2rOzPW/PnGK6ZM1uSoxUhFwGqtiPPOfhmwtTQV2D3dRDmUlojUo/9h9nw7eELAPKLdkAMAEQC/ImBtS/kRfiKEFAOkG34wg+ZOKwPqXl9aBIDj5Do7VJE54ynjc/RvQ0WMveYa5cnqLFh5Cj3sHZLeEWhZEiwKBgQC1Lwg8GyUEK8bDYXqf4viRpVTJS0nJCEQYscxJw65H9pms4Yn5UltMr35GE2GJVcgJt0K4AUpia6wQNEYFchZKepsCt+yF3ooKVt4YROkMEr01r1BBpDNv6Mooc8ClBysGxOePN1kCBAeTyQDDh9e85RVU9M286uWQKP1AlF1wcwKBgBQ7IS4uoX1Rpgq8ynNrCDffl726WHRg6TpQC3RlKesjdo8oJNsxB9cgMHxmRt08tnPZpKQjR/K4kKoH96FN37+A471wpJyOMAw72fDTz93oZE1ZXJzp3lcwCMCW1/hmLpEHFGDtuiYF5D57Gc/RfwFhBTjs0esfStGxRArg5TFZAoGASqLOPJxd+kLiRRgBwJ1qEe1OaQF3qrWZ/6Y2ZmiSgZiHI51hDfCsJYHhfZJ8Smuo1L/GXzBA6Rw7rA0sjw+5OQMamdsUNu0+ZhX0tYClk9CgWt4WLIQsoDwAEvvj7tduFQLF9MwzAU6RpIJXqzRpXansyKtzmRAWcvU/pfu4JhsCgYArmqUktyczmPg0FbtZTzd3e4Faq6S9w4Dn8w6GMRrWScIiTwLLGkAPSX2qgGrem5YEJ7vOVpuj6CfghaEVjhXZWFmYcad4NG524zjDSIL6o4unqukwdABJOgmE71KzWP0OucsT03mRofJBAFV5c4UC5DSQsnwjgdxaRWcUWNbLIw==";
|
||||
private final static String PUB="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4Dlipw4sxS6I9xMbUAiPSQkfD+8JkGAdLQo5+7MpjYAHPBGakMNfOOZgFO6PDeMvnJtRhSrw0fIRK+S382Xx3kg9TXa2NW6J4tJ+limKEv4HKEH3a0ocNdVtjmyl5CoPlhuZVtktuan+3DVMLdHDXABOyRad447DWJkExpKqu79lAcvySzzgRwXPgDnvbOGrAiPIMJ0esp+aw9gGraais+EcYnptMTvbwlFiADcgPEyVf7htIVdxyZtBLiZl1ltYX9W69Fk6prP7/wYccy4uOyu2uhHS0AmMQrbXZg4EmpAUoY7ckUOqplP0+/nJlJLB1jMxkXWzDqnCanU9pEL3sQIDAQAB";
|
||||
private final static String RETURN_URL="http://192.168.0.185:8084/wap/aliPay/returnUrl";
|
||||
public static String getAppId() {
|
||||
return APP_ID;
|
||||
}
|
||||
public static String getPri() {
|
||||
return PRI;
|
||||
}
|
||||
public static String getPub() {
|
||||
return PUB;
|
||||
}
|
||||
public static String getReturnUrl() {
|
||||
return RETURN_URL;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.AlipayClient;
|
||||
import com.alipay.api.DefaultAlipayClient;
|
||||
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
|
||||
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
*
|
||||
*@description:支付宝工具类
|
||||
*@author: bzg
|
||||
*@time: 2021/10/8 17:41
|
||||
*/
|
||||
|
||||
public class AliUtil {
|
||||
|
||||
|
||||
// public static Map<String, Object> getAliUserId(String auth_code,String priKey,String pubKey,String appId) {
|
||||
// Map<String, Object> result = new HashMap<>(2);
|
||||
// AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId,
|
||||
// priKey, "json", "GBK", pubKey, "RSA2");
|
||||
// AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
|
||||
// request.setCode(auth_code);
|
||||
// request.setGrantType("authorization_code");
|
||||
// try {
|
||||
// AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
|
||||
// result.put("aliUserId", oauthTokenResponse.getUserId());
|
||||
// result.put("accessToken", oauthTokenResponse.getAccessToken());
|
||||
// } catch (AlipayApiException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// return result;
|
||||
// }
|
||||
|
||||
public static AlipaySystemOauthTokenResponse getAliUserIdV2(String auth_code,String priKey,String pubKey,String appId) {
|
||||
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId,
|
||||
priKey, "json", "GBK", pubKey, "RSA2");
|
||||
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
|
||||
request.setCode(auth_code);
|
||||
request.setGrantType("authorization_code");
|
||||
try {
|
||||
AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
|
||||
if(!response.isSuccess()){
|
||||
MsgException.throwException("支付宝授权失败");
|
||||
}
|
||||
return response;
|
||||
} catch (AlipayApiException e) {
|
||||
e.printStackTrace();
|
||||
MsgException.throwException("支付宝授权异常");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
/**
|
||||
* @author DJH
|
||||
*/
|
||||
public class AreaUtils {
|
||||
|
||||
/**
|
||||
* 获取地区的编码数组
|
||||
* @return 省市县(区)的编码数组
|
||||
*/
|
||||
public static String[] distinctArrayFromAreaCode(String area) {
|
||||
String[] result = new String[3];
|
||||
result[2] = area;
|
||||
// 前4位即为市的编码
|
||||
|
||||
if (area.length() > 6) {
|
||||
// 某些特殊区域市编码长度为4位
|
||||
result[1] = area.substring(0, 6);
|
||||
} else {
|
||||
result[1] = area.substring(0, 4) + "00";
|
||||
}
|
||||
// 前2位即为省的编码
|
||||
result[0] = area.substring(0, 2) + "0000";
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
public class AuditUtils {
|
||||
|
||||
/**
|
||||
* 银盛商户类型转换
|
||||
* @param merchantType 商户类型
|
||||
* @return 通道商户类型
|
||||
*/
|
||||
public static String getYsMerchantType(String merchantType) {
|
||||
if ("1".equals(merchantType)) {
|
||||
return "3";
|
||||
}
|
||||
|
||||
//
|
||||
if ("2".equals(merchantType)) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
return "1";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class Base64DecodedMultipartFile implements MultipartFile {
|
||||
|
||||
private final byte[] imgContent;
|
||||
private final String header;
|
||||
|
||||
public Base64DecodedMultipartFile(byte[] imgContent, String header) {
|
||||
this.imgContent = imgContent;
|
||||
this.header = header.split(";")[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
// TODO - implementation depends on your requirements
|
||||
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getOriginalFilename() {
|
||||
// TODO - implementation depends on your requirements
|
||||
return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1];
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentType() {
|
||||
// TODO - implementation depends on your requirements
|
||||
return header.split(":")[1];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return imgContent == null || imgContent.length == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize() {
|
||||
return imgContent.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getBytes() throws IOException {
|
||||
return imgContent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(imgContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transferTo(File dest) throws IOException, IllegalStateException {
|
||||
new FileOutputStream(dest).write(imgContent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.coobird.thumbnailator.Thumbnails;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
@Slf4j
|
||||
public class Base64Util {
|
||||
|
||||
private static final Integer KB = 1024;
|
||||
|
||||
private static final char last2byte = (char) Integer.parseInt("00000011", 2);
|
||||
private static final char last4byte = (char) Integer.parseInt("00001111", 2);
|
||||
private static final char last6byte = (char) Integer.parseInt("00111111", 2);
|
||||
private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
|
||||
private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
|
||||
private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
|
||||
private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
|
||||
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
|
||||
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
|
||||
'2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
|
||||
|
||||
/**
|
||||
* 将文件转成base64 字符串
|
||||
*
|
||||
* @return *
|
||||
* @throws Exception
|
||||
*/
|
||||
|
||||
public static String encodeBase64File(String path) throws Exception {
|
||||
File file = new File(path);
|
||||
FileInputStream inputFile = new FileInputStream(file);
|
||||
byte[] buffer = new byte[(int) file.length()];
|
||||
inputFile.read(buffer);
|
||||
inputFile.close();
|
||||
return Base64.getEncoder().encodeToString(buffer);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* base64转inputStream
|
||||
*
|
||||
* @param base64string
|
||||
* @return
|
||||
*/
|
||||
public static InputStream base64ToInputStream(String base64string) {
|
||||
ByteArrayInputStream stream = null;
|
||||
try {
|
||||
byte[] bytes1 = Base64.getDecoder().decode(base64string);
|
||||
stream = new ByteArrayInputStream(bytes1);
|
||||
} catch (Exception e) {
|
||||
// TODO: handle exception
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将base64字符解码保存文件
|
||||
*
|
||||
* @param base64Code
|
||||
* @param targetPath
|
||||
* @throws Exception
|
||||
*/
|
||||
|
||||
public static void decoderBase64File(String base64Code, String targetPath) throws Exception {
|
||||
byte[] buffer = Base64.getDecoder().decode(base64Code);
|
||||
FileOutputStream out = new FileOutputStream(targetPath);
|
||||
out.write(buffer);
|
||||
out.close();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 将base64字符保存文本文件
|
||||
*
|
||||
* @param base64Code
|
||||
* @param targetPath
|
||||
* @throws Exception
|
||||
*/
|
||||
|
||||
public static void toFile(String base64Code, String targetPath) throws Exception {
|
||||
|
||||
byte[] buffer = base64Code.getBytes();
|
||||
FileOutputStream out = new FileOutputStream(targetPath);
|
||||
out.write(buffer);
|
||||
out.close();
|
||||
}
|
||||
|
||||
public static MultipartFile base64ToMultipart(String base64) {
|
||||
String[] baseStrs = base64.split(",");
|
||||
|
||||
byte[] b = Base64.getDecoder().decode(baseStrs[1]);
|
||||
|
||||
for (int i = 0; i < b.length; ++i) {
|
||||
if (b[i] < 0) {
|
||||
b[i] += 256;
|
||||
}
|
||||
}
|
||||
return new Base64DecodedMultipartFile(b, baseStrs[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param origPicContent
|
||||
* @param desFileSize 期望文件大小,单位KB
|
||||
* @return
|
||||
*/
|
||||
public static String compressPic(String origPicContent, Integer desFileSize) {
|
||||
ByteArrayInputStream in = null;
|
||||
ByteArrayOutputStream out = null;
|
||||
try {
|
||||
byte[] bytes = Base64.getDecoder().decode(origPicContent);
|
||||
while (bytes.length > desFileSize * KB) {
|
||||
in = new ByteArrayInputStream(bytes);
|
||||
out = new ByteArrayOutputStream();
|
||||
Thumbnails.of(in)
|
||||
.scale(0.9f)
|
||||
.outputQuality(1)
|
||||
.toOutputStream(out);
|
||||
bytes = out.toByteArray();
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(bytes).replaceAll("[\r\n]","");
|
||||
} catch (IOException e) {
|
||||
log.error ("decode buffer fail, message:{}", e.getMessage (), e);
|
||||
} finally {
|
||||
if (in != null) {
|
||||
try {
|
||||
in.close ();
|
||||
} catch (IOException e) {
|
||||
log.error ("ByteArrayInputStream close fail, message:{}", e.getMessage (), e);
|
||||
}
|
||||
}
|
||||
if (out != null) {
|
||||
try {
|
||||
out.close ();
|
||||
} catch (IOException e) {
|
||||
log.error ("ByteArrayOutputStream close fail, message:{}", e.getMessage (), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return origPicContent;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串 base64 编码
|
||||
* @param source
|
||||
* @return
|
||||
*/
|
||||
public static String encode(String source){
|
||||
return Base64.getEncoder().encodeToString(source.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串 base64 解码
|
||||
* @param source
|
||||
* @return
|
||||
*/
|
||||
public static String decode(String source){
|
||||
try {
|
||||
return new String(Base64.getDecoder().decode(source),"UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 对apche BeanUtils 进行封装,将强制性捕获异常转化成运行时异常
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class BeanUtils {
|
||||
|
||||
private static void handleReflectionException(Exception e) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 克隆对象
|
||||
*
|
||||
* @param bean
|
||||
* @return
|
||||
*/
|
||||
public static Object cloneBean(Object bean) {
|
||||
try {
|
||||
return org.apache.commons.beanutils.BeanUtils.cloneBean(bean);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param destClass
|
||||
* @param orig
|
||||
* @return
|
||||
*/
|
||||
public static Object copyProperties(Class destClass, Object orig) {
|
||||
try {
|
||||
Object target = destClass.newInstance();
|
||||
copyProperties((Object) target, orig);
|
||||
return target;
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void copyProperties(Object dest, Object orig) {
|
||||
try {
|
||||
org.apache.commons.beanutils.BeanUtils.copyProperties(dest.getClass(), orig);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void copyProperty(Object bean, String name, Object value) {
|
||||
try {
|
||||
org.apache.commons.beanutils.BeanUtils.copyProperty(bean, name, value);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Map describe(Object bean) {
|
||||
try {
|
||||
return org.apache.commons.beanutils.BeanUtils.describe(bean);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String[] getArrayProperty(Object bean, String name) {
|
||||
try {
|
||||
return org.apache.commons.beanutils.BeanUtils.getArrayProperty(bean, name);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getIndexedProperty(Object bean, String name, int index) {
|
||||
try {
|
||||
return org.apache.commons.beanutils.BeanUtils.getIndexedProperty(bean, name, index);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getIndexedProperty(Object bean, String name) {
|
||||
try {
|
||||
return org.apache.commons.beanutils.BeanUtils.getIndexedProperty(bean, name);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getMappedProperty(Object bean, String name, String key) {
|
||||
try {
|
||||
return org.apache.commons.beanutils.BeanUtils.getMappedProperty(bean, name, key);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getMappedProperty(Object bean, String name) {
|
||||
try {
|
||||
return org.apache.commons.beanutils.BeanUtils.getMappedProperty(bean, name);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getNestedProperty(Object bean, String name) {
|
||||
try {
|
||||
return org.apache.commons.beanutils.BeanUtils.getNestedProperty(bean, name);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getProperty(Object bean, String name) {
|
||||
try {
|
||||
return org.apache.commons.beanutils.BeanUtils.getProperty(bean, name);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getSimpleProperty(Object bean, String name) {
|
||||
try {
|
||||
return org.apache.commons.beanutils.BeanUtils.getSimpleProperty(bean, name);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void populate(Object bean, Map properties) {
|
||||
try {
|
||||
org.apache.commons.beanutils.BeanUtils.populate(bean, properties);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void setProperty(Object bean, String name, Object value) {
|
||||
try {
|
||||
org.apache.commons.beanutils.BeanUtils.setProperty(bean, name, value);
|
||||
} catch (Exception e) {
|
||||
handleReflectionException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将map转换成对应的javabean
|
||||
*
|
||||
*/
|
||||
public static Object convertMap(Class type, Map map) throws Exception {
|
||||
BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
|
||||
Object obj = type.newInstance(); // 创建 JavaBean 对象
|
||||
|
||||
// 给 JavaBean 对象的属性赋值
|
||||
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
|
||||
for (int i = 0; i < propertyDescriptors.length; i++) {
|
||||
PropertyDescriptor descriptor = propertyDescriptors[i];
|
||||
String propertyName = descriptor.getName();
|
||||
if (map.containsKey(propertyName)) {
|
||||
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
|
||||
Object value = map.get(propertyName);
|
||||
|
||||
Object[] args = new Object[1];
|
||||
args[0] = value;
|
||||
|
||||
descriptor.getWriteMethod().invoke(obj, args);
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将javabean转换成map
|
||||
*/
|
||||
public static Map convertBean(Object bean) throws Exception {
|
||||
Class type = bean.getClass();
|
||||
Map returnMap = new HashMap();
|
||||
BeanInfo beanInfo = Introspector.getBeanInfo(type);
|
||||
|
||||
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
|
||||
for (int i = 0; i < propertyDescriptors.length; i++) {
|
||||
PropertyDescriptor descriptor = propertyDescriptors[i];
|
||||
String propertyName = descriptor.getName();
|
||||
if (!propertyName.equals("class")) {
|
||||
Method readMethod = descriptor.getReadMethod();
|
||||
Object result = readMethod.invoke(bean, new Object[0]);
|
||||
if (result != null) {
|
||||
returnMap.put(propertyName, result);
|
||||
} else {
|
||||
returnMap.put(propertyName, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
return returnMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环遍历克隆Map对象 值对象为浅clone
|
||||
*
|
||||
* @param src
|
||||
* @return
|
||||
*/
|
||||
public static Map<String, Object> cloneMap(Map<String, Object> src) {
|
||||
Map<String, Object> des = new HashMap<String, Object>();
|
||||
for (Iterator<String> it = src.keySet().iterator(); it.hasNext();) {
|
||||
String key = it.next();
|
||||
Object value = src.get(key);
|
||||
des.put(key, value);
|
||||
}
|
||||
return des;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
|
||||
/**
|
||||
* @author SSS
|
||||
*/
|
||||
public class ByteArrayImg extends ByteArrayResource {
|
||||
|
||||
private String picName;
|
||||
|
||||
public ByteArrayImg(byte[] byteArray, String picName) {
|
||||
super(byteArray);
|
||||
this.picName = picName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getFilename() {
|
||||
return picName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.dom4j.Document;
|
||||
import org.dom4j.DocumentHelper;
|
||||
import org.dom4j.Element;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
public class CertFicatesUtils {
|
||||
|
||||
//接口请求地址
|
||||
private static String requestUrl = "https://api.mch.weixin.qq.com/risk/getcertficates";
|
||||
//服务商号
|
||||
private static String mch_id = "1551169371";
|
||||
|
||||
private static String payKey = "7F05NZBTJ3XNDK5HLSDC3H25ZXOQKDHT";
|
||||
|
||||
|
||||
//获取商户平台证书序列号
|
||||
public static String getCertFicates() {
|
||||
|
||||
// 初始化一个HttpClient
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
// Post请求
|
||||
HttpPost httpPost = new HttpPost(requestUrl);
|
||||
/**
|
||||
* 这边需要您提供微信分配的商户号跟API密钥
|
||||
*/
|
||||
Map<String, String> param = new HashMap<>(4);
|
||||
param.put("mch_id", mch_id);
|
||||
param.put("nonce_str", UUID.randomUUID().toString().replace("-", ""));
|
||||
// 暂只支持HMAC-SHA256 加密
|
||||
param.put("sign_type", "HMAC-SHA256");
|
||||
// 对你的参数进行加密处理
|
||||
String sign = WechatSignUtil.sha256Sign(param, payKey);
|
||||
param.put("sign", sign);
|
||||
httpPost.setEntity(new StringEntity(map2Xml(param), "UTF-8"));
|
||||
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_XML.getMimeType());
|
||||
try {
|
||||
HttpResponse httpResponse = httpClient.execute(httpPost);
|
||||
|
||||
if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
|
||||
String responseEntity = EntityUtils.toString(httpResponse.getEntity());
|
||||
System.out.println(responseEntity);
|
||||
Document document = DocumentHelper.parseText(responseEntity);
|
||||
Element root = document.getRootElement();
|
||||
if ("SUCCESS".equalsIgnoreCase(root.element("return_code").getTextTrim())&& "SUCCESS".equalsIgnoreCase(root.element("result_code").getTextTrim())) {
|
||||
|
||||
|
||||
//System.out.println(root.element("certificates").getTextTrim());
|
||||
JSONObject data = JSONObject.parseObject(root.element("certificates").getTextTrim());
|
||||
//System.out.println(data.getString("data"));
|
||||
JSONObject senconds = JSONObject.parseObject(data.getString("data").replace("[", "").replace("]", ""));
|
||||
JSONObject encrypt_certificate = JSONObject.parseObject(senconds.getString("encrypt_certificate"));
|
||||
|
||||
|
||||
|
||||
return //senconds.getString("serial_no");
|
||||
//root.element("serial_no").getTextTrim();
|
||||
decryptCertSN(encrypt_certificate.getString("associated_data"),encrypt_certificate.getString("nonce"),encrypt_certificate.getString("ciphertext"),"VVGT43fzo4ICUGcH5jJ38VBGXwq8Kmja");
|
||||
//document.selectSingleNode("//certificates").getStringValue();
|
||||
}else {
|
||||
System.out.println("请求平台证书序号响应错误!");
|
||||
}
|
||||
// log.error("请求平台证书序号响应异常 {}",
|
||||
// document.selectSingleNode("//return_msg").getStringValue());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
// log.error("执行httpclient请求平台证书序号错误 {}", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* map对象转xml
|
||||
*
|
||||
* @param map
|
||||
* @return
|
||||
*/
|
||||
private static String map2Xml(Map<String, String> map) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
result.append("<xml>");
|
||||
if (map != null && map.keySet().size() > 0) {
|
||||
map.forEach((key, value) -> {
|
||||
result.append("<" + key + "><![CDATA[");
|
||||
result.append(value);
|
||||
result.append("]]></" + key + ">");
|
||||
});
|
||||
}
|
||||
result.append("</xml>");
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
|
||||
//解密平台证书
|
||||
private static String decryptCertSN(String associatedData, String nonce, String cipherText, String apiv3Key) throws Exception{
|
||||
final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE");
|
||||
SecretKeySpec key = new SecretKeySpec(apiv3Key.getBytes(), "AES");
|
||||
GCMParameterSpec spec = new GCMParameterSpec(128, nonce.getBytes());
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, spec);
|
||||
cipher.updateAAD(associatedData.getBytes());
|
||||
return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
|
||||
/**
|
||||
* @author DJH
|
||||
*/
|
||||
public class CheckUtils {
|
||||
|
||||
/**
|
||||
* 判断值是否在指定范围内
|
||||
* @param target 目标值
|
||||
* @param max 最大
|
||||
* @param min 最小
|
||||
* @param msg 抛出的异常信息
|
||||
*/
|
||||
public static void limit(int target, int min, int max, String msg) {
|
||||
if (target < min || target > max) {
|
||||
throw new MsgException(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
|
||||
import cn.pluss.platform.api.Result;
|
||||
|
||||
public class ComUtil {
|
||||
private final static Logger logger = LoggerFactory.getLogger(ComUtil.class);
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static boolean isEmpty(Object aObj) {
|
||||
if (aObj instanceof String) {
|
||||
return isEmpty((String) aObj);
|
||||
} else if (aObj instanceof Long) {
|
||||
return isEmpty((Long) aObj);
|
||||
} else if (aObj instanceof java.util.Date) {
|
||||
return isEmpty((java.util.Date) aObj);
|
||||
} else if (aObj instanceof Collection) {
|
||||
return isEmpty((Collection) aObj);
|
||||
} else if (aObj instanceof Map) {
|
||||
return isEmpty((Map) aObj);
|
||||
} else if (aObj != null && aObj.getClass().isArray()) {
|
||||
return isEmptyArray(aObj);
|
||||
} else {
|
||||
return isNull(aObj);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isEmptyArray(Object array) {
|
||||
int length = 0;
|
||||
if (array instanceof int[]) {
|
||||
length = ((int[]) array).length;
|
||||
} else if (array instanceof byte[]) {
|
||||
length = ((byte[]) array).length;
|
||||
} else if (array instanceof short[]) {
|
||||
length = ((short[]) array).length;
|
||||
} else if (array instanceof char[]) {
|
||||
length = ((char[]) array).length;
|
||||
} else if (array instanceof float[]) {
|
||||
length = ((float[]) array).length;
|
||||
} else if (array instanceof double[]) {
|
||||
length = ((double[]) array).length;
|
||||
} else if (array instanceof long[]) {
|
||||
length = ((long[]) array).length;
|
||||
} else if (array instanceof boolean[]) {
|
||||
length = ((boolean[]) array).length;
|
||||
} else {
|
||||
length = ((Object[]) array).length;
|
||||
}
|
||||
if (length == 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isEmpty(java.util.Date aDate) {
|
||||
if (aDate == null) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isEmpty(Long aLong) {
|
||||
if (aLong == null) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static boolean isEmpty(Map m) {
|
||||
if (m == null || m.size() == 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static boolean isEmpty(Collection c) {
|
||||
if (c == null || c.size() == 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean isEmpty(String aStr) {
|
||||
if (aStr == null || aStr.trim().isEmpty()) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String trim(String aStr) {
|
||||
if (aStr == null) {
|
||||
return "";
|
||||
} else {
|
||||
return aStr.trim();
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isNull(Object oStr) {
|
||||
if (oStr == null) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean equals(String str1, String str2) {
|
||||
return str1 != null ? str1.equals(str2) : str2 == null;
|
||||
}
|
||||
|
||||
public static boolean equals(Long L1, Long L2) {
|
||||
return L1 != null ? L1.equals(L2) : L2 == null;
|
||||
}
|
||||
|
||||
public static boolean equals(Object obj1, Object obj2) {
|
||||
boolean result;
|
||||
if (obj1 != null) {
|
||||
result = obj1.equals(obj2);
|
||||
} else {
|
||||
result = (obj2 == null);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static boolean equalsIgnoreCase(String str1, String str2) {
|
||||
return str1 != null ? str1.equalsIgnoreCase(str2) : str2 == null;
|
||||
}
|
||||
|
||||
public static String getIpAddress(HttpServletRequest request) {
|
||||
String ip = request.getHeader("x-forwarded-for");
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
// 如果是多级代理,那么取第一个ip为客户端ip
|
||||
if (ip != null && ip.indexOf(",") != -1) {
|
||||
ip = ip.substring(0, ip.indexOf(",")).trim();
|
||||
}
|
||||
|
||||
return ip;
|
||||
}
|
||||
|
||||
public static void responseResult(HttpServletResponse response, Result result) {
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
|
||||
response.setStatus(200);
|
||||
try {
|
||||
response.getWriter().write(JSON.toJSONString(result));
|
||||
} catch (IOException ex) {
|
||||
logger.error(ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* TODO
|
||||
* cookie 工具类
|
||||
* @author crystal
|
||||
* @date 2022/6/24 17:29
|
||||
*/
|
||||
public class CookieUtils {
|
||||
|
||||
|
||||
private static final String PREFIX = "SYB-USERID-OPEND-";
|
||||
/**
|
||||
* 获取value
|
||||
* @param request
|
||||
* @param key
|
||||
* @param isBase64Flag 是否需要转码
|
||||
* @return
|
||||
*/
|
||||
public static String getCookieValue(HttpServletRequest request,String key,boolean isBase64Flag){
|
||||
String value = null;
|
||||
Cookie[] cookies = request.getCookies();
|
||||
key = PREFIX + key;
|
||||
if (cookies != null && cookies.length > 0) {
|
||||
for (Cookie c : cookies) {
|
||||
if (key.equals(c.getName())) {
|
||||
value = c.getValue();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(isBase64Flag && StringUtil.isNotEmpty(value)){
|
||||
value = Base64Util.decode(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static void setCookie(HttpServletResponse response,String key, String value,boolean isBase64Flag){
|
||||
key = PREFIX + key;
|
||||
if(isBase64Flag){
|
||||
value = Base64Util.encode(value);
|
||||
}
|
||||
Cookie cookie = new Cookie(key, value);
|
||||
cookie.setMaxAge(-1);
|
||||
response.addCookie(cookie);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.enums.SqlKeyword;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class CustomAbstractWrapper<T> extends QueryWrapper<T> {
|
||||
|
||||
public CustomAbstractWrapper() {
|
||||
}
|
||||
|
||||
public CustomAbstractWrapper(T entity) {
|
||||
super(entity);
|
||||
}
|
||||
|
||||
public CustomAbstractWrapper(T entity, String... columns) {
|
||||
super(entity, columns);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected QueryWrapper<T> addCondition(boolean condition, String column, SqlKeyword sqlKeyword, Object val) {
|
||||
if (Objects.isNull(val) || "".equals(val)) {
|
||||
condition = false;
|
||||
}
|
||||
return super.addCondition(condition, column, sqlKeyword, val);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Djh
|
||||
* @param <T> 类型
|
||||
* 便于从数据中取出需要的数据
|
||||
*/
|
||||
@Data
|
||||
@RequiredArgsConstructor
|
||||
public class DataFactory<T> {
|
||||
|
||||
private List<T> srcList;
|
||||
|
||||
public T get(T condition) {
|
||||
if (srcList == null || srcList.size() == 0) {
|
||||
srcList = configuration.getData();
|
||||
}
|
||||
|
||||
for (T item: srcList) {
|
||||
if (configuration.compare(item, condition)) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private final Configuration<T> configuration;
|
||||
|
||||
|
||||
public interface Configuration<T> {
|
||||
|
||||
/**
|
||||
* 获取数据
|
||||
* @return
|
||||
*/
|
||||
List<T> getData();
|
||||
|
||||
/**
|
||||
* 数据比较
|
||||
* @param src
|
||||
* @param tar
|
||||
* @return
|
||||
*/
|
||||
boolean compare(T src, T tar);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,654 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @author hkj
|
||||
* @category @see 日期工具
|
||||
*/
|
||||
public class DateUtils {
|
||||
|
||||
public final static String DEFAULT_FORMAT = "yyyy-MM-dd";
|
||||
|
||||
public static String formatDateDefault(Date date, String pattern) {
|
||||
if (date == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
try {
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
|
||||
return formatter.format(date);
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据给定的格式化参数,将字符串转换为日期
|
||||
*
|
||||
* @param dateString
|
||||
* @param dateFormat
|
||||
* @return java.util.Date
|
||||
*/
|
||||
public static java.util.Date parse(String dateString, String dateFormat) {
|
||||
if ("".equals(dateString.trim()) || dateString == null) {
|
||||
return null;
|
||||
}
|
||||
DateFormat sdf = new SimpleDateFormat(dateFormat);
|
||||
Date date = null;
|
||||
try {
|
||||
date = sdf.parse(dateString);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 默认将字符串转换为日期,格式(yyyy-MM-dd)
|
||||
*
|
||||
* @param dateString
|
||||
* @return
|
||||
*/
|
||||
public static java.util.Date parse(String dateString) {
|
||||
return parse(dateString, DEFAULT_FORMAT);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据给定的格式化参数,将日期转换为字符串
|
||||
*
|
||||
* @param date
|
||||
* @param dateFormat
|
||||
* @return String
|
||||
*/
|
||||
public static String toString(java.util.Date date, String dateFormat) {
|
||||
if ("".equals(date) || date == null) {
|
||||
return "bug: date is null";
|
||||
}
|
||||
DateFormat sdf = new SimpleDateFormat(dateFormat);
|
||||
String str = sdf.format(date);
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认将日期转换为字符串,格式(yyyy-MM-dd)
|
||||
*
|
||||
* @param date
|
||||
* @return String
|
||||
*/
|
||||
public static String toString(java.util.Date date) {
|
||||
return toString(date, DEFAULT_FORMAT);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将日期转换为长整型?
|
||||
*
|
||||
* @param date
|
||||
* @return long
|
||||
*/
|
||||
public static long toLong(java.util.Date date) {
|
||||
if (date == null) {
|
||||
return 0;
|
||||
}
|
||||
long d = date.getTime();
|
||||
|
||||
return d;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将长整型转换为日期对象
|
||||
*
|
||||
* @param time
|
||||
* @return date
|
||||
*/
|
||||
public static java.util.Date toDate(long time) {
|
||||
if ("".equals(time)) {
|
||||
return new Date();
|
||||
}
|
||||
Date date = new Date(time);
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得系统当前时间
|
||||
*
|
||||
* @return java.util.Date
|
||||
*/
|
||||
public static String currentStringDate() {
|
||||
Date date = new Date();
|
||||
|
||||
return toString(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得系统当前时间(按用户自己格式)
|
||||
*
|
||||
* @return java.util.Date
|
||||
*/
|
||||
public static String currentYourDate(String formate) {
|
||||
Date date = new Date();
|
||||
return toString(date, formate);
|
||||
}
|
||||
|
||||
public static String currentYourDate() {
|
||||
Date date = new Date();
|
||||
return toString(date, DEFAULT_FORMAT);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得系统当前时间
|
||||
*
|
||||
* @return java.util.Date
|
||||
*/
|
||||
public static java.util.Date currentDate() {
|
||||
Date date = new Date();
|
||||
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据日历的规则,为给定的日历字段添加或减去指定的时间<E697B6>?
|
||||
*
|
||||
* @param field 指定的日历字段
|
||||
* @param date 需要操作的日期对象
|
||||
* @param value 更改的时间值
|
||||
* @return java.util.Date
|
||||
*/
|
||||
public static Date add(int field, Date date, int value) {
|
||||
Calendar ca = Calendar.getInstance();
|
||||
ca.setTime(date);
|
||||
ca.add(field, value);
|
||||
Date newDate = ca.getTime();
|
||||
|
||||
return newDate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回给定日历字段的值
|
||||
*
|
||||
* @param field 指定的日历字段
|
||||
* @param date 给定的日期对象
|
||||
* @return java.util.Date
|
||||
*/
|
||||
public static int get(int field, Date date) {
|
||||
Calendar ca = Calendar.getInstance();
|
||||
ca.setTime(date);
|
||||
int value = ca.get(field);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回前N个月的日期值
|
||||
*
|
||||
* @param month
|
||||
* @return
|
||||
*/
|
||||
public static Date getLastMonth(String month) {
|
||||
Calendar ca = Calendar.getInstance();
|
||||
int m = 0;
|
||||
try {
|
||||
m = Integer.parseInt(month);
|
||||
} catch (NumberFormatException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
ca.add(Calendar.MONTH, -m);
|
||||
return ca.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回当前日期的前一天
|
||||
*
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static String getPreDate(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.add(Calendar.DAY_OF_MONTH, -1);
|
||||
date = calendar.getTime();
|
||||
return toString(date, DEFAULT_FORMAT);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证字符串是否匹配日期
|
||||
*/
|
||||
public static boolean isDate(String str, String formate) {
|
||||
try {
|
||||
DateFormat sdf = new SimpleDateFormat(formate);
|
||||
sdf.parse(str);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取偏移日期
|
||||
*
|
||||
* @param offset
|
||||
* @return
|
||||
*/
|
||||
public static Date getOffsetDate(int offset) {
|
||||
|
||||
SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Date beginDate = new Date();
|
||||
Calendar date = Calendar.getInstance();
|
||||
date.setTime(beginDate);
|
||||
date.set(Calendar.DATE, date.get(Calendar.DATE) + offset);
|
||||
Date endDate = null;
|
||||
try {
|
||||
endDate = dft.parse(dft.format(date.getTime()));
|
||||
} catch (ParseException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return endDate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回日时分秒
|
||||
*
|
||||
* @param second
|
||||
* @return
|
||||
*/
|
||||
public static String secondToTime(long second) {
|
||||
long days = second / 86400;// 转换天数
|
||||
second = second % 86400;// 剩余秒数
|
||||
long hours = second / 3600;// 转换小时数
|
||||
second = second % 3600;// 剩余秒数
|
||||
long minutes = second / 60;// 转换分钟
|
||||
second = second % 60;// 剩余秒数
|
||||
String min = minutes + "";
|
||||
if (minutes < 10) {
|
||||
min = "0" + minutes;
|
||||
}
|
||||
String sec = second + "";
|
||||
if (second < 10) {
|
||||
sec = "0" + second;
|
||||
}
|
||||
|
||||
if (0 < days) {
|
||||
return days + "天," + hours + "小时," + minutes + "分," + second + "秒";
|
||||
} else {
|
||||
return hours + ":" + min + ":" + sec;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取当天的开始时间
|
||||
public static Date getDayBegin() {
|
||||
Calendar cal = new GregorianCalendar();
|
||||
cal.set(Calendar.HOUR_OF_DAY, 0);
|
||||
cal.set(Calendar.MINUTE, 0);
|
||||
cal.set(Calendar.SECOND, 0);
|
||||
cal.set(Calendar.MILLISECOND, 0);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
// 获取当天的结束时间
|
||||
public static Date getDayEnd() {
|
||||
Calendar cal = new GregorianCalendar();
|
||||
cal.set(Calendar.HOUR_OF_DAY, 23);
|
||||
cal.set(Calendar.MINUTE, 59);
|
||||
cal.set(Calendar.SECOND, 59);
|
||||
cal.set(Calendar.MILLISECOND, 999);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
// 获取昨天的开始时间
|
||||
public static Date getBeginDayOfYesterday() {
|
||||
Calendar cal = new GregorianCalendar();
|
||||
cal.setTime(getDayBegin());
|
||||
cal.add(Calendar.DAY_OF_MONTH, -1);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
// 获取昨天的结束时间
|
||||
public static Date getEndDayOfYesterDay() {
|
||||
Calendar cal = new GregorianCalendar();
|
||||
cal.setTime(getDayEnd());
|
||||
cal.add(Calendar.DAY_OF_MONTH, -1);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
// 获取明天的开始时间
|
||||
public static Date getBeginDayOfTomorrow() {
|
||||
Calendar cal = new GregorianCalendar();
|
||||
cal.setTime(getDayBegin());
|
||||
cal.add(Calendar.DAY_OF_MONTH, 1);
|
||||
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
// 获取明天的结束时间
|
||||
public static Date getEndDayOfTomorrow() {
|
||||
Calendar cal = new GregorianCalendar();
|
||||
cal.setTime(getDayEnd());
|
||||
cal.add(Calendar.DAY_OF_MONTH, 1);
|
||||
return cal.getTime();
|
||||
}
|
||||
|
||||
// 获取本周的开始时间
|
||||
public static Date getBeginDayOfWeek() {
|
||||
Date date = new Date();
|
||||
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
|
||||
if (dayofweek == 1) {
|
||||
dayofweek += 7;
|
||||
}
|
||||
cal.add(Calendar.DATE, 2 - dayofweek);
|
||||
return getDayStartTime(cal.getTime());
|
||||
}
|
||||
|
||||
// 获取本周的结束时间
|
||||
public static Date getEndDayOfWeek() {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(getBeginDayOfWeek());
|
||||
cal.add(Calendar.DAY_OF_WEEK, 6);
|
||||
Date weekEndSta = cal.getTime();
|
||||
return getDayEndTime(weekEndSta);
|
||||
}
|
||||
|
||||
// 获取本月的开始时间
|
||||
public static Date getBeginDayOfMonth() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(getNowYear(), getNowMonth() - 1, 1);
|
||||
return getDayStartTime(calendar.getTime());
|
||||
}
|
||||
|
||||
// 获取本月的结束时间
|
||||
public static Date getEndDayOfMonth() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(getNowYear(), getNowMonth() - 1, 1);
|
||||
int day = calendar.getActualMaximum(5);
|
||||
calendar.set(getNowYear(), getNowMonth() - 1, day);
|
||||
return getDayEndTime(calendar.getTime());
|
||||
}
|
||||
|
||||
// 获取本年的开始时间
|
||||
public static Date getBeginDayOfYear() {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.set(Calendar.YEAR, getNowYear());
|
||||
// cal.set
|
||||
cal.set(Calendar.MONTH, Calendar.JANUARY);
|
||||
cal.set(Calendar.DATE, 1);
|
||||
|
||||
return getDayStartTime(cal.getTime());
|
||||
}
|
||||
|
||||
// 获取本年的结束时间
|
||||
public static Date getEndDayOfYear() {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.set(Calendar.YEAR, getNowYear());
|
||||
cal.set(Calendar.MONTH, Calendar.DECEMBER);
|
||||
cal.set(Calendar.DATE, 31);
|
||||
return getDayEndTime(cal.getTime());
|
||||
}
|
||||
|
||||
// 获取某个日期的开始时间
|
||||
public static Timestamp getDayStartTime(Date d) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
if (null != d) {
|
||||
calendar.setTime(d);
|
||||
}
|
||||
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0,
|
||||
0, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
return new Timestamp(calendar.getTimeInMillis());
|
||||
}
|
||||
|
||||
// 获取某个日期的结束时间
|
||||
public static Timestamp getDayEndTime(Date d) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
if (null != d) {
|
||||
calendar.setTime(d);
|
||||
}
|
||||
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23,
|
||||
59, 59);
|
||||
calendar.set(Calendar.MILLISECOND, 999);
|
||||
return new Timestamp(calendar.getTimeInMillis());
|
||||
}
|
||||
|
||||
// 获取今年是哪一年
|
||||
public static Integer getNowYear() {
|
||||
Date date = new Date();
|
||||
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
|
||||
gc.setTime(date);
|
||||
return Integer.valueOf(gc.get(1));
|
||||
}
|
||||
|
||||
// 获取本月是哪一月
|
||||
public static int getNowMonth() {
|
||||
Date date = new Date();
|
||||
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
|
||||
gc.setTime(date);
|
||||
return gc.get(2) + 1;
|
||||
}
|
||||
|
||||
// 获取上一月的开始时间
|
||||
public static Date getBeginDayOfPreMonth() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(getNowYear(), getNowMonth() - 2, 1);
|
||||
return getDayStartTime(calendar.getTime());
|
||||
}
|
||||
|
||||
// 获取某个月的开始时间
|
||||
public static String getBeginMonth(int i) {
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar cal_1 = Calendar.getInstance();// 获取当前日期
|
||||
cal_1.add(Calendar.MONTH, i);
|
||||
cal_1.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
|
||||
String firstDay = format.format(cal_1.getTime()) + " 00:00:00";
|
||||
return firstDay;
|
||||
}
|
||||
|
||||
// 获取某个月的结束时间
|
||||
public static String getEndMonth(int i) {
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar cale = Calendar.getInstance();
|
||||
cale.add(Calendar.MONTH, i + 1);// 设置为1号,当前日期既为本月第一天
|
||||
cale.set(Calendar.DAY_OF_MONTH, 0);// 设置为1号,当前日期既为本月第一天
|
||||
String lastDay = format.format(cale.getTime()) + " 23:59:59";
|
||||
return lastDay;
|
||||
}
|
||||
|
||||
// 获取某个月的开始时间
|
||||
public static Date getMonth(int i) {
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar cal_1 = Calendar.getInstance();// 获取当前日期
|
||||
cal_1.add(Calendar.MONTH, i);
|
||||
cal_1.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
|
||||
// String firstDay = format.format(cal_1.getTime())+" 00:00:00";
|
||||
return cal_1.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* getLastDay:(获取距离指定时间的指定距离天数 的时间 +[正]为后 -[负]为前). <br/>
|
||||
*
|
||||
* @author Administrator
|
||||
* @param time
|
||||
* @param i
|
||||
* @return
|
||||
* @since JDK 1.8
|
||||
*/
|
||||
public static String getDay(String time,int i){
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
Date date=null;
|
||||
try {
|
||||
date = sdf.parse(time);
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
calendar.setTime(date);
|
||||
int day=calendar.get(Calendar.DATE);
|
||||
// 此处修改为+1则是获取后一天
|
||||
calendar.set(Calendar.DATE,day+i);
|
||||
|
||||
String lastDay = sdf.format(calendar.getTime());
|
||||
return lastDay;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* isBoolean:(当前时间大于活动开始时间,并且当前时间小于活动结束时间). <br/>
|
||||
*
|
||||
* @return
|
||||
*
|
||||
* @author Administrator
|
||||
* @since JDK 1.8
|
||||
*/
|
||||
public static boolean isBoolean(Date startTime, Date endTime) {
|
||||
boolean flag = false;
|
||||
boolean start = new Date().getTime() >= startTime.getTime();
|
||||
boolean end = new Date().getTime() <= endTime.getTime();
|
||||
if (start && end) {
|
||||
flag = true;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
|
||||
public static boolean isValidDate(String str) {
|
||||
boolean convertSuccess=true;
|
||||
// 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
try {
|
||||
// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
|
||||
//format.setLenient(false);
|
||||
format.parse(str);
|
||||
} catch (ParseException e) {
|
||||
// e.printStackTrace();
|
||||
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
|
||||
convertSuccess = false;
|
||||
}
|
||||
return convertSuccess;
|
||||
}
|
||||
|
||||
public static List<Map<String,Object>> getLast6Months() throws ParseException {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.add(Calendar.MONTH, -5);
|
||||
String before_six = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH);//六个月前
|
||||
ArrayList<String> result = new ArrayList<String>();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
|
||||
Calendar min = Calendar.getInstance();
|
||||
Calendar max = Calendar.getInstance();
|
||||
min.setTime(sdf.parse(before_six));
|
||||
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
|
||||
max.setTime(sdf.parse(sdf.format(new Date())));
|
||||
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
|
||||
Calendar curr = min;
|
||||
while (curr.before(max)) {
|
||||
result.add(sdf.format(curr.getTime()));
|
||||
curr.add(Calendar.MONTH, 1);
|
||||
}
|
||||
String nowYear = String.valueOf(c.get(Calendar.YEAR));
|
||||
List<Map<String,Object>> nowChilds = new ArrayList<>();
|
||||
List<Map<String,Object>> prevChilds = new ArrayList<>();
|
||||
Map<String,Object> prevYearMap = new HashMap<>();
|
||||
Map<String,Object> nowYearMap = new HashMap<>();
|
||||
List<Map<String,Object>> yearList = new ArrayList<>();
|
||||
for (String o:result) {
|
||||
String year = o.split("-")[0];
|
||||
String month = o.split("-")[1];
|
||||
if(nowYear.equals(year)){
|
||||
Map<String,Object> childsMap = new HashMap<>();
|
||||
childsMap.put("value",month);
|
||||
nowChilds.add(childsMap);
|
||||
nowYearMap.put("value",year);
|
||||
//yearList.add();
|
||||
}else{
|
||||
Map<String,Object> childsMap = new HashMap<>();
|
||||
childsMap.put("value",month);
|
||||
prevChilds.add(childsMap);
|
||||
prevYearMap.put("value",year);
|
||||
}
|
||||
}
|
||||
nowYearMap.put("childs",nowChilds);
|
||||
if(!prevChilds.isEmpty()){
|
||||
prevYearMap.put("childs",prevChilds);
|
||||
yearList.add(prevYearMap);
|
||||
}
|
||||
yearList.add(nowYearMap);
|
||||
return yearList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断两个时间相差的天数
|
||||
* @param date1
|
||||
* @param date2
|
||||
* @return
|
||||
*/
|
||||
public static int differentDaysByMillisecond(Date date1,Date date2)
|
||||
{
|
||||
int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
|
||||
return days;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断两个时间相差的小时数
|
||||
* @param date1
|
||||
* @param date2
|
||||
* @return
|
||||
*/
|
||||
public static int differentDaysByHours(Date date1,Date date2)
|
||||
{
|
||||
int hours = (int) ((date2.getTime() - date1.getTime()) / (1000*3600));
|
||||
return Math.abs(hours);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws ParseException {
|
||||
//List<String> last6Months = getLast6Months();
|
||||
// List<String> last6Months = new ArrayList<>();
|
||||
// last6Months.add("2019-11");
|
||||
// last6Months.add("2019-12");
|
||||
// last6Months.add("2020-01");
|
||||
// last6Months.add("2020-02");
|
||||
// last6Months.add("2020-03");
|
||||
// last6Months.add("2020-04");
|
||||
/*Calendar c = Calendar.getInstance();
|
||||
String nowYear = String.valueOf(c.get(Calendar.YEAR));
|
||||
List<Map<String,Object>> nowChilds = new ArrayList<>();
|
||||
List<Map<String,Object>> prevChilds = new ArrayList<>();
|
||||
|
||||
Map<String,Object> prevYearMap = new HashMap<>();
|
||||
Map<String,Object> nowYearMap = new HashMap<>();
|
||||
List<Map<String,Object>> yearList = new ArrayList<>();
|
||||
for (String o:last6Months) {
|
||||
String year = o.split("-")[0];
|
||||
String month = o.split("-")[1];
|
||||
if(nowYear.equals(year)){
|
||||
Map<String,Object> childsMap = new HashMap<>();
|
||||
childsMap.put("value",month);
|
||||
nowChilds.add(childsMap);
|
||||
nowYearMap.put("value",year);
|
||||
//yearList.add();
|
||||
}else{
|
||||
Map<String,Object> childsMap = new HashMap<>();
|
||||
childsMap.put("value",month);
|
||||
prevChilds.add(childsMap);
|
||||
prevYearMap.put("value",year);
|
||||
}
|
||||
}
|
||||
nowYearMap.put("childs",nowChilds);
|
||||
prevYearMap.put("childs",prevChilds);
|
||||
yearList.add(nowYearMap);
|
||||
yearList.add(prevYearMap);
|
||||
System.out.println(yearList);*/
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.DESKeySpec;
|
||||
import java.security.Key;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
public class DesUtil {
|
||||
|
||||
/**
|
||||
* 偏移变量,固定占8位字节
|
||||
*/
|
||||
private final static String IV_PARAMETER = "12345678";
|
||||
/**
|
||||
* 密钥算法
|
||||
*/
|
||||
private static final String ALGORITHM = "DES";
|
||||
/**
|
||||
* 加密/解密算法-工作模式-填充模式
|
||||
*/
|
||||
private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";
|
||||
/**
|
||||
* 默认编码
|
||||
*/
|
||||
private static final String CHARSET = "utf-8";
|
||||
|
||||
/**
|
||||
* 生成key
|
||||
*
|
||||
* @param password
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
private static Key generateKey(String password) throws Exception {
|
||||
DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));
|
||||
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
|
||||
return keyFactory.generateSecret(dks);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* DES加密字符串
|
||||
*
|
||||
* @param password 加密密码,长度不能够小于8位
|
||||
* @param data 待加密字符串
|
||||
* @return 加密后内容
|
||||
*/
|
||||
public static String encrypt(String password, String data) {
|
||||
if (password== null || password.length() < 8) {
|
||||
throw new RuntimeException("加密失败,key不能小于8位");
|
||||
}
|
||||
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
SecureRandom random = new SecureRandom();
|
||||
try {
|
||||
Key secretKey = generateKey(password);
|
||||
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey, random);
|
||||
byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));
|
||||
|
||||
//JDK1.8及以上可直接使用Base64,JDK1.7及以下可以使用BASE64Encoder
|
||||
//Android平台可以使用android.util.Base64
|
||||
return new String(Base64.getEncoder().encode(bytes));
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DES解密字符串
|
||||
*
|
||||
* @param password 解密密码,长度不能够小于8位
|
||||
* @param data 待解密字符串
|
||||
* @return 解密后内容
|
||||
*/
|
||||
public static String decrypt(String password, String data) {
|
||||
if (password== null || password.length() < 8) {
|
||||
throw new RuntimeException("加密失败,key不能小于8位");
|
||||
}
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
SecureRandom random = new SecureRandom();
|
||||
try {
|
||||
Key secretKey = generateKey(password);
|
||||
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey, random);
|
||||
return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))), CHARSET);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
// /**
|
||||
// * DES加密文件
|
||||
// *
|
||||
// * @param srcFile 待加密的文件
|
||||
// * @param destFile 加密后存放的文件路径
|
||||
// * @return 加密后的文件路径
|
||||
// */
|
||||
// public static String encryptFile(String password, String srcFile, String destFile) {
|
||||
//
|
||||
// if (password== null || password.length() < 8) {
|
||||
// throw new RuntimeException("加密失败,key不能小于8位");
|
||||
// }
|
||||
// try {
|
||||
// IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
|
||||
// Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
|
||||
// cipher.init(Cipher.ENCRYPT_MODE, generateKey(key), iv);
|
||||
// InputStream is = new FileInputStream(srcFile);
|
||||
// OutputStream out = new FileOutputStream(destFile);
|
||||
// CipherInputStream cis = new CipherInputStream(is, cipher);
|
||||
// byte[] buffer = new byte[1024];
|
||||
// int r;
|
||||
// while ((r = cis.read(buffer)) > 0) {
|
||||
// out.write(buffer, 0, r);
|
||||
// }
|
||||
// cis.close();
|
||||
// is.close();
|
||||
// out.close();
|
||||
// return destFile;
|
||||
// } catch (Exception ex) {
|
||||
// ex.printStackTrace();
|
||||
// }
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * DES解密文件
|
||||
// *
|
||||
// * @param srcFile 已加密的文件
|
||||
// * @param destFile 解密后存放的文件路径
|
||||
// * @return 解密后的文件路径
|
||||
// */
|
||||
// public static String decryptFile(String password, String srcFile, String destFile) {
|
||||
// if (password== null || password.length() < 8) {
|
||||
// throw new RuntimeException("加密失败,key不能小于8位");
|
||||
// }
|
||||
// try {
|
||||
// File file = new File(destFile);
|
||||
// if (!file.exists()) {
|
||||
// file.getParentFile().mkdirs();
|
||||
// file.createNewFile();
|
||||
// }
|
||||
// IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
|
||||
// Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
|
||||
// cipher.init(Cipher.DECRYPT_MODE, generateKey(key), iv);
|
||||
// InputStream is = new FileInputStream(srcFile);
|
||||
// OutputStream out = new FileOutputStream(destFile);
|
||||
// CipherOutputStream cos = new CipherOutputStream(out, cipher);
|
||||
// byte[] buffer = new byte[1024];
|
||||
// int r;
|
||||
// while ((r = is.read(buffer)) >= 0) {
|
||||
// cos.write(buffer, 0, r);
|
||||
// }
|
||||
// cos.close();
|
||||
// is.close();
|
||||
// out.close();
|
||||
// return destFile;
|
||||
// } catch (Exception ex) {
|
||||
// ex.printStackTrace();
|
||||
// }
|
||||
// return null;
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import com.github.binarywang.java.emoji.EmojiConverter;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 表情处理类
|
||||
* @author Administrator
|
||||
*
|
||||
*/
|
||||
public class EmojiUtil {
|
||||
|
||||
private static EmojiConverter emojiConverter = EmojiConverter.getInstance();
|
||||
|
||||
/**
|
||||
* 将emojiStr转为 带有表情的字符
|
||||
* @param emojiStr
|
||||
* @return
|
||||
*/
|
||||
public static String emojiConverterUnicodeStr(String emojiStr){
|
||||
String result = emojiConverter.toUnicode(emojiStr);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 带有表情的字符串转换为编码
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static String emojiConverterToAlias(String str){
|
||||
String result=emojiConverter.toAlias(str);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String emojiRecovery2(String str){
|
||||
String patternString = "\\[\\[(.*?)\\]\\]";
|
||||
|
||||
Pattern pattern = Pattern.compile(patternString);
|
||||
Matcher matcher = pattern.matcher(str);
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
while(matcher.find()) {
|
||||
try {
|
||||
matcher.appendReplacement(sb,
|
||||
URLDecoder.decode(matcher.group(1), "UTF-8"));
|
||||
} catch(UnsupportedEncodingException e) {
|
||||
|
||||
}
|
||||
}
|
||||
matcher.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String emojiConvert1(String str)
|
||||
{
|
||||
String patternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";
|
||||
|
||||
Pattern pattern = Pattern.compile(patternString);
|
||||
Matcher matcher = pattern.matcher(str);
|
||||
StringBuffer sb = new StringBuffer();
|
||||
while(matcher.find()) {
|
||||
try {
|
||||
matcher.appendReplacement(
|
||||
sb,
|
||||
"[["
|
||||
+ URLEncoder.encode(matcher.group(1),
|
||||
"UTF-8") + "]]");
|
||||
} catch(UnsupportedEncodingException e) {
|
||||
}
|
||||
}
|
||||
matcher.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 表格生成
|
||||
* @author Djh
|
||||
*/
|
||||
public interface ExcelInfo<T> {
|
||||
|
||||
/**
|
||||
* 生成数据行
|
||||
* @param rowData 一行的实体数据
|
||||
* @return 返回一行的list数据
|
||||
*/
|
||||
default List<Object> getRowData(T rowData) {
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 生成数据行map
|
||||
* @param rowData 一行的实体数据
|
||||
* @return 返回一行的list数据
|
||||
*/
|
||||
default Map<String, Object> getRowDataMap(T rowData) {
|
||||
return null;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.net.URLEncoder;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.apache.poi.hssf.usermodel.*;
|
||||
import org.apache.poi.hssf.util.HSSFColor;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* @author yuchen
|
||||
*
|
||||
* @Description
|
||||
*/
|
||||
|
||||
public class ExcelUtil {
|
||||
public static<T> HSSFWorkbook getHSSFWorkbook( String sheetNmae, String[] title, Collection<T> values){
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 利用正则的预编译功能
|
||||
*/
|
||||
private static Pattern NUMBER_PATTERN = Pattern.compile("^//d+(//.//d+)?$");
|
||||
|
||||
/**
|
||||
* 导出Excel工具
|
||||
*
|
||||
* @param fileName 文件名
|
||||
* @param sheetName sheet名称
|
||||
* @param headers 第一列内容,表头
|
||||
* @param dataSet 内容
|
||||
* @param keyList map键,用于排序
|
||||
* @param response response
|
||||
* @param pattern 日期格式化
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
public static void exportExcel(String fileName, String sheetName, String[] headers,
|
||||
List<Map<String, Object>> dataSet, String[] keyList, HttpServletResponse response, String pattern) throws IOException {
|
||||
exportExcel(fileName, sheetName, headers, dataSet, keyList, new ExcelInfo<Map<String, Object>>() {
|
||||
@Override
|
||||
public Map<String, Object> getRowDataMap(Map<String, Object> rowData) {
|
||||
return rowData;
|
||||
}
|
||||
}, response, pattern);
|
||||
}
|
||||
|
||||
|
||||
private static <T> void exportExcel(String fileName, String sheetName, String[] headers,
|
||||
List<T> dataSet, String[] keyList, ExcelInfo<T> iExcelInfo, HttpServletResponse response, String pattern) throws IOException {
|
||||
// 声明一个工作薄
|
||||
HSSFWorkbook workbook = new HSSFWorkbook();
|
||||
HSSFCellStyle cellStyle = getCellStyle(workbook);
|
||||
|
||||
// 生成一个表格
|
||||
HSSFSheet sheet = workbook.createSheet(sheetName);
|
||||
// 设置表格默认列宽度为15个字节
|
||||
sheet.setDefaultColumnWidth((short) 15);
|
||||
setTitle(sheet, headers);
|
||||
|
||||
HSSFFont font3 = workbook.createFont();
|
||||
font3.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
|
||||
|
||||
// 声明一个画图的顶级管理器
|
||||
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
|
||||
|
||||
// 遍历集合数据,产生数据行
|
||||
Iterator<T> it = dataSet.iterator();
|
||||
int index = 0;
|
||||
while (it.hasNext()) {
|
||||
index++;
|
||||
T next = it.next();
|
||||
Map<String, Object> rowDataMap = null;
|
||||
List<Object> rowData = null;
|
||||
int dataSize;
|
||||
if (keyList != null) {
|
||||
rowDataMap = iExcelInfo.getRowDataMap(next);
|
||||
dataSize = keyList.length;
|
||||
} else {
|
||||
rowData = iExcelInfo.getRowData(next);
|
||||
dataSize = rowData.size();
|
||||
}
|
||||
|
||||
HSSFRow row = sheet.createRow(index);
|
||||
//根据key的顺序依次从数据中拿到需要的数据,并生成所需要的单元格
|
||||
for (int i = 0; i < dataSize; i++) {
|
||||
HSSFCell cell = row.createCell(i);
|
||||
cell.setCellStyle(cellStyle);
|
||||
Object value;
|
||||
if (keyList != null) {
|
||||
String key = keyList[i];
|
||||
value = rowDataMap.get(key);
|
||||
} else {
|
||||
value = rowData.get(i);
|
||||
}
|
||||
|
||||
|
||||
String textValue;
|
||||
if (value instanceof byte[]) {
|
||||
setPic(row, sheet, patriarch, (byte[]) value, i, index);
|
||||
} else {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
|
||||
textValue = getTextObject(value, formatter);
|
||||
if (textValue != null) {
|
||||
Matcher matcher = NUMBER_PATTERN.matcher(textValue);
|
||||
if (matcher.matches()) {
|
||||
// 是数字当作double处理
|
||||
cell.setCellValue(Double.parseDouble(textValue));
|
||||
} else {
|
||||
HSSFRichTextString richString = new HSSFRichTextString(
|
||||
textValue);
|
||||
|
||||
richString.applyFont(font3);
|
||||
cell.setCellValue(richString);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setResponseHeader(response, fileName);
|
||||
ServletOutputStream out = response.getOutputStream();
|
||||
workbook.write(out);
|
||||
}
|
||||
/**
|
||||
* 导出Excel工具
|
||||
*
|
||||
* @param fileName 文件名
|
||||
* @param sheetName sheet名称
|
||||
* @param response response
|
||||
* @param pattern 日期格式化
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
public static <T> void exportObjectExcel(String fileName, String sheetName, String[] headers, List<T> dataList, ExcelInfo<T> iExcelInfo, HttpServletResponse response, String pattern) throws IOException {
|
||||
|
||||
exportExcel(fileName, sheetName, headers, dataList, null, iExcelInfo, response, pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出Excel工具,
|
||||
*
|
||||
* @param fileName 文件名
|
||||
* @param sheetName sheet名称
|
||||
* @param response response
|
||||
* @param pattern 日期格式化
|
||||
* @throws IOException io异常
|
||||
*/
|
||||
public static <T> void exportObjectExcel(String fileName, String sheetName, String[] headers, List<T> dataList, String[] keyList, HttpServletResponse response, String pattern) throws IOException {
|
||||
|
||||
exportExcel(fileName, sheetName, headers, dataList, keyList, new ExcelInfo<T>() {
|
||||
@Override
|
||||
public Map<String, Object> getRowDataMap(T rowData) {
|
||||
return (JSONObject)JSONObject.toJSON(rowData);
|
||||
}
|
||||
}, response, pattern);
|
||||
}
|
||||
|
||||
private static void setXSSFResponseHeader(HttpServletResponse response, String fileName) {
|
||||
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
||||
String headerValue = "attachment;";
|
||||
headerValue += " filename=\"" + encodeURIComponent(fileName + ".xlsx") +"\";";
|
||||
headerValue += " filename*=utf-8''" + encodeURIComponent(fileName + ".xlsx");
|
||||
response.setHeader("Content-Disposition", headerValue);
|
||||
}
|
||||
|
||||
private static void setResponseHeader(HttpServletResponse response, String fileName) {
|
||||
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
||||
String headerValue = "attachment;";
|
||||
headerValue += " filename=\"" + encodeURIComponent(fileName + ".xls") +"\";";
|
||||
headerValue += " filename*=utf-8''" + encodeURIComponent(fileName + ".xls");
|
||||
response.setHeader("Content-Disposition", headerValue);
|
||||
}
|
||||
|
||||
public static String getTextObject(Object value, DateTimeFormatter sdf) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
} else if (value instanceof Date) {
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
Date date = (Date) value;
|
||||
return sdf.format(date.toInstant().atZone(zone).toLocalDateTime());
|
||||
} else if (value instanceof LocalDateTime) {
|
||||
return ((LocalDateTime) value).format(sdf);
|
||||
} else if (value instanceof BigDecimal) {
|
||||
return ((BigDecimal) value).setScale(2, RoundingMode.HALF_UP).toPlainString();
|
||||
} else {
|
||||
return value.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置表格头
|
||||
* @param sheet sheet
|
||||
* @param headers 标题数组
|
||||
*/
|
||||
private static void setTitle(HSSFSheet sheet, String[] headers) {
|
||||
HSSFWorkbook workbook = sheet.getWorkbook();
|
||||
HSSFCellStyle style = getHeaderStyle(workbook);
|
||||
// 生成一个字体
|
||||
HSSFFont font = workbook.createFont();
|
||||
font.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
|
||||
font.setFontHeightInPoints((short) 12);
|
||||
font.setBold(true);
|
||||
// 把字体应用到当前的样式
|
||||
style.setFont(font);
|
||||
// 产生表格标题行
|
||||
HSSFRow row = sheet.createRow(0);
|
||||
for (short i = 0; i < headers.length; i++) {
|
||||
HSSFCell cell = row.createCell(i);
|
||||
cell.setCellStyle(style);
|
||||
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
|
||||
cell.setCellValue(text);
|
||||
}
|
||||
}
|
||||
|
||||
private static void setPic(HSSFRow hssfRow, Sheet sheet, HSSFPatriarch patriarch, byte[] value, int col, int row) {
|
||||
// 有图片时,设置行高为60px;
|
||||
hssfRow.setHeightInPoints(60);
|
||||
// 设置图片所在列宽度为80px,注意这里单位的一个换算
|
||||
sheet.setColumnWidth(col, (short) (35.7 * 80));
|
||||
// sheet.autoSizeColumn(i);
|
||||
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
|
||||
1023, 255, (short) 6, row, (short) 6, row);
|
||||
anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
|
||||
patriarch.createPicture(anchor, sheet.getWorkbook().addPicture(
|
||||
value, HSSFWorkbook.PICTURE_TYPE_JPEG));
|
||||
}
|
||||
|
||||
/**
|
||||
* 标题的样式
|
||||
*/
|
||||
private static HSSFCellStyle getHeaderStyle(HSSFWorkbook workbook) {
|
||||
HSSFPalette customPalette = workbook.getCustomPalette();
|
||||
customPalette.setColorAtIndex(HSSFColor.HSSFColorPredefined.TAN.getIndex(), (byte) 0xDD, (byte) 0xEB, (byte) 0xF7);
|
||||
|
||||
HSSFCellStyle cellStyle = workbook.createCellStyle();
|
||||
setCellStyle(cellStyle);
|
||||
cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.TAN.getIndex());
|
||||
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
|
||||
return cellStyle;
|
||||
}
|
||||
|
||||
public static void setCellStyle(CellStyle cellStyle) {
|
||||
cellStyle.setAlignment(HorizontalAlignment.CENTER);
|
||||
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
cellStyle.setBorderBottom(BorderStyle.THIN);
|
||||
cellStyle.setBorderTop(BorderStyle.THIN);
|
||||
cellStyle.setBorderLeft(BorderStyle.THIN);
|
||||
cellStyle.setBorderRight(BorderStyle.THIN);
|
||||
}
|
||||
|
||||
public static HSSFCellStyle getCellStyle(HSSFWorkbook workbook) {
|
||||
HSSFCellStyle cellStyle = workbook.createCellStyle();
|
||||
cellStyle.setVerticalAlignment(VerticalAlignment.TOP);
|
||||
// cellStyle.setWrapText(true);
|
||||
return cellStyle;
|
||||
}
|
||||
|
||||
public static void output(Workbook workbook, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
if (workbook instanceof HSSFWorkbook) {
|
||||
setResponseHeader(response, fileName);
|
||||
} else {
|
||||
setXSSFResponseHeader(response, fileName);
|
||||
}
|
||||
|
||||
ServletOutputStream out = response.getOutputStream();
|
||||
workbook.write(out);
|
||||
}
|
||||
|
||||
public static String encodeURIComponent(String value) {
|
||||
try {
|
||||
return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Workbook getWorkBook(MultipartFile file) {
|
||||
//获得文件名
|
||||
String fileName = file.getOriginalFilename();
|
||||
//创建Workbook工作薄对象,表示整个excel
|
||||
Workbook workbook = null;
|
||||
try {
|
||||
//获取excel文件的io流
|
||||
InputStream is = file.getInputStream();
|
||||
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
|
||||
if (fileName.endsWith("xls")) {
|
||||
//2003
|
||||
workbook = new HSSFWorkbook(is);
|
||||
} else if (fileName.endsWith("xlsx")) {
|
||||
//2007 及2007以上
|
||||
workbook = new XSSFWorkbook(is);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return workbook;
|
||||
}
|
||||
|
||||
public static String getCellValue(Cell cell) {
|
||||
String cellValue = "";
|
||||
if (cell == null) {
|
||||
return cellValue;
|
||||
}
|
||||
switch (cell.getCellTypeEnum()) {
|
||||
case NUMERIC:
|
||||
//数字
|
||||
cellValue = stringDateProcess(cell);
|
||||
break;
|
||||
case STRING:
|
||||
//字符串
|
||||
cellValue = String.valueOf(cell.getStringCellValue());
|
||||
break;
|
||||
case BOOLEAN:
|
||||
//Boolean
|
||||
cellValue = String.valueOf(cell.getBooleanCellValue());
|
||||
break;
|
||||
case FORMULA:
|
||||
//公式
|
||||
cellValue = String.valueOf(cell.getCellFormula());
|
||||
break;
|
||||
case BLANK:
|
||||
//空值
|
||||
cellValue = "";
|
||||
break;
|
||||
case ERROR:
|
||||
//故障
|
||||
cellValue = "非法字符";
|
||||
break;
|
||||
default:
|
||||
cellValue = "未知类型";
|
||||
break;
|
||||
}
|
||||
return cellValue;
|
||||
}
|
||||
|
||||
public static String stringDateProcess(Cell cell) {
|
||||
String result = new String();
|
||||
if (HSSFDateUtil.isCellDateFormatted(cell)) {
|
||||
// 处理日期格式、时间格式
|
||||
SimpleDateFormat sdf = null;
|
||||
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
|
||||
sdf = new SimpleDateFormat("HH:mm");
|
||||
} else {// 日期
|
||||
sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
|
||||
}
|
||||
Date date = cell.getDateCellValue();
|
||||
result = sdf.format(date);
|
||||
} else if (cell.getCellStyle().getDataFormat() == 58) {
|
||||
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
|
||||
double value = cell.getNumericCellValue();
|
||||
Date date = org.apache.poi.ss.usermodel.DateUtil
|
||||
.getJavaDate(value);
|
||||
result = sdf.format(date);
|
||||
} else {
|
||||
double value = cell.getNumericCellValue();
|
||||
CellStyle style = cell.getCellStyle();
|
||||
DecimalFormat format = new DecimalFormat();
|
||||
String temp = style.getDataFormatString();
|
||||
// 单元格设置成常规
|
||||
if (temp.equals("General")) {
|
||||
format.applyPattern("#");
|
||||
}
|
||||
result = format.format(value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析上传的excel, 默认只解析第一张Sheet
|
||||
*
|
||||
* @param file excel
|
||||
* @param startRow 数据开始行
|
||||
* @return List<String [ ]>
|
||||
* @throws IOException
|
||||
*/
|
||||
public static List<String[]> getExcelData(MultipartFile file, int startRow) throws IOException {
|
||||
int resultSize = 0;
|
||||
ArrayList<String[]> resultData = new ArrayList<>(resultSize);
|
||||
if (!checkFile(file)) {
|
||||
return resultData;
|
||||
}
|
||||
//获得Workbook工作薄对象
|
||||
Workbook workbook = getWorkBook(file);
|
||||
if (workbook != null) {
|
||||
//获取第一张sheet工作表
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
if (sheet == null) {
|
||||
return resultData;
|
||||
}
|
||||
// 重新初始化List结果大小
|
||||
resultSize = sheet.getLastRowNum() + 1;
|
||||
//获得当前sheet的开始行
|
||||
int firstRowNum = sheet.getFirstRowNum();
|
||||
//获得当前sheet的结束行
|
||||
int lastRowNum = sheet.getLastRowNum();
|
||||
//循环除了startRow的所有行,如果要循环除第一行以外的就firstRowNum+1
|
||||
for (int rowNum = firstRowNum + startRow; rowNum <= lastRowNum; rowNum++) {
|
||||
//获得当前行
|
||||
Row row = sheet.getRow(rowNum);
|
||||
if (rowIsEmpty(row)) {
|
||||
break;
|
||||
}
|
||||
//获得当前行的开始列
|
||||
int firstCellNum = row.getFirstCellNum();
|
||||
//获得当前行的列数
|
||||
int lastCellNum = row.getLastCellNum();
|
||||
String[] cells = new String[lastCellNum];
|
||||
//循环当前行
|
||||
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
|
||||
Cell cell = row.getCell(cellNum);
|
||||
cells[cellNum] = getCellValue(cell);
|
||||
}
|
||||
resultData.add(cells);
|
||||
}
|
||||
workbook.close();
|
||||
}
|
||||
return resultData;
|
||||
}
|
||||
public static boolean rowIsEmpty(Row row) {
|
||||
if (null == row) {
|
||||
return true;
|
||||
}
|
||||
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
|
||||
Cell cell = row.getCell(c);
|
||||
if (cell != null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件格式
|
||||
*
|
||||
* @param file
|
||||
* @throws IOException
|
||||
*/
|
||||
public static boolean checkFile(MultipartFile file) throws IOException {
|
||||
if (null == file) {
|
||||
return false;
|
||||
}
|
||||
//获得文件名
|
||||
String fileName = file.getOriginalFilename();
|
||||
//判断文件是否是excel文件
|
||||
if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import org.apache.commons.net.util.Base64;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.multipart.commons.CommonsMultipartFile;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.*;
|
||||
|
||||
/**
|
||||
* @author yuchen
|
||||
* @Description
|
||||
*/
|
||||
public class FileUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
|
||||
|
||||
/**
|
||||
* File2byte:(file转byte). <br/>
|
||||
*
|
||||
* @param filePath
|
||||
* @return
|
||||
* @throws MalformedURLException
|
||||
* @author Administrator
|
||||
* @since JDK 1.8
|
||||
*/
|
||||
public static byte[] fileToByte(String filePath) throws Exception {
|
||||
InputStream in = null;
|
||||
BufferedInputStream bin = null;
|
||||
ByteArrayOutputStream baos = null;
|
||||
BufferedOutputStream bout = null;
|
||||
try {
|
||||
URL url = new URL(filePath);
|
||||
URLConnection conn = url.openConnection();
|
||||
in = conn.getInputStream();
|
||||
bin = new BufferedInputStream(in);
|
||||
baos = new ByteArrayOutputStream();
|
||||
bout = new BufferedOutputStream(baos);
|
||||
byte[] buffer = new byte[1024];
|
||||
int len = bin.read(buffer);
|
||||
while (len != -1) {
|
||||
bout.write(buffer, 0, len);
|
||||
len = bin.read(buffer);
|
||||
}
|
||||
// 刷新此输出流并强制写出所有缓冲的输出字节
|
||||
bout.flush();
|
||||
byte[] bytes = baos.toByteArray();
|
||||
return bytes;
|
||||
} finally {
|
||||
in.close();
|
||||
bin.close();
|
||||
bout.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* File2byte:(file转byte). <br/>
|
||||
*
|
||||
* @param filePath
|
||||
* @return
|
||||
* @throws MalformedURLException
|
||||
* @author Administrator
|
||||
* @since JDK 1.8
|
||||
*/
|
||||
public static byte[] File2byte2(String filePath) throws Exception {
|
||||
byte[] buffer = null;
|
||||
try {
|
||||
File file = new File(filePath);
|
||||
FileInputStream fis = new FileInputStream(file);
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
byte[] b = new byte[1024];
|
||||
int n;
|
||||
while ((n = fis.read(b)) != -1) {
|
||||
bos.write(b, 0, n);
|
||||
}
|
||||
fis.close();
|
||||
bos.close();
|
||||
buffer = bos.toByteArray();
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 根据文件路径读取byte[] 数组
|
||||
*/
|
||||
public static byte[] readFileByBytes(String filePath) throws IOException {
|
||||
File file = new File(filePath);
|
||||
if (!file.exists()) {
|
||||
throw new FileNotFoundException(filePath);
|
||||
} else {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
|
||||
BufferedInputStream in = null;
|
||||
|
||||
try {
|
||||
in = new BufferedInputStream(new FileInputStream(file));
|
||||
short bufSize = 1024;
|
||||
byte[] buffer = new byte[bufSize];
|
||||
int len1;
|
||||
while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
|
||||
bos.write(buffer, 0, len1);
|
||||
}
|
||||
|
||||
byte[] var7 = bos.toByteArray();
|
||||
return var7;
|
||||
} finally {
|
||||
try {
|
||||
if (in != null) {
|
||||
in.close();
|
||||
}
|
||||
} catch (IOException var14) {
|
||||
var14.printStackTrace();
|
||||
}
|
||||
|
||||
bos.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static Integer imageSize(String imageBase64Str) {
|
||||
if (imageBase64Str == null) {
|
||||
throw new MsgException("图片不能为空!");
|
||||
}
|
||||
//1.找到等号,把等号也去掉(=用来填充base64字符串长度用)
|
||||
Integer equalIndex = imageBase64Str.indexOf("=");
|
||||
if (imageBase64Str.indexOf("=") > 0) {
|
||||
imageBase64Str = imageBase64Str.substring(0, equalIndex);
|
||||
}
|
||||
//2.原来的字符流大小,单位为字节
|
||||
Integer strLength = imageBase64Str.length();
|
||||
System.out.println("imageBase64Str Length = " + strLength);
|
||||
//3.计算后得到的文件流大小,单位为字节
|
||||
Integer size = strLength - (strLength / 8) * 2;
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* byte(字节)根据长度转成kb(千字节)和mb(兆字节)
|
||||
*
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
public static boolean bytesToKB(long bytes, int maxSize) {
|
||||
boolean flag = false;
|
||||
BigDecimal filesize = new BigDecimal(bytes);
|
||||
logger.error("==========filesize==============" + filesize);
|
||||
BigDecimal megabyte = new BigDecimal(1024 * 1024);
|
||||
logger.error("==========megabyte==============" + megabyte);
|
||||
float returnValue = filesize.divide(megabyte, 1, BigDecimal.ROUND_DOWN).floatValue();
|
||||
logger.error("==========returnValue1==============" + returnValue);
|
||||
if (returnValue >= maxSize) {
|
||||
flag = true;
|
||||
//return (returnValue + "MB");
|
||||
return flag;
|
||||
}
|
||||
BigDecimal kilobyte = new BigDecimal(1024);
|
||||
returnValue = filesize.divide(kilobyte, 1, BigDecimal.ROUND_DOWN).floatValue();
|
||||
logger.error("==========returnValue2==============" + returnValue);
|
||||
return flag;
|
||||
}
|
||||
|
||||
public static void url2File(String url, File file) {
|
||||
try {
|
||||
FileOutputStream fos = new FileOutputStream(file);
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
|
||||
conn.setReadTimeout(30000);
|
||||
conn.setConnectTimeout(30000);
|
||||
//设置应用程序要从网络连接读取数据
|
||||
conn.setDoInput(true);
|
||||
conn.setRequestMethod("GET");
|
||||
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
|
||||
InputStream is = conn.getInputStream();
|
||||
|
||||
int bytesRead = 0;
|
||||
byte[] buffer = new byte[8192];
|
||||
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
|
||||
fos.write(buffer, 0, bytesRead);
|
||||
}
|
||||
fos.close();
|
||||
is.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("文件下载失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] url2Bytes(String url) throws IOException {
|
||||
URL urlConet = new URL(url);
|
||||
HttpURLConnection con = (HttpURLConnection) urlConet.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
con.setConnectTimeout(4 * 1000);
|
||||
InputStream inStream = con.getInputStream(); //通过输入流获取图片数据
|
||||
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[2048];
|
||||
int len = 0;
|
||||
while ((len = inStream.read(buffer)) != -1) {
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
inStream.close();
|
||||
byte[] data = outStream.toByteArray();
|
||||
return data;
|
||||
}
|
||||
|
||||
public static String getBase64FromInputStream(InputStream in) {
|
||||
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
|
||||
byte[] data = null;
|
||||
// 读取图片字节数组
|
||||
try {
|
||||
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
|
||||
byte[] buff = new byte[100];
|
||||
int rc = 0;
|
||||
while ((rc = in.read(buff, 0, 100)) > 0) {
|
||||
swapStream.write(buff, 0, rc);
|
||||
}
|
||||
data = swapStream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (in != null) {
|
||||
try {
|
||||
in.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (data == null) {
|
||||
return null;
|
||||
} else {
|
||||
return new String(Base64.encodeBase64(data));
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] readInputStream(InputStream inputStream) throws IOException {
|
||||
byte[] buffer = new byte[1024];
|
||||
int len = 0;
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
while ((len = inputStream.read(buffer)) != -1) {
|
||||
bos.write(buffer, 0, len);
|
||||
}
|
||||
bos.close();
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
public static String getBase64FromUrl(String url) {
|
||||
try {
|
||||
URL urlConn = new URL(url);
|
||||
HttpURLConnection con = (HttpURLConnection) urlConn.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
con.setConnectTimeout(4 * 1000);
|
||||
InputStream inStream = con.getInputStream();
|
||||
|
||||
return FileUtil.getBase64FromInputStream(inStream);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param fileUrl:
|
||||
* @param savePath:
|
||||
* @description:根据url下载文件到指定的目录
|
||||
* @date: 2021/8/4 16:45
|
||||
*/
|
||||
public static void downloadFile(String fileUrl, String savePath) throws Exception {
|
||||
File file = new File(savePath);
|
||||
//判断文件是否存在,不存在则创建文件
|
||||
if (!file.exists()) {
|
||||
file.createNewFile();
|
||||
}
|
||||
URL url = new URL(fileUrl);
|
||||
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
|
||||
urlCon.setConnectTimeout(6000);
|
||||
urlCon.setReadTimeout(6000);
|
||||
int code = urlCon.getResponseCode();
|
||||
if (code != HttpURLConnection.HTTP_OK) {
|
||||
throw new Exception("文件读取失败");
|
||||
}
|
||||
DataInputStream in = new DataInputStream(urlCon.getInputStream());
|
||||
DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
|
||||
byte[] buffer = new byte[2048];
|
||||
int count = 0;
|
||||
while ((count = in.read(buffer)) > 0) {
|
||||
out.write(buffer, 0, count);
|
||||
}
|
||||
try {
|
||||
if (out != null) {
|
||||
out.close();
|
||||
}
|
||||
if (in != null) {
|
||||
in.close();
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void downLoad(HttpServletResponse response, String name, String filePath) throws IOException {
|
||||
response.setContentType("application/x-download");
|
||||
String fileName = URLEncoder.encode(name, "UTF-8");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
|
||||
File file = new File(filePath);
|
||||
InputStream stream = null;
|
||||
ServletOutputStream out = null;
|
||||
try {
|
||||
stream = new FileInputStream(file);
|
||||
out = response.getOutputStream();
|
||||
byte buff[] = new byte[1024];
|
||||
int length = 0;
|
||||
while ((length = stream.read(buff)) > 0) {
|
||||
out.write(buff, 0, length);
|
||||
}
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (stream != null) {
|
||||
stream.close();
|
||||
}
|
||||
if (out != null) {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean deleteDir(File dir) {
|
||||
if (dir.isDirectory()) {
|
||||
String[] children = dir.list();
|
||||
if (children == null) {
|
||||
return dir.delete();
|
||||
}
|
||||
|
||||
for (String child : children) {
|
||||
boolean success = deleteDir(new File(dir, child));
|
||||
if (!success) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 目录此时为空,可以删除
|
||||
return dir.delete();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author SSS
|
||||
*/
|
||||
public class FixedData {
|
||||
|
||||
public static List<String> bankList = new ArrayList<String>() {{
|
||||
add("工商银行");
|
||||
add("交通银行");
|
||||
add("招商银行");
|
||||
add("民生银行");
|
||||
add("中信银行");
|
||||
add("浦发银行");
|
||||
add("兴业银行");
|
||||
add("光大银行");
|
||||
add("广发银行");
|
||||
add("平安银行");
|
||||
add("北京银行");
|
||||
add("华夏银行");
|
||||
add("农业银行");
|
||||
add("建设银行");
|
||||
add("邮政储蓄银行");
|
||||
add("中国银行");
|
||||
add("宁波银行");
|
||||
add("其他银行");
|
||||
}};
|
||||
|
||||
/**
|
||||
* 银行名称转化
|
||||
* @param originBankName 银行名称
|
||||
* @return 限定的银行名称
|
||||
*/
|
||||
public static String getBankName(String originBankName) {
|
||||
if (originBankName == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (String bankName : bankList) {
|
||||
if (Objects.equals(originBankName, bankName)) {
|
||||
return bankName;
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(originBankName)) {
|
||||
if (originBankName.contains("广发银行") || originBankName.contains("广东发展银行")) {
|
||||
return "广发银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("建设银行")) {
|
||||
return "建设银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("招商银行")) {
|
||||
return "招商银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("工商银行")) {
|
||||
return "工商银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("民生银行")) {
|
||||
return "民生银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("中信银行")) {
|
||||
return "中信银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("浦东发展银行")) {
|
||||
return "浦发银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("兴业银行")) {
|
||||
return "兴业银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("光大银行")) {
|
||||
return "光大银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("平安银行")) {
|
||||
return "平安银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("北京银行")) {
|
||||
return "北京银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("华夏银行")) {
|
||||
return "华夏银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("农业银行")) {
|
||||
return "农业银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("邮政")) {
|
||||
return "邮政储蓄银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("中国银行")) {
|
||||
return "中国银行";
|
||||
}
|
||||
|
||||
if (originBankName.contains("宁波银行")) {
|
||||
return "宁波银行";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
return "其他银行";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import org.apache.commons.net.ftp.FTPClient;
|
||||
import org.apache.commons.net.ftp.FTPReply;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
/**
|
||||
* ftp文件操作工具类
|
||||
*/
|
||||
public class FtpUtils {
|
||||
|
||||
// // ftp服务器地址
|
||||
// public String hostname = "119.254.93.57";
|
||||
//
|
||||
// // ftp服务器端口号默认为21
|
||||
// public Integer port = 22221;
|
||||
//
|
||||
// // ftp登录账号
|
||||
// public String username = "rscy";
|
||||
//
|
||||
// // ftp登录密码fileName
|
||||
// public String password = "gS4*F&o51KhA";
|
||||
//
|
||||
// public String basePath = "onlpay/";
|
||||
|
||||
public static FTPClient ftpClient = null;
|
||||
|
||||
/**
|
||||
* 本地字符编码
|
||||
**/
|
||||
private static String localCharset = "GBK";
|
||||
|
||||
/**
|
||||
* FTP协议里面,规定文件名编码为iso-8859-1
|
||||
**/
|
||||
private static String serverCharset = "ISO-8859-1";
|
||||
|
||||
/**
|
||||
* UTF-8字符编码
|
||||
**/
|
||||
private static final String CHARSET_UTF8 = "UTF-8";
|
||||
|
||||
/**
|
||||
* OPTS UTF8字符串常量
|
||||
**/
|
||||
private static final String OPTS_UTF8 = "OPTS UTF8";
|
||||
|
||||
/**
|
||||
* 设置缓冲区大小4M
|
||||
**/
|
||||
private static final int BUFFER_SIZE = 1024 * 1024 * 4;
|
||||
|
||||
/**
|
||||
* 下载该目录下所有文件到本地
|
||||
*
|
||||
* @param ftpPath FTP服务器上的相对路径,例如:test/123
|
||||
* @param savePath 保存文件到本地的路径,例如:D:/test
|
||||
* @return 成功返回true,否则返回false
|
||||
*/
|
||||
public static boolean downloadFiles(String prefixPath,String ftpPath, String savePath,String hostname,Integer port,String username,String password) {
|
||||
// 登录
|
||||
login(hostname, port, username, password);
|
||||
if (ftpClient != null) {
|
||||
try {
|
||||
String path = changeEncoding(prefixPath + ftpPath);
|
||||
// 判断是否存在该目录
|
||||
if (!ftpClient.changeWorkingDirectory(path)) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
ftpClient.enterLocalPassiveMode(); // 设置被动模式,开通一个端口来传输数据
|
||||
String[] fs = ftpClient.listNames();
|
||||
// 判断该目录下是否有文件
|
||||
if (fs == null || fs.length == 0) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
for (String ff : fs) {
|
||||
String ftpName = new String(ff.getBytes(serverCharset), localCharset);
|
||||
File file = new File(savePath + '/' + ftpName);
|
||||
try (OutputStream os = new FileOutputStream(file)) {
|
||||
ftpClient.retrieveFile(ff, os);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
closeConnect();
|
||||
}
|
||||
}
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接FTP服务器
|
||||
*
|
||||
* @param address 地址,如:127.0.0.1
|
||||
* @param port 端口,如:21
|
||||
* @param username 用户名,如:root
|
||||
* @param password 密码,如:root
|
||||
*/
|
||||
private static void login(String address, int port, String username, String password) {
|
||||
ftpClient = new FTPClient();
|
||||
try {
|
||||
ftpClient.connect(address, port);
|
||||
ftpClient.login(username, password);
|
||||
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
|
||||
//限制缓冲区大小
|
||||
ftpClient.setBufferSize(BUFFER_SIZE);
|
||||
int reply = ftpClient.getReplyCode();
|
||||
if (!FTPReply.isPositiveCompletion(reply)) {
|
||||
closeConnect();
|
||||
MsgException.throwException("FTP服务器连接失败");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
MsgException.throwException("FTP登录失败");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* FTP服务器路径编码转换
|
||||
*
|
||||
* @param ftpPath FTP服务器路径
|
||||
* @return String
|
||||
*/
|
||||
private static String changeEncoding(String ftpPath) {
|
||||
String directory = null;
|
||||
try {
|
||||
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
|
||||
localCharset = CHARSET_UTF8;
|
||||
}
|
||||
directory = new String(ftpPath.getBytes(localCharset), serverCharset);
|
||||
} catch (Exception e) {
|
||||
MsgException.throwException("路径编码转换失败");
|
||||
}
|
||||
return directory;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭FTP连接
|
||||
*/
|
||||
private static void closeConnect() {
|
||||
if (ftpClient != null && ftpClient.isConnected()) {
|
||||
try {
|
||||
ftpClient.logout();
|
||||
ftpClient.disconnect();
|
||||
} catch (IOException e) {
|
||||
// logger.error("关闭FTP连接失败", e);
|
||||
MsgException.throwException("关闭FTP连接失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 检查指定目录下是否含有指定文件
|
||||
*
|
||||
* @param ftpPath FTP服务器文件相对路径,例如:test/123
|
||||
* @param fileName 要下载的文件名,例如:test.txt
|
||||
* @return 成功返回true,否则返回false
|
||||
*/
|
||||
public boolean checkFileInFtp(String prefixPath,String ftpPath, String fileName,String hostname,Integer port,String username,String password) {
|
||||
// 登录
|
||||
login(hostname, port, username, password);
|
||||
if (ftpClient != null) {
|
||||
try {
|
||||
String path = changeEncoding(prefixPath + ftpPath);
|
||||
// 判断是否存在该目录
|
||||
if (!ftpClient.changeWorkingDirectory(path)) {
|
||||
//logger.error(basePath + ftpPath + DIR_NOT_EXIST);
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
ftpClient.enterLocalPassiveMode(); // 设置被动模式,开通一个端口来传输数据
|
||||
String[] fs = ftpClient.listNames();
|
||||
// 判断该目录下是否有文件
|
||||
if (fs == null || fs.length == 0) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
for (String ff : fs) {
|
||||
String ftpName = new String(ff.getBytes(serverCharset), localCharset);
|
||||
if (ftpName.equals(fileName)) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
closeConnect();
|
||||
}
|
||||
}
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载该目录下所有文件到本地 根据实际需要修改执行逻辑
|
||||
*
|
||||
* @param ftpPath FTP服务器上的相对路径,例如:test/123
|
||||
* @param savePath 保存文件到本地的路径,例如:D:/test
|
||||
* @return 成功返回true,否则返回false
|
||||
*/
|
||||
// public Map<String, Object> downLoadTableFile(String ftpPath, String savePath) {
|
||||
// // 登录
|
||||
// login(hostname, port, username, password);
|
||||
// Map<String, Object> resultMap = new HashMap<>();
|
||||
// if (ftpClient != null) {
|
||||
// try {
|
||||
// String path = changeEncoding(basePath + "/" + ftpPath);
|
||||
// // 判断是否存在该目录
|
||||
// if (!ftpClient.changeWorkingDirectory(path)) {
|
||||
// System.out.println("12================>"+basePath + "/" + ftpPath + DIR_NOT_EXIST);
|
||||
// //logger.error(basePath + "/" + ftpPath + DIR_NOT_EXIST);
|
||||
// resultMap.put("result", false);
|
||||
// return resultMap;
|
||||
// }
|
||||
// ftpClient.enterLocalPassiveMode(); // 设置被动模式,开通一个端口来传输数据
|
||||
// String[] fs = ftpClient.listNames();
|
||||
// // 判断该目录下是否有文件
|
||||
// if (fs == null || fs.length == 0) {
|
||||
//// logger.error(basePath + "/" + ftpPath + DIR_CONTAINS_NO_FILE);
|
||||
// System.out.println("12================>"+basePath + "/" + ftpPath + DIR_CONTAINS_NO_FILE);
|
||||
// resultMap.put("result", false);
|
||||
// return resultMap;
|
||||
// }
|
||||
// List<String> tableFileNameList = new ArrayList<>();
|
||||
// //根据表名创建文件夹
|
||||
// String tableDirName = savePath + "/" + ftpPath;
|
||||
// File tableDirs=new File(tableDirName);
|
||||
// if(!tableDirs.exists()){
|
||||
// tableDirs.mkdirs();
|
||||
// }
|
||||
// for (String ff : fs) {
|
||||
// String ftpName = new String(ff.getBytes(serverCharset), localCharset);
|
||||
// File file = new File(tableDirName + "/" + ftpName);
|
||||
// //存储文件名导入时使用
|
||||
// tableFileNameList.add(tableDirName + "/" + ftpName);
|
||||
// try (OutputStream os = new FileOutputStream(file)) {
|
||||
// ftpClient.retrieveFile(ff, os);
|
||||
// } catch (Exception e) {
|
||||
// System.out.println("13================>"+e.getMessage());
|
||||
//// logger.error(e.getMessage(), e);
|
||||
// }
|
||||
// }
|
||||
// resultMap.put("fileNameList", tableFileNameList);
|
||||
// resultMap.put("result", true);
|
||||
// return resultMap;
|
||||
// } catch (IOException e) {
|
||||
// System.out.println("13================>下载文件失败");
|
||||
//// logger.error("下载文件失败", e);
|
||||
// } finally {
|
||||
// closeConnect();
|
||||
// }
|
||||
// }
|
||||
// resultMap.put("result", false);
|
||||
// return resultMap;
|
||||
// }
|
||||
|
||||
|
||||
/**
|
||||
* Ø 目录示例:/onlpay/20200701/ 线上交易对帐文件每天1个文件夹,命名方式为8位年月日
|
||||
* Ø 交易对帐文件tran_ROX00000000****_20200701.cvs.gz
|
||||
* Ø 出款预对帐文件pre_balance_ROX00000000****_20200701.txt.gz
|
||||
* Ø 出款终对帐文件last_balance_ROX00000000****_20200701.txt.gz
|
||||
* Ø 差错对账文件prev_error_ROX00000000****_20200512.cvs.gz
|
||||
* /onlpay/20210202/pre_balance_ROX000000002983_20210202.txt.gz
|
||||
*/
|
||||
// public static void main(String[] args) throws IOException {
|
||||
// FtpUtils ftp = new FtpUtils();
|
||||
// ftp.downloadFiles("20210202/","E:\\crystal\\ftp\\file");
|
||||
//
|
||||
// String filePath = "E:\\crystal\\ftp\\file\\";
|
||||
// String fileName = "pre_balance_ROX000000002983_20210202.txt.gz";
|
||||
// FileInputStream fileInputStream = new FileInputStream(filePath + fileName);
|
||||
// //解凍する
|
||||
// GZIPInputStream Zin = new GZIPInputStream(fileInputStream);
|
||||
// File outdir = new File(filePath);
|
||||
// extractFile(Zin, outdir, "aaa.txt");
|
||||
// }
|
||||
|
||||
public static void extractFile(String fileName,String filePath,String outFileName) throws IOException {
|
||||
FileInputStream fileInputStream = new FileInputStream(filePath + File.separator +fileName);
|
||||
//解凍する
|
||||
GZIPInputStream in = new GZIPInputStream(fileInputStream);
|
||||
File outdir = new File(filePath);
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
BufferedOutputStream out = new BufferedOutputStream(
|
||||
new FileOutputStream(new File(outdir, outFileName)));
|
||||
int count = -1;
|
||||
while ((count = in.read(buffer)) != -1) {
|
||||
out.write(buffer, 0, count);
|
||||
}
|
||||
out.close();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import cn.hutool.crypto.SecureUtil;
|
||||
import cn.pluss.platform.config.GetuiConfig;
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.web.client.ResponseErrorHandler;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 个推按照cid推送,
|
||||
* <b>没有区分安卓和iOS</b>
|
||||
*/
|
||||
@Slf4j
|
||||
public class GetuiPushUtil implements IPush {
|
||||
|
||||
private static IPush instance;
|
||||
|
||||
public static IPush getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new GetuiPushUtil();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static RestTemplate restTemplate;
|
||||
|
||||
private static RestTemplate getRestTemplate() {
|
||||
if (restTemplate == null) {
|
||||
restTemplate = new RestTemplate();
|
||||
ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
|
||||
@Override
|
||||
public boolean hasError(ClientHttpResponse response) throws IOException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleError(ClientHttpResponse response) throws IOException {
|
||||
}
|
||||
};
|
||||
restTemplate.setErrorHandler(responseErrorHandler);
|
||||
}
|
||||
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
public void init() {
|
||||
// token初始化
|
||||
if (GetuiConfig.token == null) {
|
||||
initToken();
|
||||
}
|
||||
|
||||
// token超时初始化
|
||||
if (System.currentTimeMillis() + 1000 > GetuiConfig.expireTime) {
|
||||
initToken();
|
||||
}
|
||||
}
|
||||
|
||||
private static void initToken() {
|
||||
String authUrl = "https://restapi.getui.com/v2/lcpLtzlX1IAVVHaMzO7rI9/auth";
|
||||
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
long currentTimeMillis = System.currentTimeMillis();
|
||||
System.out.println(currentTimeMillis);
|
||||
map.put("timestamp", currentTimeMillis);
|
||||
map.put("appkey", "qH8axt3RQ97lSPA1nsol1");
|
||||
|
||||
String sign = SecureUtil.sha256("qH8axt3RQ97lSPA1nsol1" + currentTimeMillis + "5QOwOzksge8R0ikThr0Ma1");
|
||||
map.put("sign", sign);
|
||||
|
||||
JSONObject resp = getRestTemplate().postForObject(authUrl, map, JSONObject.class);
|
||||
if (resp == null) {
|
||||
log.error("个推获取授权接口请求异常");
|
||||
throw new MsgException("个推获取授权接口请求异常");
|
||||
}
|
||||
|
||||
if (resp.getIntValue("code") != 0) {
|
||||
log.error("个推获取授权接口请求异常: {}", resp.getString("msg"));
|
||||
throw new MsgException(resp.getString("msg"));
|
||||
}
|
||||
|
||||
JSONObject data = resp.getJSONObject("data");
|
||||
GetuiConfig.token = data.getString("token");
|
||||
GetuiConfig.expireTime = data.getLong("expire_time");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendAndroidByAlias(List<String> cidList, String notificationTitle, String msgContent, String extrasParam) {
|
||||
init();
|
||||
// 创建消息
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("token", GetuiConfig.token);
|
||||
|
||||
JSONObject param1 = new JSONObject();
|
||||
param1.fluentPut("request_id", UUID.randomUUID().toString().replace("-", ""))
|
||||
.fluentPut("group_name", UUID.randomUUID().toString().replace("-", ""))
|
||||
.fluentPut("settings", new JSONObject().fluentPut("ttl", 3600000));
|
||||
|
||||
JSONObject extra = new JSONObject();
|
||||
extra.put("url", extrasParam);
|
||||
extra.put("content", msgContent);
|
||||
extra.put("title", notificationTitle);
|
||||
|
||||
JSONObject notification1 = new JSONObject();
|
||||
notification1.put("title", notificationTitle);
|
||||
notification1.put("body", msgContent);
|
||||
notification1.put("click_type", "payload");
|
||||
notification1.put("payload", extra.toString());
|
||||
param1.fluentPut("push_message", new JSONObject().fluentPut("notification", notification1));
|
||||
|
||||
JSONObject pushChannel = new JSONObject();
|
||||
JSONObject iosChannel = new JSONObject();
|
||||
iosChannel.put("type", "notify");
|
||||
iosChannel.put("payload", extra.toString());
|
||||
|
||||
JSONObject aps = new JSONObject();
|
||||
aps.put("alert", new JSONObject().fluentPut("title", notificationTitle).fluentPut("body", msgContent));
|
||||
aps.put("content-available", 0);
|
||||
iosChannel.put("aps", aps);
|
||||
iosChannel.put("auto_badge", "+1");
|
||||
pushChannel.put("ios", iosChannel);
|
||||
param1.put("push_channel", pushChannel);
|
||||
|
||||
HttpEntity<JSONObject> httpEntity = new HttpEntity<>(param1, headers);
|
||||
JSONObject resp = getRestTemplate().postForObject(GetuiConfig.createMsg, httpEntity, JSONObject.class);
|
||||
if (resp == null) {
|
||||
log.error("个推推送接口请求异常");
|
||||
// throw new MsgException("个推推送接口请求异常");
|
||||
return;
|
||||
}
|
||||
log.error("resp: {}", resp);
|
||||
|
||||
if (resp.getIntValue("code") != 0) {
|
||||
log.error("个推推送接口请求异常: {}", resp.getString("msg"));
|
||||
// throw new MsgException(resp.getString("msg"));
|
||||
return;
|
||||
}
|
||||
|
||||
String taskId = resp.getJSONObject("data").getString("taskid");
|
||||
|
||||
JSONObject param = new JSONObject();
|
||||
param.put("is_async", true);
|
||||
param.put("audience", new JSONObject().fluentPut("cid", cidList));
|
||||
param.put("taskid", taskId);
|
||||
|
||||
HttpEntity<JSONObject> httpEntity2 = new HttpEntity<>(param, headers);
|
||||
JSONObject resp2 = getRestTemplate().postForObject(GetuiConfig.listCid, httpEntity2, JSONObject.class);
|
||||
if (resp2 == null) {
|
||||
log.error("个推推送接口请求异常");
|
||||
// throw new MsgException("个推推送接口请求异常");
|
||||
return;
|
||||
}
|
||||
log.error("resp2: {}", resp2);
|
||||
|
||||
if (resp2.getIntValue("code") != 0) {
|
||||
log.error("个推推送接口请求异常: {}", resp.getString("msg"));
|
||||
// throw new MsgException(resp.getString("msg"));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendIOSByAlias(List<String> cidList, String notificationTitle, String msgContent, String extrasParam) {
|
||||
init();
|
||||
|
||||
// 创建消息
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("token", GetuiConfig.token);
|
||||
|
||||
JSONObject param1 = new JSONObject();
|
||||
param1.fluentPut("request_id", UUID.randomUUID().toString().replace("-", ""))
|
||||
.fluentPut("group_name", UUID.randomUUID().toString().replace("-", ""))
|
||||
.fluentPut("settings", new JSONObject().fluentPut("ttl", 3600000));
|
||||
|
||||
JSONObject notification1 = new JSONObject();
|
||||
notification1.put("title", notificationTitle);
|
||||
notification1.put("body", msgContent);
|
||||
notification1.put("click_type", "payload");
|
||||
notification1.put("payload", extrasParam);
|
||||
param1.fluentPut("push_message", new JSONObject().fluentPut("notification", notification1));
|
||||
|
||||
HttpEntity<JSONObject> httpEntity = new HttpEntity<>(param1, headers);
|
||||
JSONObject resp = getRestTemplate().postForObject(GetuiConfig.createMsg, httpEntity, JSONObject.class);
|
||||
if (resp == null) {
|
||||
log.error("个推推送接口请求异常");
|
||||
// throw new MsgException("个推推送接口请求异常");
|
||||
return;
|
||||
}
|
||||
log.error("resp: {}", resp);
|
||||
|
||||
if (resp.getIntValue("code") != 0) {
|
||||
log.error("个推推送接口请求异常: {}", resp.getString("msg"));
|
||||
// throw new MsgException(resp.getString("msg"));
|
||||
return;
|
||||
}
|
||||
|
||||
String taskId = resp.getJSONObject("data").getString("taskid");
|
||||
|
||||
JSONObject param = new JSONObject();
|
||||
param.put("is_async", true);
|
||||
param.put("audience", new JSONObject().fluentPut("cid", cidList));
|
||||
param.put("taskid", taskId);
|
||||
|
||||
HttpEntity<JSONObject> httpEntity2 = new HttpEntity<>(param, headers);
|
||||
JSONObject resp2 = getRestTemplate().postForObject(GetuiConfig.listCid, httpEntity2, JSONObject.class);
|
||||
if (resp2 == null) {
|
||||
log.error("个推推送接口请求异常");
|
||||
// throw new MsgException("个推推送接口请求异常");
|
||||
return;
|
||||
}
|
||||
log.error("resp2: {}", resp2);
|
||||
|
||||
if (resp2.getIntValue("code") != 0) {
|
||||
log.error("个推推送接口请求异常: {}", resp.getString("msg"));
|
||||
// throw new MsgException(resp.getString("msg"));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendAllPlatByAlias(List<String> alias, String notificationTitle, String msgContent, String extrasParam) {
|
||||
sendAndroidByAlias(alias, notificationTitle, msgContent, extrasParam);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendIOSAll(String notificationTitle, String msgContent, String extrasParam) {
|
||||
init();
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("token", GetuiConfig.token);
|
||||
|
||||
JSONObject param = new JSONObject();
|
||||
param.put("is_async", true);
|
||||
param.put("request_id", UUID.randomUUID().toString().replace("-", ""));
|
||||
param.put("settings", new JSONObject().fluentPut("ttl", 3600000));
|
||||
|
||||
JSONObject tag = new JSONObject()
|
||||
.fluentPut("key", "phone_type")
|
||||
.fluentPut("values", new String[]{"android"})
|
||||
.fluentPut("opt_type", "and");
|
||||
|
||||
param.put("audience", new JSONArray().fluentAdd(tag));
|
||||
|
||||
JSONObject notification = new JSONObject();
|
||||
notification.put("title", notificationTitle);
|
||||
notification.put("body", msgContent);
|
||||
notification.put("click_type", "payload");
|
||||
notification.put("payload", extrasParam);
|
||||
param.put("push_message", notification);
|
||||
|
||||
HttpEntity<JSONObject> httpEntity = new HttpEntity<>(param, headers);
|
||||
JSONObject resp = getRestTemplate().postForObject(GetuiConfig.all, httpEntity, JSONObject.class);
|
||||
if (resp == null) {
|
||||
log.error("个推推送接口请求异常");
|
||||
// throw new MsgException("个推推送接口请求异常");
|
||||
return;
|
||||
}
|
||||
|
||||
if (resp.getIntValue("code") != 0) {
|
||||
log.error("个推推送接口请求异常: {}", resp.getString("msg"));
|
||||
// throw new MsgException(resp.getString("msg"));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendAndroidAll(String notificationTitle, String msgContent, String extrasParam) {
|
||||
init();
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("token", GetuiConfig.token);
|
||||
|
||||
JSONObject param = new JSONObject();
|
||||
param.put("is_async", true);
|
||||
param.put("request_id", UUID.randomUUID().toString().replace("-", ""));
|
||||
param.put("settings", new JSONObject().fluentPut("ttl", 3600000));
|
||||
|
||||
JSONObject tag = new JSONObject()
|
||||
.fluentPut("key", "phone_type")
|
||||
.fluentPut("values", new String[]{"ios"})
|
||||
.fluentPut("opt_type", "and");
|
||||
|
||||
param.put("audience", new JSONArray().fluentAdd(tag));
|
||||
|
||||
JSONObject notification = new JSONObject();
|
||||
notification.put("title", notificationTitle);
|
||||
notification.put("body", msgContent);
|
||||
notification.put("click_type", "payload");
|
||||
notification.put("payload", extrasParam);
|
||||
param.put("push_message", notification);
|
||||
|
||||
HttpEntity<JSONObject> httpEntity = new HttpEntity<>(param, headers);
|
||||
JSONObject resp = getRestTemplate().postForObject(GetuiConfig.all, httpEntity, JSONObject.class);
|
||||
if (resp == null) {
|
||||
log.error("个推推送接口请求异常");
|
||||
// throw new MsgException("个推推送接口请求异常");
|
||||
return;
|
||||
}
|
||||
|
||||
if (resp.getIntValue("code") != 0) {
|
||||
log.error("个推推送接口请求异常: {}", resp.getString("msg"));
|
||||
// throw new MsgException(resp.getString("msg"));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendAllPlatAll(String notificationTitle, String msgContent, String extrasParam) {
|
||||
init();
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("token", GetuiConfig.token);
|
||||
|
||||
JSONObject param = new JSONObject();
|
||||
param.put("is_async", true);
|
||||
param.put("request_id", UUID.randomUUID().toString().replace("-", ""));
|
||||
param.put("settings", new JSONObject().fluentPut("ttl", 3600000));
|
||||
param.put("audience", "all");
|
||||
|
||||
JSONObject notification = new JSONObject();
|
||||
notification.put("title", notificationTitle);
|
||||
notification.put("body", msgContent);
|
||||
notification.put("click_type", "payload");
|
||||
notification.put("payload", extrasParam);
|
||||
param.put("push_message", notification);
|
||||
|
||||
|
||||
HttpEntity<JSONObject> httpEntity = new HttpEntity<>(param, headers);
|
||||
JSONObject resp = getRestTemplate().postForObject(GetuiConfig.all, httpEntity, JSONObject.class);
|
||||
if (resp == null) {
|
||||
log.error("个推推送接口请求异常");
|
||||
throw new MsgException("个推推送接口请求异常");
|
||||
}
|
||||
|
||||
if (resp.getIntValue("code") != 0) {
|
||||
log.error("个推推送接口请求异常: {}", resp.getString("msg"));
|
||||
throw new MsgException(resp.getString("msg"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class HMACSHAUtil {
|
||||
|
||||
/**
|
||||
* 生成 HMACSHA256
|
||||
* @param data 待处理数据
|
||||
* @param key 密钥
|
||||
* @return 加密结果
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String getHMACSHA256(String data, String key){
|
||||
Mac sha256_HMAC;
|
||||
byte[] array = null ;
|
||||
try {
|
||||
sha256_HMAC = Mac.getInstance("HmacSHA256");
|
||||
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
|
||||
sha256_HMAC.init(secret_key);
|
||||
array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte item : array) {
|
||||
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
|
||||
}
|
||||
return sb.toString().toUpperCase();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
public class HttpResult {
|
||||
|
||||
// 响应的状态码
|
||||
private int code;
|
||||
|
||||
// 响应的响应体
|
||||
private String body;
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public HttpResult(int code,String body) {
|
||||
this.code=code;
|
||||
this.body=body;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "HttpResult [code=" + code + ", body=" + body + "]";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,724 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import cn.pluss.platform.wechat.MyX509TrustManager;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.apache.http.*;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.ResponseHandler;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.*;
|
||||
import org.apache.http.client.utils.URIBuilder;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.BasicResponseHandler;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class HttpUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
|
||||
|
||||
// private static CloseableHttpClient httpClient;
|
||||
//
|
||||
// public void APIService() {
|
||||
// // 1 创建HttpClinet,相当于打开浏览器
|
||||
// this.httpClient = HttpClients.createDefault();
|
||||
// }
|
||||
|
||||
|
||||
/**
|
||||
* 带参数的get请求
|
||||
*
|
||||
* @param url
|
||||
* @param map
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResult doGet(String url, Map<String, Object> map) throws Exception {
|
||||
|
||||
// 声明URIBuilder
|
||||
URIBuilder uriBuilder = new URIBuilder(url);
|
||||
|
||||
// 判断参数map是否为非空
|
||||
if (map != null) {
|
||||
// 遍历参数
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
// 设置参数
|
||||
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
|
||||
}
|
||||
}
|
||||
|
||||
// 2 创建httpGet对象,相当于设置url请求地址
|
||||
HttpGet httpGet = new HttpGet(uriBuilder.build());
|
||||
|
||||
// 3 使用HttpClient执行httpGet,相当于按回车,发起请求
|
||||
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = httpClient.execute(httpGet);
|
||||
|
||||
// 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
|
||||
// 状态码
|
||||
// response.getStatusLine().getStatusCode();
|
||||
// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
|
||||
// EntityUtils.toString(response.getEntity(), "UTF-8");
|
||||
HttpResult httpResult = null;
|
||||
// 解析数据封装HttpResult
|
||||
if (response.getEntity() != null) {
|
||||
|
||||
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
|
||||
EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
|
||||
} else {
|
||||
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
|
||||
}
|
||||
|
||||
// 返回
|
||||
return httpResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* 带参数的get请求
|
||||
*
|
||||
* @param url
|
||||
* @param map
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResult doGet(String url, Map<String, String> headers, Map<String, Object> map) throws Exception {
|
||||
|
||||
// 声明URIBuilder
|
||||
URIBuilder uriBuilder = new URIBuilder(url);
|
||||
// 判断参数map是否为非空
|
||||
if (map != null) {
|
||||
// 遍历参数
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
// 设置参数
|
||||
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
|
||||
}
|
||||
}
|
||||
|
||||
// 2 创建httpGet对象,相当于设置url请求地址
|
||||
HttpGet httpGet = new HttpGet(uriBuilder.build());
|
||||
|
||||
// 判断参数headers是否为非空
|
||||
if (headers != null) {
|
||||
// 遍历参数
|
||||
for (Map.Entry<String, String> entry : headers.entrySet()) {
|
||||
// 设置参数
|
||||
httpGet.addHeader(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
// 3 使用HttpClient执行httpGet,相当于按回车,发起请求
|
||||
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = httpClient.execute(httpGet);
|
||||
|
||||
// 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
|
||||
// 状态码
|
||||
// response.getStatusLine().getStatusCode();
|
||||
// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
|
||||
// EntityUtils.toString(response.getEntity(), "UTF-8");
|
||||
HttpResult httpResult = null;
|
||||
// 解析数据封装HttpResult
|
||||
if (response.getEntity() != null) {
|
||||
|
||||
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
|
||||
EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
|
||||
} else {
|
||||
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
|
||||
}
|
||||
|
||||
// 返回
|
||||
return httpResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* 不带参数的get请求
|
||||
*
|
||||
* @param url
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public HttpResult doGet(String url) throws Exception {
|
||||
return doGet(url, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 带参数的post请求
|
||||
*
|
||||
* @param url
|
||||
* @param map
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResult doPost(String url, Map<String, Object> map) throws Exception {
|
||||
// 声明httpPost请求
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
httpPost.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
|
||||
// 判断map不为空
|
||||
if (map != null) {
|
||||
// 声明存放参数的List集合
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
|
||||
// 遍历map,设置参数到list中
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
|
||||
}
|
||||
|
||||
// 创建form表单对象
|
||||
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
|
||||
|
||||
// 把表单对象设置到httpPost中
|
||||
httpPost.setEntity(formEntity);
|
||||
}
|
||||
|
||||
// 使用HttpClient发起请求,返回response
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = httpClient.execute(httpPost);
|
||||
|
||||
// 解析response封装返回对象httpResult
|
||||
HttpResult httpResult = null;
|
||||
if (response.getEntity() != null) {
|
||||
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
|
||||
EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
|
||||
} else {
|
||||
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
|
||||
}
|
||||
|
||||
// 返回结果
|
||||
return httpResult;
|
||||
}
|
||||
|
||||
|
||||
public static String HttpPostWithJson(String url, String json) {
|
||||
String returnValue = "这是默认返回值,接口调用失败";
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
ResponseHandler<String> responseHandler = new BasicResponseHandler();
|
||||
try {
|
||||
//第一步:创建HttpClient对象
|
||||
httpClient = HttpClients.createDefault();
|
||||
|
||||
//第二步:创建httpPost对象
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
|
||||
//第三步:给httpPost设置JSON格式的参数
|
||||
StringEntity requestEntity = new StringEntity(json, StandardCharsets.UTF_8);
|
||||
requestEntity.setContentEncoding("UTF-8");
|
||||
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
|
||||
httpPost.setEntity(requestEntity);
|
||||
|
||||
//第四步:发送HttpPost请求,获取返回值
|
||||
returnValue = httpClient.execute(httpPost, responseHandler); //调接口获取返回值时,必须用此方法
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
//第五步:处理返回值
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 不带参数的post请求
|
||||
*
|
||||
* @param url
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResult doPost(String url) throws Exception {
|
||||
return doPost(url, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 带参数的Put请求
|
||||
*
|
||||
* @param url
|
||||
* @param map
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
|
||||
// 声明httpPost请求
|
||||
HttpPut httpPut = new HttpPut(url);
|
||||
|
||||
// 判断map不为空
|
||||
if (map != null) {
|
||||
// 声明存放参数的List集合
|
||||
List<NameValuePair> params = new ArrayList<>();
|
||||
|
||||
// 遍历map,设置参数到list中
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
|
||||
}
|
||||
|
||||
// 创建form表单对象
|
||||
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
|
||||
|
||||
// 把表单对象设置到httpPost中
|
||||
httpPut.setEntity(formEntity);
|
||||
}
|
||||
|
||||
// 使用HttpClient发起请求,返回response
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = httpClient.execute(httpPut);
|
||||
|
||||
// 解析response封装返回对象httpResult
|
||||
HttpResult httpResult = null;
|
||||
if (response.getEntity() != null) {
|
||||
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
|
||||
EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
|
||||
} else {
|
||||
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
|
||||
}
|
||||
|
||||
// 返回结果
|
||||
return httpResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* 带参数的Delete请求
|
||||
*
|
||||
* @param url
|
||||
* @param map
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public HttpResult doDelete(String url, Map<String, Object> map) throws Exception {
|
||||
|
||||
// 声明URIBuilder
|
||||
URIBuilder uriBuilder = new URIBuilder(url);
|
||||
|
||||
// 判断参数map是否为非空
|
||||
if (map != null) {
|
||||
// 遍历参数
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
// 设置参数
|
||||
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
|
||||
}
|
||||
}
|
||||
|
||||
// 2 创建httpGet对象,相当于设置url请求地址
|
||||
HttpDelete httpDelete = new HttpDelete(uriBuilder.build());
|
||||
|
||||
// 3 使用HttpClient执行httpGet,相当于按回车,发起请求
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = httpClient.execute(httpDelete);
|
||||
|
||||
// 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
|
||||
// 状态码
|
||||
// response.getStatusLine().getStatusCode();
|
||||
// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
|
||||
// EntityUtils.toString(response.getEntity(), "UTF-8");
|
||||
HttpResult httpResult = null;
|
||||
// 解析数据封装HttpResult
|
||||
if (response.getEntity() != null) {
|
||||
httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
|
||||
EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
|
||||
} else {
|
||||
httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
|
||||
}
|
||||
|
||||
// 返回
|
||||
return httpResult;
|
||||
}
|
||||
|
||||
public static String httpPostWithJson(String url, String json) {
|
||||
String returnValue = "接口调用失败";
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
ResponseHandler<String> responseHandler = new BasicResponseHandler();
|
||||
try {
|
||||
//第一步:创建HttpClient对象
|
||||
httpClient = HttpClients.createDefault();
|
||||
|
||||
//第二步:创建httpPost对象
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
|
||||
//第三步:给httpPost设置JSON格式的参数
|
||||
StringEntity requestEntity = new StringEntity(json, "utf-8");
|
||||
requestEntity.setContentEncoding("UTF-8");
|
||||
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
|
||||
httpPost.setEntity(requestEntity);
|
||||
|
||||
//第四步:发送HttpPost请求,获取返回值
|
||||
returnValue = httpClient.execute(httpPost, responseHandler); //调接口获取返回值时,必须用此方法
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
//第五步:处理返回值
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
|
||||
public static String sendPost(String url, String param) {
|
||||
PrintWriter out = null;
|
||||
BufferedReader in = null;
|
||||
String result = "";
|
||||
try {
|
||||
URL realUrl = new URL(url);
|
||||
// 打开和URL之间的连接
|
||||
URLConnection conn = realUrl.openConnection();
|
||||
// 设置通用的请求属性
|
||||
conn.setRequestProperty("accept", "*/*");
|
||||
conn.setRequestProperty("connection", "Keep-Alive");
|
||||
conn.setRequestProperty("user-agent",
|
||||
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||||
// 发送POST请求必须设置如下两行
|
||||
conn.setDoOutput(true);
|
||||
conn.setDoInput(true);
|
||||
// 获取URLConnection对象对应的输出流
|
||||
out = new PrintWriter(conn.getOutputStream());
|
||||
// 发送请求参数
|
||||
out.print(param);
|
||||
// flush输出流的缓冲
|
||||
out.flush();
|
||||
// 定义BufferedReader输入流来读取URL的响应
|
||||
in = new BufferedReader(
|
||||
new InputStreamReader(conn.getInputStream()));
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
result += line;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("发送 POST 请求出现异常!" + e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
//使用finally块来关闭输出流、输入流
|
||||
finally {
|
||||
try {
|
||||
if (out != null) {
|
||||
out.close();
|
||||
}
|
||||
if (in != null) {
|
||||
in.close();
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* post请求(用于key-value格式的参数)
|
||||
*
|
||||
* @param url
|
||||
* @param params
|
||||
* @return
|
||||
*/
|
||||
public static String doPost2(String url, Map<String, Object> params) {
|
||||
|
||||
BufferedReader in = null;
|
||||
try {
|
||||
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
|
||||
// 定义HttpClient
|
||||
HttpClient client = httpClientBuilder.build();
|
||||
// 实例化HTTP方法
|
||||
HttpPost request = new HttpPost();
|
||||
request.setURI(new URI(url));
|
||||
|
||||
//设置参数
|
||||
List<NameValuePair> nvps = new ArrayList<>();
|
||||
for (String name : params.keySet()) {
|
||||
String value = String.valueOf(params.get(name));
|
||||
nvps.add(new BasicNameValuePair(name, value));
|
||||
|
||||
//System.out.println(name +"-"+value);
|
||||
}
|
||||
request.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
|
||||
|
||||
HttpResponse response = client.execute(request);
|
||||
int code = response.getStatusLine().getStatusCode();
|
||||
if (code == 200) { //请求成功
|
||||
in = new BufferedReader(new InputStreamReader(response.getEntity()
|
||||
.getContent(), StandardCharsets.UTF_8));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String line = "";
|
||||
String NL = System.getProperty("line.separator");
|
||||
while ((line = in.readLine()) != null) {
|
||||
sb.append(line).append(NL);
|
||||
}
|
||||
|
||||
in.close();
|
||||
|
||||
return sb.toString();
|
||||
} else { //
|
||||
System.out.println("状态码:" + code);
|
||||
return null;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
|
||||
{
|
||||
JSONObject jsonObject = null;
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
try
|
||||
{
|
||||
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
|
||||
TrustManager[] tm = { new MyX509TrustManager() };
|
||||
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
|
||||
sslContext.init(null, tm, new java.security.SecureRandom());
|
||||
|
||||
// 从上述SSLContext对象中得到SSLSocketFactory对象
|
||||
SSLSocketFactory ssf = sslContext.getSocketFactory();
|
||||
|
||||
URL url = new URL(requestUrl);
|
||||
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
|
||||
httpUrlConn.setSSLSocketFactory(ssf);
|
||||
|
||||
httpUrlConn.setDoOutput(true);
|
||||
httpUrlConn.setDoInput(true);
|
||||
httpUrlConn.setUseCaches(false);
|
||||
|
||||
// 设置请求方式(GET/POST)
|
||||
httpUrlConn.setRequestMethod(requestMethod);
|
||||
|
||||
if ("GET".equalsIgnoreCase(requestMethod))
|
||||
httpUrlConn.connect();
|
||||
|
||||
// 当有数据需要提交时
|
||||
if (null != outputStr)
|
||||
{
|
||||
OutputStream outputStream = httpUrlConn.getOutputStream();
|
||||
// 注意编码格式,防止中文乱码
|
||||
outputStream.write(outputStr.getBytes("UTF-8"));
|
||||
outputStream.close();
|
||||
}
|
||||
|
||||
// 将返回的输入流转换成字符串
|
||||
InputStream inputStream = httpUrlConn.getInputStream();
|
||||
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
|
||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
|
||||
|
||||
String str = null;
|
||||
while ((str = bufferedReader.readLine()) != null)
|
||||
{
|
||||
buffer.append(str);
|
||||
}
|
||||
bufferedReader.close();
|
||||
inputStreamReader.close();
|
||||
// 释放资源
|
||||
inputStream.close();
|
||||
inputStream = null;
|
||||
httpUrlConn.disconnect();
|
||||
jsonObject = JSONObject.parseObject(buffer.toString());
|
||||
}
|
||||
catch (ConnectException ce)
|
||||
{
|
||||
System.out.println("Weixin server connection timed out.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
System.out.println("https request error:{}"+ e);
|
||||
}
|
||||
return jsonObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* post请求(用于请求json格式的参数)
|
||||
*
|
||||
* @param url
|
||||
* @param params
|
||||
* @return
|
||||
*/
|
||||
public static String doPostJson(String url, String params) throws Exception {
|
||||
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
HttpPost httpPost = new HttpPost(url);// 创建httpPost
|
||||
httpPost.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
|
||||
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
|
||||
String charSet = "UTF-8";
|
||||
StringEntity entity = new StringEntity(params, charSet);
|
||||
httpPost.setEntity(entity);
|
||||
CloseableHttpResponse response = null;
|
||||
|
||||
try {
|
||||
|
||||
response = httpclient.execute(httpPost);
|
||||
StatusLine status = response.getStatusLine();
|
||||
int state = status.getStatusCode();
|
||||
if (state == HttpStatus.SC_OK) {
|
||||
HttpEntity responseEntity = response.getEntity();
|
||||
return EntityUtils.toString(responseEntity);
|
||||
} else {
|
||||
System.out.println("请求返回:" + state + "(" + url + ")");
|
||||
}
|
||||
} finally {
|
||||
if (response != null) {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
try {
|
||||
httpclient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static String baiduGET(String url) {
|
||||
try {
|
||||
URL realUrl = new URL(url);
|
||||
// 打开和URL之间的连接
|
||||
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.connect();
|
||||
// 获取所有响应头字段
|
||||
Map<String, List<String>> map = connection.getHeaderFields();
|
||||
// 遍历所有的响应头字段
|
||||
// for (String key : map.keySet()) {
|
||||
// System.err.println(key + "--->" + map.get(key));
|
||||
// }
|
||||
// 定义 BufferedReader输入流来读取URL的响应
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
StringBuilder result = new StringBuilder();
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
result.append(line);
|
||||
}
|
||||
/*
|
||||
* 返回结果示例
|
||||
*/
|
||||
JSONObject jsonObject = JSON.parseObject(result.toString());
|
||||
String access_token = jsonObject.getString("access_token");
|
||||
System.err.println("access_token:====" + access_token);
|
||||
return access_token;
|
||||
} catch (Exception e) {
|
||||
System.err.print("获取token失败!");
|
||||
e.printStackTrace(System.err);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String baiduPOST(String requestUrl, String accessToken, String params) throws Exception {
|
||||
return baiduPOST(requestUrl, accessToken, MediaType.APPLICATION_FORM_URLENCODED_VALUE, params);
|
||||
}
|
||||
|
||||
public static String baiduPOST(String requestUrl, String accessToken, String contentType, String params) throws Exception {
|
||||
String encoding = "UTF-8";
|
||||
if (requestUrl.contains("nlp")) {
|
||||
encoding = "GBK";
|
||||
}
|
||||
return baiduPOST(requestUrl, accessToken, contentType, params, encoding);
|
||||
}
|
||||
|
||||
private static String baiduPOST(String requestUrl, String accessToken, String contentType, String params,
|
||||
String encoding) throws Exception {
|
||||
String url = requestUrl + "?access_token=" + accessToken;
|
||||
return postGeneralUrl(url, contentType, params, encoding);
|
||||
}
|
||||
|
||||
public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
|
||||
throws Exception {
|
||||
URL url = new URL(generalUrl);
|
||||
// 打开和URL之间的连接
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
// 设置通用的请求属性
|
||||
connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType);
|
||||
connection.setRequestProperty("Connection", "Keep-Alive");
|
||||
connection.setUseCaches(false);
|
||||
connection.setDoOutput(true);
|
||||
connection.setDoInput(true);
|
||||
// 得到请求的输出流对象
|
||||
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
|
||||
out.write(params.getBytes(encoding));
|
||||
out.flush();
|
||||
out.close();
|
||||
|
||||
// 建立实际的连接
|
||||
connection.connect();
|
||||
// 获取所有响应头字段
|
||||
Map<String, List<String>> headers = connection.getHeaderFields();
|
||||
// 遍历所有的响应头字段
|
||||
for (String key : headers.keySet()) {
|
||||
System.err.println(key + "--->" + headers.get(key));
|
||||
}
|
||||
// 定义 BufferedReader输入流来读取URL的响应
|
||||
BufferedReader in;
|
||||
in = new BufferedReader(
|
||||
new InputStreamReader(connection.getInputStream(), encoding));
|
||||
StringBuilder result = new StringBuilder();
|
||||
String getLine;
|
||||
while ((getLine = in.readLine()) != null) {
|
||||
result.append(getLine);
|
||||
}
|
||||
in.close();
|
||||
System.err.println("result:" + result);
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
|
||||
public static String GET(String url) {
|
||||
try {
|
||||
URL realUrl = new URL(url);
|
||||
// 打开和URL之间的连接
|
||||
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.connect();
|
||||
// 获取所有响应头字段
|
||||
Map<String, List<String>> map = connection.getHeaderFields();
|
||||
// 遍历所有的响应头字段
|
||||
for (String key : map.keySet()) {
|
||||
System.err.println(key + "--->" + map.get(key));
|
||||
}
|
||||
// 定义 BufferedReader输入流来读取URL的响应
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
StringBuilder result = new StringBuilder();
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
result.append(line);
|
||||
}
|
||||
return result.toString();
|
||||
} catch (Exception e) {
|
||||
System.err.print("获取token失败!");
|
||||
e.printStackTrace(System.err);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* @author DJH
|
||||
* 网络请求相关工具类
|
||||
*/
|
||||
public class HttpUtils {
|
||||
|
||||
/**
|
||||
* 判断是不是IOS app
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public static boolean isIOS(HttpServletRequest request) {
|
||||
String userAgent = request.getHeader("user-agent");
|
||||
|
||||
/**
|
||||
* 仅适用于收银呗app
|
||||
*/
|
||||
return userAgent.contains("iOS");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.NoSuchProviderException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
public class HttpsMain {
|
||||
/**
|
||||
* 是否dev环境
|
||||
*/
|
||||
public static final boolean isDev = false;
|
||||
/**
|
||||
* 是否开启验签
|
||||
*/
|
||||
public static final boolean isSign = true;
|
||||
|
||||
/**
|
||||
* 身份证
|
||||
*/
|
||||
public static String certNo = "512734195005252263";
|
||||
|
||||
/**
|
||||
* 商户ID
|
||||
*/
|
||||
public static String merchantId = "226801000000000261290";
|
||||
|
||||
/**
|
||||
* 渠道
|
||||
*/
|
||||
public static final String channel = "MYBANK";
|
||||
|
||||
/**
|
||||
* 短信验证码
|
||||
*/
|
||||
public static final String smsCode = "888888";
|
||||
|
||||
/**
|
||||
* 币种
|
||||
*/
|
||||
public static final String currencyCode = "156";
|
||||
|
||||
//sit环境url
|
||||
// public static String reqUrl = "https://fcsupergw.dl.alipaydev.com/open/api/common/requestasync.htm";
|
||||
|
||||
// public static String uploadUrl = "https://fcsupergwlite.dl.alipaydev.com/ant/mybank/merchantprod/merchant/uploadphoto.htm";
|
||||
/**
|
||||
* partner
|
||||
*/
|
||||
public static String IsvOrgId = "202210000000000001025";
|
||||
|
||||
/**
|
||||
* 联调阶段使用1.0.0的版本,上线前需要根据情况重新配置
|
||||
*/
|
||||
public static String version = "1.0.0";
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
}
|
||||
|
||||
public static String httpsReq(String reqUrl, String param) throws NoSuchAlgorithmException,
|
||||
NoSuchProviderException, IOException,
|
||||
KeyManagementException {
|
||||
URL url = new URL(reqUrl);
|
||||
HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
|
||||
httpsConn.setHostnameVerifier(new HostnameVerifier() {
|
||||
public boolean verify(String paramString, SSLSession paramSSLSession) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
//创建SSLContext对象,并使用我们指定的信任管理器初始化
|
||||
TrustManager tm = new X509TrustManager() {
|
||||
public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate,
|
||||
String paramString) throws CertificateException {
|
||||
}
|
||||
|
||||
public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate,
|
||||
String paramString) throws CertificateException {
|
||||
}
|
||||
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
|
||||
sslContext.init(null, new TrustManager[] { tm }, new java.security.SecureRandom());
|
||||
|
||||
//从上述SSLContext对象中得到SSLSocketFactory对象
|
||||
SSLSocketFactory ssf = sslContext.getSocketFactory();
|
||||
|
||||
//创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
|
||||
httpsConn.setSSLSocketFactory(ssf);
|
||||
|
||||
httpsConn.setDoOutput(true);
|
||||
httpsConn.setRequestMethod("POST");
|
||||
httpsConn.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
|
||||
httpsConn.setRequestProperty("Content-Length", String.valueOf(param.length()));
|
||||
|
||||
OutputStreamWriter out = new OutputStreamWriter(httpsConn.getOutputStream(), "UTF-8");
|
||||
out.write(param);
|
||||
out.flush();
|
||||
out.close();
|
||||
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(
|
||||
httpsConn.getInputStream(), "UTF-8"));
|
||||
String tempLine = "";
|
||||
StringBuffer resultBuffer = new StringBuffer();
|
||||
while ((tempLine = reader.readLine()) != null) {
|
||||
resultBuffer.append(tempLine).append(System.getProperty("line.separator"));
|
||||
}
|
||||
return resultBuffer.toString();
|
||||
}
|
||||
|
||||
public static String httpReq(String param) throws NoSuchAlgorithmException,
|
||||
NoSuchProviderException, IOException,
|
||||
KeyManagementException {
|
||||
URL url = new URL("http://fcsupergw.d1003.mayibank.net/open/api/common/request.htm");
|
||||
HttpURLConnection httpsConn = (HttpURLConnection) url.openConnection();
|
||||
|
||||
httpsConn.setDoOutput(true);
|
||||
httpsConn.setRequestMethod("POST");
|
||||
httpsConn.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
|
||||
httpsConn.setRequestProperty("Content-Length", String.valueOf(param.length()));
|
||||
|
||||
OutputStreamWriter out = new OutputStreamWriter(httpsConn.getOutputStream(), "UTF-8");
|
||||
out.write(param);
|
||||
out.flush();
|
||||
out.close();
|
||||
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(
|
||||
httpsConn.getInputStream(), "UTF-8"));
|
||||
String tempLine = "";
|
||||
StringBuffer resultBuffer = new StringBuffer();
|
||||
while ((tempLine = reader.readLine()) != null) {
|
||||
resultBuffer.append(tempLine).append(System.getProperty("line.separator"));
|
||||
}
|
||||
return resultBuffer.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface IPush {
|
||||
|
||||
/**
|
||||
* 推送到安卓
|
||||
*
|
||||
* @param alias id数组
|
||||
* @param notificationTitle 推送通知标题
|
||||
* @param msgContent 推送内容
|
||||
* @param extrasParam 附加参数
|
||||
*/
|
||||
void sendAndroidByAlias(List<String> alias, String notificationTitle, String msgContent, String extrasParam);
|
||||
|
||||
/**
|
||||
* 推送到iphone
|
||||
*
|
||||
* @param alias id数组
|
||||
* @param notificationTitle 推送通知标题
|
||||
* @param msgContent 推送内容
|
||||
* @param extrasParam 附加参数
|
||||
*/
|
||||
void sendIOSByAlias(List<String> alias, String notificationTitle, String msgContent, String extrasParam);
|
||||
|
||||
/**
|
||||
* 推送到全部,android & iOS
|
||||
*
|
||||
* @param alias id数组
|
||||
* @param notificationTitle 推送通知标题
|
||||
* @param msgContent 推送内容
|
||||
* @param extrasParam 附加参数
|
||||
*/
|
||||
void sendAllPlatByAlias(List<String> alias, String notificationTitle, String msgContent, String extrasParam);
|
||||
|
||||
/**
|
||||
* 推送到全部iphone
|
||||
*
|
||||
* @param notificationTitle 推送通知标题
|
||||
* @param msgContent 推送通知内容
|
||||
* @param extrasParam 附加参数
|
||||
*/
|
||||
void sendIOSAll(String notificationTitle, String msgContent, String extrasParam);
|
||||
|
||||
/**
|
||||
* 推送到全部安卓机
|
||||
*
|
||||
* @param notificationTitle 推送通知标题
|
||||
* @param msgContent 推送通知内容
|
||||
* @param extrasParam 附加参数
|
||||
*/
|
||||
void sendAndroidAll(String notificationTitle, String msgContent, String extrasParam);
|
||||
|
||||
/**
|
||||
* 推送到所有人
|
||||
*/
|
||||
void sendAllPlatAll(String notificationTitle, String msgContent, String extrasParam);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.Base64;
|
||||
|
||||
public class ImageUtils {
|
||||
|
||||
/**
|
||||
* 通过图片的url获取图片的base64字符串
|
||||
*
|
||||
* @param imgUrl 图片url
|
||||
* @return 返回图片base64的字符串
|
||||
*/
|
||||
public static String image2Base64(String imgUrl) {
|
||||
URL url = null;
|
||||
InputStream is = null;
|
||||
ByteArrayOutputStream outStream = null;
|
||||
HttpURLConnection httpUrl = null;
|
||||
|
||||
try {
|
||||
url = new URL(imgUrl);
|
||||
httpUrl = (HttpURLConnection) url.openConnection();
|
||||
httpUrl.connect();
|
||||
httpUrl.getInputStream();
|
||||
is = httpUrl.getInputStream();
|
||||
outStream = new ByteArrayOutputStream();
|
||||
|
||||
//创建一个Buffer字符串
|
||||
byte[] buffer = new byte[1024];
|
||||
|
||||
//每次读取的字符串长度,如果为-1,代表全部读取完毕
|
||||
int len = 0;
|
||||
|
||||
//使用一个输入流从buffer里把数据读取出来
|
||||
while ((len = is.read(buffer)) != -1) {
|
||||
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
|
||||
// 对字节数组Base64编码
|
||||
return Base64.getEncoder().encodeToString(outStream.toByteArray());
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (is != null) {
|
||||
try {
|
||||
is.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
if (outStream != null) {
|
||||
try {
|
||||
outStream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
if (httpUrl != null) {
|
||||
httpUrl.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
return imgUrl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import cn.pluss.platform.exception.MsgException;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.aliyuncs.geoip.model.v20200101.DescribeIpv4LocationResponse;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* IP相关接口
|
||||
*/
|
||||
public class IpUtils {
|
||||
|
||||
private static final String UNKNOWN = "unknown";
|
||||
private static final String LOCALHOST = "127.0.0.1";
|
||||
private static final String SEPARATOR = ",";
|
||||
|
||||
public static String getIpAddr(HttpServletRequest request) {
|
||||
System.out.println(request);
|
||||
String ipAddress;
|
||||
try {
|
||||
ipAddress = request.getHeader("x-forwarded-for");
|
||||
if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
|
||||
ipAddress = request.getRemoteAddr();
|
||||
if (LOCALHOST.equals(ipAddress)) {
|
||||
InetAddress inet = null;
|
||||
try {
|
||||
inet = InetAddress.getLocalHost();
|
||||
ipAddress = inet.getHostAddress();
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
|
||||
// "***.***.***.***".length()
|
||||
if (ipAddress != null && ipAddress.length() > 15) {
|
||||
if (ipAddress.indexOf(SEPARATOR) > 0) {
|
||||
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
ipAddress = "";
|
||||
}
|
||||
return ipAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为公网ip
|
||||
* @return
|
||||
*/
|
||||
public static boolean isWAN(String ip) {
|
||||
if (StringUtils.isEmpty(ip)) {
|
||||
throw new MsgException("ip不能为空");
|
||||
}
|
||||
|
||||
if (ip.startsWith("192.168")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ip.startsWith("172.16")) {
|
||||
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 高德根据ip获取经纬度
|
||||
* @param address
|
||||
* @return
|
||||
*/
|
||||
public static Map<String,String> getLocationByAddress(String address){
|
||||
Map<String,String> result = new HashMap<>(2);
|
||||
String url = "https://restapi.amap.com/v3/geocode/geo?address="+address+"&key=4d6b5117916ada2b52452d6a04483ac7";
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
JSONObject forObject = restTemplate.getForObject(url, JSONObject.class);
|
||||
if("1".equals(forObject.getString("status"))){
|
||||
JSONArray geocodes = forObject.getJSONArray("geocodes");
|
||||
String location = geocodes.getJSONObject(0).getString("location");
|
||||
result.put("y",location.split(",")[0]);
|
||||
result.put("x",location.split(",")[1]);
|
||||
return result;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getIpLoactionAddress(DescribeIpv4LocationResponse response) {
|
||||
if(response == null){
|
||||
return null;
|
||||
}
|
||||
StringBuffer sb = new StringBuffer();
|
||||
if(StringUtil.isNotEmpty(response.getProvince())){
|
||||
sb.append(response.getProvince() + "-");
|
||||
}
|
||||
if(StringUtil.isNotEmpty(response.getCity())){
|
||||
sb.append(response.getCity() + "-");
|
||||
}
|
||||
if(StringUtil.isNotEmpty(response.getCounty())){
|
||||
sb.append(response.getCounty() + "-");
|
||||
}
|
||||
if(sb.length() == 0){
|
||||
return null;
|
||||
}
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import cn.jiguang.common.resp.APIConnectionException;
|
||||
import cn.jiguang.common.resp.APIRequestException;
|
||||
import cn.jpush.api.JPushClient;
|
||||
import cn.jpush.api.push.PushResult;
|
||||
import cn.jpush.api.push.model.Message;
|
||||
import cn.jpush.api.push.model.Options;
|
||||
import cn.jpush.api.push.model.Platform;
|
||||
import cn.jpush.api.push.model.PushPayload;
|
||||
import cn.jpush.api.push.model.audience.Audience;
|
||||
import cn.jpush.api.push.model.notification.AndroidNotification;
|
||||
import cn.jpush.api.push.model.notification.IosNotification;
|
||||
import cn.jpush.api.push.model.notification.Notification;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 极光推送
|
||||
*/
|
||||
@Slf4j
|
||||
public class JGPushUtil implements IPush {
|
||||
|
||||
private static IPush instance;
|
||||
|
||||
private JGPushUtil() {
|
||||
}
|
||||
|
||||
public static IPush getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new JGPushUtil();
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
private final static String APP_KEY = "46a8063491a3a1e89ec9254f";
|
||||
|
||||
private final static String MASTER_SECRET = "ee279316fb21f2ec65390768";
|
||||
|
||||
private static JPushClient jpushClient;
|
||||
|
||||
public static JPushClient getJPushClient() {
|
||||
if (jpushClient == null) {
|
||||
jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
|
||||
}
|
||||
|
||||
return jpushClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendAndroidByAlias(List<String> alias, String notificationTitle, String msgContent, String extrasParam) {
|
||||
PushPayload pushPayload = getPayLoadBuilder(notificationTitle, msgContent, extrasParam)
|
||||
.setPlatform(Platform.android())
|
||||
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
|
||||
.setAudience(Audience.alias(alias))
|
||||
//jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
|
||||
.setNotification(Notification.newBuilder()
|
||||
//指定当前推送的android通知
|
||||
.addPlatformNotification(getAndroidNotification(notificationTitle, msgContent, extrasParam))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
sendAndResultHandle(pushPayload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendIOSByAlias(List<String> alias, String notificationTitle, String msgContent, String extrasParam) {
|
||||
PushPayload pushPayload = getPayLoadBuilder(notificationTitle, msgContent, extrasParam)
|
||||
.setPlatform(Platform.ios())
|
||||
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
|
||||
.setAudience(Audience.alias(alias))
|
||||
// iOS的由apns服务器下发,Winphone的由mpns下发
|
||||
.setNotification(Notification.newBuilder()
|
||||
//指定当前推送的android通知
|
||||
.addPlatformNotification(getIOSNotification(notificationTitle, msgContent, extrasParam))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
sendAndResultHandle(pushPayload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendAllPlatByAlias(List<String> alias, String notificationTitle, String msgContent, String extrasParam) {
|
||||
PushPayload pushPayload = getPayLoadBuilder(notificationTitle, msgContent, extrasParam)
|
||||
.setPlatform(Platform.android_ios())
|
||||
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
|
||||
.setAudience(Audience.alias(alias))
|
||||
.setNotification(Notification.newBuilder()
|
||||
.addPlatformNotification(getIOSNotification(notificationTitle, msgContent, extrasParam))
|
||||
.addPlatformNotification(getAndroidNotification(notificationTitle, msgContent, extrasParam))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
sendAndResultHandle(pushPayload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendIOSAll(String notificationTitle, String msgContent, String extrasParam) {
|
||||
PushPayload pushPayload = getPayLoadBuilder(notificationTitle, msgContent, extrasParam)
|
||||
.setPlatform(Platform.ios())
|
||||
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
|
||||
.setAudience(Audience.all())
|
||||
// iOS的由apns服务器下发,Winphone的由mpns下发
|
||||
.setNotification(Notification.newBuilder()
|
||||
.addPlatformNotification(getIOSNotification(notificationTitle, msgContent, extrasParam))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
sendAndResultHandle(pushPayload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendAndroidAll(String notificationTitle, String msgContent, String extrasParam) {
|
||||
PushPayload pushPayload = getPayLoadBuilder(notificationTitle, msgContent, extrasParam)
|
||||
.setPlatform(Platform.android())
|
||||
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
|
||||
.setAudience(Audience.all())
|
||||
.setNotification(Notification.newBuilder()
|
||||
.addPlatformNotification(getAndroidNotification(notificationTitle, msgContent, extrasParam))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
sendAndResultHandle(pushPayload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendAllPlatAll(String notificationTitle, String msgContent, String extrasParam) {
|
||||
PushPayload pushPayload = getPayLoadBuilder(notificationTitle, msgContent, extrasParam)
|
||||
.setPlatform(Platform.android_ios())
|
||||
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
|
||||
.setAudience(Audience.all())
|
||||
.setNotification(Notification.newBuilder()
|
||||
.addPlatformNotification(getIOSNotification(notificationTitle, msgContent, extrasParam))
|
||||
.addPlatformNotification(getAndroidNotification(notificationTitle, msgContent, extrasParam))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
sendAndResultHandle(pushPayload);
|
||||
}
|
||||
|
||||
|
||||
private AndroidNotification getAndroidNotification(String notificationTitle, String msgContent, String extrasParam) {
|
||||
return AndroidNotification.newBuilder()
|
||||
.setAlert(msgContent)
|
||||
.setTitle(notificationTitle)
|
||||
// Notification.DEFAULT_ALL = -1
|
||||
// Notification.DEFAULT_VIBRATE = 2
|
||||
// Notification.DEFAULT_LIGHTS = 4
|
||||
.setAlertType(-1)
|
||||
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
|
||||
.addExtra("url", extrasParam)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取iOS的通知构造体
|
||||
*
|
||||
* @param notificationTitle 标题
|
||||
* @param msgContent 内容
|
||||
* @param extrasParam 附加参数
|
||||
* @return
|
||||
*/
|
||||
private IosNotification getIOSNotification(String notificationTitle, String msgContent, String extrasParam) {
|
||||
return IosNotification.newBuilder()
|
||||
//传一个IosAlert对象,指定apns title、title、subtitle等
|
||||
.setAlert(msgContent)
|
||||
.setMutableContent(true)
|
||||
//直接传alert
|
||||
//此项是指定此推送的badge自动加1
|
||||
.incrBadge(1)
|
||||
//此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
|
||||
// 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
|
||||
.setSound("sound.caf")
|
||||
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
|
||||
.addExtra("url", extrasParam)
|
||||
//此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
|
||||
//取消此注释,消息推送时ios将无法在锁屏情况接收
|
||||
// .setContentAvailable(true)
|
||||
.build();
|
||||
}
|
||||
|
||||
private PushPayload.Builder getPayLoadBuilder(String notificationTitle, String msgContent, String extrasParam) {
|
||||
return PushPayload.newBuilder()
|
||||
//Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
|
||||
// sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
|
||||
.setMessage(Message.newBuilder()
|
||||
.setMsgContent(msgContent)
|
||||
.setTitle(notificationTitle)
|
||||
.addExtra("5", extrasParam)
|
||||
.build())
|
||||
.setOptions(Options.newBuilder()
|
||||
//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
|
||||
.setApnsProduction(MobPushUtil.PROD == 1)
|
||||
//此字段是给开发者自己给推送编号,方便推送者分辨推送记录
|
||||
.setSendno(1)
|
||||
.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送推送并对结果进行处理
|
||||
* @param pushPayload
|
||||
*/
|
||||
void sendAndResultHandle(PushPayload pushPayload) {
|
||||
try {
|
||||
PushResult pushResult = getJPushClient().sendPush(pushPayload);
|
||||
// System.out.println("[极光推送] PushResult result is " + pushResult);
|
||||
log.info("[极光推送] PushResult result is " + pushResult);
|
||||
} catch (APIConnectionException e) {
|
||||
log.error("[极光推送] Connection error. Should retry later. {}", e.toString());
|
||||
} catch (APIRequestException e) {
|
||||
System.out.println("[极光推送] " + e.getErrorMessage());
|
||||
// log.error("[极光推送]Error response from JPush server. Should review and fix it. ", e);
|
||||
log.info("[极光推送]HTTP Status: " + e.getStatus());
|
||||
log.info("[极光推送]Error Code: " + e.getErrorCode());
|
||||
log.info("[极光推送]Error Message: " + e.getErrorMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
|
||||
import cn.jiguang.common.resp.APIConnectionException;
|
||||
import cn.jiguang.common.resp.APIRequestException;
|
||||
import cn.jpush.api.JPushClient;
|
||||
import cn.jpush.api.push.PushResult;
|
||||
import cn.jpush.api.push.model.Message;
|
||||
import cn.jpush.api.push.model.Options;
|
||||
import cn.jpush.api.push.model.Platform;
|
||||
import cn.jpush.api.push.model.PushPayload;
|
||||
import cn.jpush.api.push.model.audience.Audience;
|
||||
import cn.jpush.api.push.model.notification.AndroidNotification;
|
||||
import cn.jpush.api.push.model.notification.IosNotification;
|
||||
import cn.jpush.api.push.model.notification.Notification;
|
||||
import cn.jpush.api.schedule.ScheduleResult;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class JpushClientUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(JpushClientUtil.class);
|
||||
|
||||
private final static String APPKER = "46a8063491a3a1e89ec9254f";
|
||||
|
||||
private final static String MASTERSECRET = "ee279316fb21f2ec65390768";
|
||||
|
||||
private static JPushClient jPushClient = new JPushClient(MASTERSECRET,APPKER);
|
||||
|
||||
private JpushClientUtil() {
|
||||
throw new AssertionError("不能产生该对象");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<String> alias = new ArrayList<>();
|
||||
//alias.add("276");
|
||||
alias.add("1791");
|
||||
//alias.add("896");
|
||||
//sendToRegistrationId(alias, "测试", "测试信息", "测试信息", "https://www.baidu.com");
|
||||
|
||||
// sendToAllAndroid("测试Android", "测试Android", "测试Android", "https://www.baidu.com");
|
||||
// sendToAllIos("测试Ios", "测试信息Ios", "测试信息Ios", "https://www.baidu.com");
|
||||
// sendToAll("测试全平台", "测试信息全平台", "测试信息全平台", "https://www.baidu.com");
|
||||
int a = sendToRegistrationId2(alias, "收银呗到账通知233", "收银呗到账通知", "收银呗到账0.01元", "3","2018-11-23 17:05:25");
|
||||
System.out.println(a);
|
||||
System.out.println("发送成功!");
|
||||
}
|
||||
|
||||
|
||||
|
||||
//推送给设备标识参数的用户
|
||||
public static int sendToRegistrationId( List<String> alias,String notification_title, String msg_title, String msg_content, String extrasparam) {
|
||||
JPushClient jPushClient = new JPushClient(MASTERSECRET,APPKER);
|
||||
int result = 0;
|
||||
try {
|
||||
PushPayload pushPayload= JpushClientUtil.buildPushObject_all_alias_alertWithTitle(alias,notification_title,msg_title,msg_content,extrasparam);
|
||||
PushResult pushResult=jPushClient.sendPush(pushPayload);
|
||||
if(pushResult.getResponseCode()==200){
|
||||
result=1;
|
||||
}
|
||||
logger.info("[极光推送]PushResult result is " + pushResult);
|
||||
} catch (APIConnectionException e) {
|
||||
logger.error("[极光推送]Connection error. Should retry later. ", e);
|
||||
} catch (APIRequestException e) {
|
||||
logger.error("[极光推送]Error response from JPush server. Should review and fix it. ", e);
|
||||
logger.info("[极光推送]HTTP Status: " + e.getStatus());
|
||||
logger.info("[极光推送]Error Code: " + e.getErrorCode());
|
||||
logger.info("[极光推送]Error Message: " + e.getErrorMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// 推送给设备标识参数的用户(定时)
|
||||
public static int sendToRegistrationId2( List<String> alias,String notification_title, String msg_title, String msg_content, String extrasparam, String time) {
|
||||
JPushClient jPushClient = new JPushClient(MASTERSECRET,APPKER);
|
||||
// logger.error(JSONObject.toJSONString(jPushClient));
|
||||
int result=0;
|
||||
try {
|
||||
PushPayload pushPayload= JpushClientUtil.buildPushObject_all_alias_alertWithTitle(alias,notification_title,msg_title,msg_content,extrasparam);
|
||||
PushResult pushResult=jPushClient.sendPush(pushPayload);
|
||||
if(pushResult.getResponseCode()==200){
|
||||
result=1;
|
||||
}
|
||||
logger.info("[极光推送]ScheduleResult result is " + pushResult);
|
||||
} catch (APIConnectionException e) {
|
||||
logger.error("[极光推送]Connection error. Should retry later. ", e);
|
||||
e.printStackTrace();
|
||||
} catch (APIRequestException e) {
|
||||
e.printStackTrace();
|
||||
logger.error("[极光推送]Error response from JPush server. Should review and fix it. ", e);
|
||||
logger.info("[极光推送]HTTP Status: " + e.getStatus());
|
||||
logger.info("[极光推送]Error Code: " + e.getErrorCode());
|
||||
logger.info("[极光推送]Error Message: " + e.getErrorMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
//发送给所有安卓用户
|
||||
public static int sendToAllAndroid( String notification_title, String msg_title, String msg_content, String extrasparam) {
|
||||
int result = 0;
|
||||
try {
|
||||
PushPayload pushPayload= JpushClientUtil.buildPushObject_android_all_alertWithTitle(notification_title,msg_title,msg_content,extrasparam);
|
||||
PushResult pushResult=jPushClient.sendPush(pushPayload);
|
||||
if(pushResult.getResponseCode()==200){
|
||||
result=1;
|
||||
}
|
||||
logger.info("[极光推送]PushResult result is " + pushResult);
|
||||
} catch (APIConnectionException e) {
|
||||
logger.error("[极光推送]Connection error. Should retry later. ", e);
|
||||
} catch (APIRequestException e) {
|
||||
logger.error("[极光推送]Error response from JPush server. Should review and fix it. ", e);
|
||||
logger.info("[极光推送]HTTP Status: " + e.getStatus());
|
||||
logger.info("[极光推送]Error Code: " + e.getErrorCode());
|
||||
logger.info("[极光推送]Error Message: " + e.getErrorMessage());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// 发送给所有IOS用户
|
||||
public static int sendToAllIos(String notification_title, String msg_title, String msg_content, String extrasparam) {
|
||||
int result = 0;
|
||||
try {
|
||||
PushPayload pushPayload= JpushClientUtil.buildPushObject_ios_all_alertWithTitle(notification_title,msg_title,msg_content,extrasparam);
|
||||
PushResult pushResult=jPushClient.sendPush(pushPayload);
|
||||
if(pushResult.getResponseCode()==200){
|
||||
result=1;
|
||||
}
|
||||
logger.info("[极光推送]PushResult result is " + pushResult);
|
||||
} catch (APIConnectionException e) {
|
||||
logger.error("[极光推送]Connection error. Should retry later. ", e);
|
||||
} catch (APIRequestException e) {
|
||||
logger.error("[极光推送]Error response from JPush server. Should review and fix it. ", e);
|
||||
logger.info("[极光推送]HTTP Status: " + e.getStatus());
|
||||
logger.info("[极光推送]Error Code: " + e.getErrorCode());
|
||||
logger.info("[极光推送]Error Message: " + e.getErrorMessage());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// 发送给所有用户
|
||||
public static int sendToAll( String notification_title, String msg_title, String msg_content, String extrasparam) {
|
||||
int result = 0;
|
||||
try {
|
||||
PushPayload pushPayload= JpushClientUtil.buildPushObject_android_and_ios(notification_title,msg_title,msg_content,extrasparam);
|
||||
PushResult pushResult=jPushClient.sendPush(pushPayload);
|
||||
if(pushResult.getResponseCode()==200){
|
||||
result=1;
|
||||
}
|
||||
logger.info("[极光推送]PushResult result is " + pushResult);
|
||||
} catch (APIConnectionException e) {
|
||||
logger.error("[极光推送]Connection error. Should retry later. ", e);
|
||||
} catch (APIRequestException e) {
|
||||
logger.error("[极光推送]Error response from JPush server. Should review and fix it. ", e);
|
||||
logger.info("[极光推送]HTTP Status: " + e.getStatus());
|
||||
logger.info("[极光推送]Error Code: " + e.getErrorCode());
|
||||
logger.info("[极光推送]Error Message: " + e.getErrorMessage());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
//发送给所有用户(定时推送)
|
||||
public static int sendToAll2( String notification_title, String msg_title, String msg_content, String extrasparam, String time) {
|
||||
int result = 0;
|
||||
try {
|
||||
PushPayload pushPayload= JpushClientUtil.buildPushObject_android_and_ios(notification_title,msg_title,msg_content,extrasparam);
|
||||
ScheduleResult scheduleResult=jPushClient.createSingleSchedule("测试", time, pushPayload, MASTERSECRET,APPKER);
|
||||
if(scheduleResult.getResponseCode()==200){
|
||||
result=1;
|
||||
}
|
||||
logger.info("[极光推送]scheduleResult result is " + scheduleResult);
|
||||
} catch (APIConnectionException e) {
|
||||
logger.error("[极光推送]Connection error. Should retry later. ", e);
|
||||
} catch (APIRequestException e) {
|
||||
logger.error("[极光推送]Error response from JPush server. Should review and fix it. ", e);
|
||||
logger.info("[极光推送]HTTP Status: " + e.getStatus());
|
||||
logger.info("[极光推送]Error Code: " + e.getErrorCode());
|
||||
logger.info("[极光推送]Error Message: " + e.getErrorMessage());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static PushPayload buildPushObject_android_and_ios(String notification_title, String msg_title, String msg_content, String extrasparam) {
|
||||
return PushPayload.newBuilder()
|
||||
.setPlatform(Platform.android_ios())
|
||||
.setAudience(Audience.all())
|
||||
.setNotification(Notification.newBuilder()
|
||||
.setAlert(msg_content)
|
||||
.addPlatformNotification(AndroidNotification.newBuilder()
|
||||
.setAlert(msg_content)
|
||||
.setTitle(notification_title)
|
||||
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
|
||||
.addExtra("url",extrasparam)
|
||||
.build()
|
||||
)
|
||||
.addPlatformNotification(IosNotification.newBuilder()
|
||||
//传一个IosAlert对象,指定apns title、title、subtitle等
|
||||
.setAlert(msg_content)
|
||||
//直接传alert
|
||||
//此项是指定此推送的badge自动加1
|
||||
.incrBadge(1)
|
||||
//此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
|
||||
// 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
|
||||
.setSound("sound.caf")
|
||||
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
|
||||
.addExtra("url",extrasparam)
|
||||
//此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
|
||||
// .setContentAvailable(true)
|
||||
|
||||
.build()
|
||||
)
|
||||
.build()
|
||||
)
|
||||
//Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
|
||||
// sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
|
||||
.setMessage(Message.newBuilder()
|
||||
.setMsgContent(msg_content)
|
||||
.setTitle(msg_title)
|
||||
.addExtra("url",extrasparam)
|
||||
.build())
|
||||
|
||||
.setOptions(Options.newBuilder()
|
||||
//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
|
||||
.setApnsProduction(true)
|
||||
//此字段是给开发者自己给推送编号,方便推送者分辨推送记录
|
||||
.setSendno(1)
|
||||
//此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
|
||||
.setTimeToLive(86400)
|
||||
.build()
|
||||
)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static PushPayload buildPushObject_all_alias_alertWithTitle(List<String> alias,String notification_title, String msg_title, String msg_content, String extrasparam) {
|
||||
logger.error("===extrasparam======"+extrasparam);
|
||||
//创建一个IosAlert对象,可指定APNs的alert、title等字段
|
||||
//IosAlert iosAlert = IosAlert.newBuilder().setTitleAndBody("title", "alert body").build();
|
||||
|
||||
return PushPayload.newBuilder()
|
||||
//指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
|
||||
.setPlatform(Platform.all())
|
||||
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
|
||||
.setAudience(Audience.alias(alias))
|
||||
// .setAudience(Audience.registrationId(registrationId))
|
||||
//jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
|
||||
.setNotification(Notification.newBuilder()
|
||||
//指定当前推送的android通知
|
||||
.addPlatformNotification(AndroidNotification.newBuilder()
|
||||
.setAlert(msg_content)
|
||||
.setTitle(notification_title)
|
||||
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
|
||||
.addExtra("url",extrasparam)
|
||||
.build())
|
||||
|
||||
/*.setNotification(Notification.newBuilder()
|
||||
.addPlatformNotification(IosNotification.newBuilder()
|
||||
.setAlert("提示")
|
||||
.setBadge(5)
|
||||
.setSound("happy")
|
||||
.addExtra("url", "JPush")
|
||||
.build())
|
||||
.build())*/
|
||||
|
||||
//指定当前推送的iOS通知
|
||||
.addPlatformNotification(IosNotification.newBuilder()
|
||||
//传一个IosAlert对象,指定apns title、title、subtitle等
|
||||
.setAlert(msg_content)
|
||||
//.setMutableContent(true)
|
||||
//直接传alert
|
||||
//此项是指定此推送的badge自动加1
|
||||
.incrBadge(1)
|
||||
//此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
|
||||
// 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
|
||||
.setSound("sound.caf")
|
||||
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
|
||||
.addExtra("url",extrasparam)
|
||||
//此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
|
||||
//取消此注释,消息推送时ios将无法在锁屏情况接收
|
||||
// .setContentAvailable(true)
|
||||
.build())
|
||||
.build())
|
||||
//Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
|
||||
// sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
|
||||
.setMessage(Message.newBuilder()
|
||||
.setMsgContent(msg_content)
|
||||
.setTitle(msg_title)
|
||||
.addExtra("5",extrasparam)
|
||||
.build())
|
||||
.setOptions(Options.newBuilder()
|
||||
//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
|
||||
.setApnsProduction(true)
|
||||
//此字段是给开发者自己给推送编号,方便推送者分辨推送记录
|
||||
.setSendno(1)
|
||||
//此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天;
|
||||
.setTimeToLive(86400)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static PushPayload buildPushObject_android_all_alertWithTitle(String notification_title, String msg_title, String msg_content, String extrasparam) {
|
||||
return PushPayload.newBuilder()
|
||||
//指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
|
||||
.setPlatform(Platform.android())
|
||||
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
|
||||
.setAudience(Audience.all())
|
||||
//jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
|
||||
.setNotification(Notification.newBuilder()
|
||||
//指定当前推送的android通知
|
||||
.addPlatformNotification(AndroidNotification.newBuilder()
|
||||
.setAlert(msg_content)
|
||||
.setTitle(notification_title)
|
||||
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
|
||||
.addExtra("url",extrasparam)
|
||||
.build())
|
||||
.build()
|
||||
)
|
||||
//Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
|
||||
// sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
|
||||
// [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
|
||||
.setMessage(Message.newBuilder()
|
||||
.setMsgContent(msg_content)
|
||||
.setTitle(msg_title)
|
||||
.addExtra("url",extrasparam)
|
||||
.build())
|
||||
|
||||
.setOptions(Options.newBuilder()
|
||||
//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
|
||||
.setApnsProduction(true)
|
||||
//此字段是给开发者自己给推送编号,方便推送者分辨推送记录
|
||||
.setSendno(1)
|
||||
//此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
|
||||
.setTimeToLive(86400)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static PushPayload buildPushObject_ios_all_alertWithTitle( String notification_title, String msg_title, String msg_content, String extrasparam) {
|
||||
return PushPayload.newBuilder()
|
||||
//指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
|
||||
.setPlatform(Platform.ios())
|
||||
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
|
||||
.setAudience(Audience.all())
|
||||
//jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
|
||||
.setNotification(Notification.newBuilder()
|
||||
//指定当前推送的android通知
|
||||
.addPlatformNotification(IosNotification.newBuilder()
|
||||
//传一个IosAlert对象,指定apns title、title、subtitle等
|
||||
.setAlert(msg_content)
|
||||
//直接传alert
|
||||
//此项是指定此推送的badge自动加1
|
||||
.incrBadge(1)
|
||||
//此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
|
||||
// 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
|
||||
.setSound("sound.caf")
|
||||
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
|
||||
.addExtra("url",extrasparam)
|
||||
//此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
|
||||
// .setContentAvailable(true)
|
||||
.build())
|
||||
.build()
|
||||
)
|
||||
//Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
|
||||
// sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
|
||||
// [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
|
||||
.setMessage(Message.newBuilder()
|
||||
.setMsgContent(msg_content)
|
||||
.setTitle(msg_title)
|
||||
.addExtra("url",extrasparam)
|
||||
.build())
|
||||
|
||||
.setOptions(Options.newBuilder()
|
||||
//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
|
||||
.setApnsProduction(false)
|
||||
//此字段是给开发者自己给推送编号,方便推送者分辨推送记录
|
||||
.setSendno(1)
|
||||
//此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
|
||||
.setTimeToLive(86400)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import cn.hutool.jwt.JWT;
|
||||
import cn.hutool.jwt.JWTHeader;
|
||||
import cn.hutool.jwt.JWTUtil;
|
||||
|
||||
public class JwtUtils {
|
||||
|
||||
public static Object get(String key, String token) {
|
||||
final JWT jwt = JWTUtil.parseToken(token);
|
||||
|
||||
jwt.getHeader(JWTHeader.TYPE);
|
||||
return jwt.getPayload(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package cn.pluss.platform.util;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.springframework.cglib.proxy.UndeclaredThrowableException;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
|
||||
/**
|
||||
* @author djh
|
||||
*/
|
||||
public class LogExceptionUtils {
|
||||
|
||||
public static void printStack(Logger logger, Throwable e, String message) {
|
||||
logger.info("异常名称:{}", e.getClass().getCanonicalName());
|
||||
if (e instanceof UndeclaredThrowableException) {
|
||||
e.getCause().printStackTrace();
|
||||
logger.info(message , e.getCause().getMessage());
|
||||
} else if (e instanceof InvocationTargetException) {
|
||||
((InvocationTargetException) e).getTargetException().printStackTrace();
|
||||
logger.info(message, e.getMessage());
|
||||
} else {
|
||||
e.printStackTrace();
|
||||
logger.info(message, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user