提交 8b09f61a 作者: 苗卫卫

项目初始化

父级
/target/
/.settings/
/.idea/
/.classpath
/.project
.DS_Store
~/
/logs/
/wios.iml
# 发版说明
# 发版说明
|发版环境|阿里云-青岛|
| ---- | ---- |
|发版内容|见 WIOS二期优化功能清单.doc
|影响范围|无|
|特别说明|无|
|发版前版本|docker version:1.0.1-20210923012418|
|发版时间|2021.10.8|
|是否经过回归|是|
|上线及回滚方案|无|
|发版负责人|李成|
|项目经理|李成|
|产品负责人|李成|
|开发负责人|李成|
|测试负责人|陈丹|
|review负责人|李成|
|发版结果|docker version:1.0.1-20211008055601|
|验证结果||
|回滚结果||
差异被折叠。 点击展开。
FROM registry.cn-qingdao.aliyuncs.com/starcharge-base/oracle-jdk8
WORKDIR /starcharge
ADD *.jar starcharge.jar
ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -Duser.timezone=GMT+08 -Dfile.encoding=UTF-8 -server -Xverify:none -jar ${jvmoptions} starcharge.jar --spring.profiles.active=${profile}
\ No newline at end of file
package com.ihidea.core.support.orm.mybatis3.interceptor.dialect;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
/**
* 优化frame.core中的分页
*
* @author kevin
*/
@Component
public class MysqlDialect extends Dialect {
protected CountSqlParser countSqlParser = new CountSqlParser();
/**
* 是否支持limit
* @return 支持返回true,否则返回false
*/
@Override
public boolean supportsLimit() {
return true;
}
/**
* 是否支持偏移游标
* @return 支持返回true,否则返回false
*/
@Override
public boolean supportsLimitOffset() {
return true;
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符(placeholder)替换.
* @param sql 执行的sql语句
* @param offset 偏移量
* @param limit 范围大
* @return 添加分页后的sql语句
*/
@Override
public String getLimitString(String sql, int offset, int limit) {
final int temp = 11;
final int tempInt = 100;
sql = sql.trim();
boolean isForUpdate = false;
if (sql.toLowerCase().endsWith(" for update")) {
sql = sql.substring(0, sql.length() - temp);
isForUpdate = true;
}
StringBuffer pagingSelect = new StringBuffer(sql.length() + tempInt);
// 如果sql中包含union,则使用全集分页;否则直接追加 limit
if(StringUtils.containsIgnoreCase(sql, "union")) {
pagingSelect.append("select * from (");
pagingSelect.append(sql);
pagingSelect.append(" ) mysqldialect1 limit " + offset + "," + limit);
} else {
pagingSelect.append(sql);
pagingSelect.append(" limit " + offset + "," + limit);
}
if (isForUpdate) {
pagingSelect.append(" for update");
}
return pagingSelect.toString();
}
@Override
public String getCountString(String sql) {
return countSqlParser.getSmartCountSql(sql);
}
@Override
public String getSysdateString() {
return "select now()";
}
}
package com.starcharge;
import java.util.Arrays;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.util.IntrospectorCleanupListener;
import com.ihidea.component.api.v2.annotation.EnableApiV2;
import com.ihidea.core.support.SpringContextLoader;
import com.ihidea.core.support.orm.mybatis3.interceptor.dialect.DialectInterceptor;
import com.ihidea.core.support.pageLimit.PageLimitHolderFilter;
import com.ihidea.core.support.servlet.ServletHolderFilter;
import com.ihidea.core.util.SystemUtilsEx;
import com.starcharge.component.datastore.FileServlet;
import com.starcharge.wios.auth.filter.LoginFilter;
/**
* 基于springboot2.2.8框架搭建,mvc还是基于servlet,未使用webflux是为了更好支持frame.core<br>
* 框架基于前后端分离的架构搭建,放弃了session过滤器及velocity相关配置<br>
* 框架屏蔽了大部分frame.core里的servlet和controller,采用按需加载模式
*
* @author lilin
* @version [版本号, 2020年4月30日]
*/
@SpringBootApplication(scanBasePackages = {"com.starcharge"})
@MapperScan({"com.starcharge.**.dao", "com.starcharge.**.daoex", "com.starcharge.**.daoEx"})
@EnableScheduling
@EnableAspectJAutoProxy
@EnableApiV2
@EnableFeignClients
@EnableAsync
public class Application {
// @Value("${cat.app.name}")
// private String catAppName;
//
// @Value("${cat.server.ip}")
// private String catServerIp;
/**
* 程序入口
*
* @param args 参数
*/
public static void main(String[] args) {
SystemUtilsEx.initJCE();
SpringApplication app = new SpringApplication(Application.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
/**
* 注册OpenAPIJsonServlet,实现@OpenAPI、@OpenAPIMethod方式的接口访问
*
* @return Servlet
*/
// @Bean
// public ServletRegistrationBean<OpenAPIJsonServlet> openAPIJsonServlet() {
// ServletRegistrationBean<OpenAPIJsonServlet> bean = new ServletRegistrationBean<>(new OpenAPIJsonServlet(),
// "/api/*");
// Map<String, String> params = new HashMap<String, String>();
// params.put("ipRanges", "58.216.219.86,10.0.0.0/8");
// bean.setInitParameters(params);
// return bean;
// }
/**
* 注册LoginFilter,实现登录权限校验
*
* @param ignoreUrls 忽略校验的url
* @param ignoreUrlPath 忽略校验的路径
* @return Filter
*/
@Bean
public FilterRegistrationBean<LoginFilter> loginFilter(@Value("${auth.ignoreUrls}") String ignoreUrls,
@Value("${auth.ignoreUrlPath}") String ignoreUrlPath) {
FilterRegistrationBean<LoginFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new LoginFilter());
Map<String, String> params = new HashMap<>();
params.put("ignoreUrls", ignoreUrls);
params.put("ignoreUrlPath", ignoreUrlPath);
registrationBean.setInitParameters(params);
// registrationBean.setUrlPatterns(Arrays.asList(new String[]{"/api/*", "/export.do"}));
registrationBean.setUrlPatterns(Arrays.asList(new String[]{"/api/*"}));
registrationBean.setOrder(10);
return registrationBean;
}
/**
* 允许跨域的filter
*
* @return Filter
*/
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
CorsConfigurationSource configSource = new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
return config;
}
};
registrationBean.setFilter(new CorsFilter(configSource));
// registrationBean.setUrlPatterns(Arrays.asList("/api/*", "/uploadFile.do"));
registrationBean.setUrlPatterns(Arrays.asList("*"));
registrationBean.setOrder(0); // 支持cors跨域的filter必须放第一个
return registrationBean;
}
/**
* 注册FileServlet,实现文件下载接口,适用于本地文件存储
*
* @return Servlet
*/
@Bean
public ServletRegistrationBean<FileServlet> fileServlet() {
ServletRegistrationBean<FileServlet> bean = new ServletRegistrationBean<>(new FileServlet(), "/download/*");
bean.setOrder(20);
return bean;
}
/**
* 注册ServletHolderFilter,实现在请求线程的任何代码模块都能获得request和response(不推荐)
*
* @return Filter
*/
@Bean
public FilterRegistrationBean<ServletHolderFilter> servletHolderFilter() {
FilterRegistrationBean<ServletHolderFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new ServletHolderFilter());
registrationBean.setUrlPatterns(Arrays.asList(new String[]{"*.do", "/api/*"}));
registrationBean.setOrder(40);
return registrationBean;
}
/**
* 注册PageLimitHolderFilter,实现自动化分页
*
* @return Filter
*/
@Bean
public FilterRegistrationBean<PageLimitHolderFilter> pageLimitFilter() {
FilterRegistrationBean<PageLimitHolderFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new PageLimitHolderFilter());
registrationBean.setUrlPatterns(Arrays.asList(new String[]{"*.do", "/api/*"}));
registrationBean.setOrder(50);
return registrationBean;
}
/**
* 此监听器主要用于解决java.beans.Introspector导致的内存泄漏的问题,如果使用Quartz需注册
*
* @return Listener
*/
@Bean
public ServletListenerRegistrationBean<EventListener> springIntrospectorCleanupListener() {
ServletListenerRegistrationBean<EventListener> registrationBean = new ServletListenerRegistrationBean<EventListener>();
registrationBean.setListener(new IntrospectorCleanupListener());
return registrationBean;
}
/**
* 注册spring上下文监听器
*
* @return Listener
*/
@Bean
public ServletListenerRegistrationBean<EventListener> springContextLoaderListener() {
ServletListenerRegistrationBean<EventListener> registrationBean = new ServletListenerRegistrationBean<EventListener>();
registrationBean.setListener(new SpringContextLoader());
return registrationBean;
}
/**
* 注册mybatis分页插件
*
* @return bean
*/
@Bean
public DialectInterceptor mybatisPageLimit() {
DialectInterceptor.getDialect();
return new DialectInterceptor();
}
/**
* 注册cat URL过滤器
*
* @return Filter
*/
// @Bean
// public FilterRegistrationBean<CatFilter> catFilter() {
// FilterRegistrationBean<CatFilter> registration = new FilterRegistrationBean<>();
// registration.setFilter(new CatFilter());
// registration.addUrlPatterns("/*");
// registration.setName("cat-filter");
// registration.setOrder(2);
// return registration;
// }
/**
* 注册cat SQL拦截器
*
* @return bean
*/
// @Bean
// public CatMybatisPlugin maybatisPlugin() {
// return new CatMybatisPlugin();
// }
/**
* cat系统参数初始化
*/
// @PostConstruct
// @Order(1)
// public void catInit() {
// System.setProperty("cat.app.name", catAppName);
// System.setProperty("cat.server.ip", catServerIp);
// }
}
package com.starcharge.api.remote;
import com.ihidea.component.api.v2.BaseResponse;
import com.starcharge.wios.auth.vo.LoginInfo;
import com.starcharge.wios.bo.api.ResponseMessage;
import com.starcharge.wios.query.*;
import com.starcharge.wios.result.WorkTaskVO;
import com.starcharge.wios.vo.TaskVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* 手动补偿接口
*/
@FeignClient(url = "${womc.flowUrl}", name = "DataSyncRemote")
public interface DataSyncRemote {
/**
* 手动补偿单据
*
* @param query
* @return
*/
@PostMapping("repair/flow/getArchivedWorkTask")
ResponseMessage<TaskVo> toWmsSyncBill(@RequestHeader("sso_token") String ssoToken, FlowQuery query);
/**
* 模拟登录
*
* @return
*/
@PostMapping("account/login")
BaseResponse<LoginInfo> accountLogin(@RequestParam String account, @RequestParam String password);
@PostMapping("camsFlow/closeFlow")
ResponseMessage<String> closeFlow(@RequestHeader("sso_token") String ssoToken,BaseSubmitFlowBO bo);
@PostMapping("camsFlow/submitFlow")
ResponseMessage<String> submitFlow(@RequestHeader("sso_token") String ssoToken,BaseSubmitFlowBO bo);
@PostMapping("camsFlow/getWorkTask")
ResponseMessage<WorkTaskVO> getWorkTask(@RequestHeader("sso_token") String ssoToken, CamsOrderQo bo);
@GetMapping("camsOrder/getOrderInfo")
ResponseMessage<Map<String, Object>> getOrderInfo(@RequestHeader("sso_token") String ssoToken,@RequestParam String id,@RequestParam Integer type);
@GetMapping("camsOrder/getConnectInfo")
ResponseMessage<Map<String, Object>> getConnectInfo(@RequestHeader("sso_token") String ssoToken,@RequestParam String id);
}
package com.starcharge.api.remote;
import com.ihidea.component.api.v2.BaseResponse;
import com.starcharge.wios.auth.vo.LoginInfo;
import com.starcharge.wios.bo.api.ResponseMessage;
import com.starcharge.wios.query.*;
import com.starcharge.wios.vo.TaskVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
/**
* 手动补偿接口
*/
@FeignClient(url = "${womc.orderUrl}", name = "OrderInformRemote")
public interface OrderInformRemote {
@PostMapping("/installtion_endreason_notification")
ResponseMessage<String> installtionEndreasonNotification(@RequestHeader("sso_token") String ssoToken,InstalltionEndreasonNotificationBO bo);
@PostMapping("/installtion_status_notification")
ResponseMessage<String> installtionStatusNotification(@RequestHeader("sso_token") String ssoToken,OrderInformBO bo);
}
package com.starcharge.base.bean;
import java.io.Serializable;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* 基础java bean
*
* @author lilin
* @version [版本号, 2018年11月15日]
*/
@SuppressWarnings("serial")
public abstract class BaseBean implements Serializable {
/**
* 重写toString
*
* @return String
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
package com.starcharge.base.config;
import com.starcharge.wios.task.ScheduleTask;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
//import com.dianping.cat.Cat;
//import com.dianping.cat.message.Transaction;
import com.ihidea.core.support.exception.ServiceException;
/**
* 拦截service层方法,记录cat日志
*
* @author lilin
* @version [版本号, 2019年1月16日]
*/
@Component
@Aspect
public class CatAdvice {
private Logger logger = LoggerFactory.getLogger(CatAdvice.class);
/**
* 定义pointcut
*/
@Pointcut("execution(public * com.starcharge..*.*(..))")
public void pointcut() {
}
/**
* 拦截要执行的目标方法
*
* @param joinPoint joinPoint
* @return Object
*/
@Around("pointcut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
try {
return pjp.proceed();
} catch (Throwable e) {
if (e instanceof ServiceException) {
logger.error( "[doAround]全局异常出口-Service,原因={}", ExceptionUtils.getFullStackTrace(e));
throw new ServiceException(((ServiceException) e).getCode(), e.getMessage());
} else {
logger.error( "[doAround]全局异常出口-Throwable,原因={}", ExceptionUtils.getFullStackTrace(e));
// 如果是生产环境,直接抛出
throw new ServiceException(e.getMessage());
}
} finally {
}
}
}
package com.starcharge.base.controller;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.starcharge.base.redis.RedisClient;
import com.starcharge.base.redis.RedisKeyConstant;
import com.starcharge.base.util.CaptchaUtilsEx;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 首页
*
* @author lilin
* @version [版本号, 2018年11月28日]
*/
@RestController
public class IndexController {
@Autowired
private RedisClient redisClient;
/**
* 版本号
*/
private static String version;
static {
try {
version = "v" + new Manifest(IndexController.class.getResourceAsStream("/META-INF/MANIFEST.MF")).getMainAttributes()
.get(Attributes.Name.IMPLEMENTATION_VERSION).toString();
} catch (Exception e) {
version = "unknow";
}
version = "<html><head></head><body>wios version: " + version + ".</body></html>";
}
/**
* 首页展示页
*
* @return 首页展示页
*/
@RequestMapping("/")
public String index() {
return version;
}
/**
* 健康检查
*
* @return success
*/
@RequestMapping("/healthCheck.do")
public String healthCheck() {
return "success";
}
/**
* 验证码
* @param deviceid 如果是前后端分离,页面也需要传(可以使用uuid,验证时使用相同的uuid)
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/jcaptcha.do")
public void jcaptcha(String deviceid, HttpServletRequest request,
HttpServletResponse response) throws Exception {
CaptchaUtilsEx captchaUtils = null;
boolean isMobileCaptcha = StringUtils.isNotBlank(deviceid);
if (isMobileCaptcha) {
captchaUtils = new CaptchaUtilsEx(130, 58, 4);
} else {
captchaUtils = new CaptchaUtilsEx(98, 39, 4, true);
}
// 如果是手机登录,则保存缓存
if (isMobileCaptcha) {
redisClient.put(RedisKeyConstant.REDIS_IMAGE_CAPTCHA_PREFIX +deviceid, captchaUtils.getImageCode(), 600);
} else {
request.getSession().setAttribute("app.jcaptcha",captchaUtils.getImageCode());
}
// 输出图象到页面
ImageIO.write(captchaUtils.getImage(), "JPEG", response.getOutputStream());
}
@RequestMapping("/generateQrcode.do")
public void generateQrcode(String url, Integer width, Integer height, HttpServletRequest request, HttpServletResponse response) throws Exception {
width = width == null ? 300 : width;
height = height == null ? 300 : height;
// 输出图象到页面
ImageIO.write(QrCodeUtil.generate(url, width, height), "JPEG", response.getOutputStream());
}
}
package com.starcharge.base.controller;
import com.starcharge.base.redis.RedisClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author kevin
* @create 2020/9/2 22:41
*/
@RestController
public class RedisTestController {
@Resource
private RedisClient redisClient;
@RequestMapping(value = "/testRedis")
public Object testRedis(String key, String value){
if(StringUtils.isNotBlank(key)){
redisClient.put(key,value, 60);
return redisClient.get(key);
}
return null;
}
}
package com.starcharge.base.redis;
/**
* redis中key的定义类
*
* @author lilin
* @version [版本号, 2020年5月11日]
*/
public class RedisKeyConstant {
/**
* token前缀
*/
// public static final String REDIS_TOKEN_PREFIX = "auth:account:";
/**
* lock前缀
*/
public static final String REDIS_LOCK_PREFIX = "tmp:lock:";
/**
* 图形验证码前缀
*/
public static final String REDIS_IMAGE_CAPTCHA_PREFIX = "mobile:JCaptchaCache_";
}
package com.starcharge.base.util;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import com.ihidea.core.support.exception.ServiceException;
/**
* 断言工具类
*
* @author lilin
* @version [4.0.0, 2017年6月28日]
*/
public final class Assert {
/**
* 判断是否为真
*
* @param expression 表达式
* @param message errorMessage
*/
public static void isTrue(boolean expression, String message) {
if (!expression) {
throw new ServiceException(message);
}
}
/**
* 判断是否为真
*
* @param expression 表达式
*/
public static void isTrue(boolean expression) {
isTrue(expression, "[Assertion failed] - this expression must be true");
}
/**
* 判断对象是否为空
*
* @param object 对象
* @param message errorMessage
*/
public static void isNull(Object object, String message) {
if (object != null) {
throw new ServiceException(message);
}
}
/**
* 判断对象是否为空
*
* @param object 对象
*/
public static void isNull(Object object) {
isNull(object, "[Assertion failed] - the object argument must be null");
}
/**
* 判断字符串是否为空
*
* @param str 对象
* @param message errorMessage
*/
public static void notBlank(String str, String message) {
if (StringUtils.isBlank(str)) {
throw new ServiceException(message);
}
}
/**
* 判断对象是否不为空
*
* @param object 对象
* @param message errorMessage
*/
public static void notNull(Object object, String message) {
if (object == null) {
throw new ServiceException(message);
}
}
/**
* 判断对象是否不为空
*
* @param object 对象
*/
public static void notNull(Object object) {
notNull(object, "[Assertion failed] - this argument is required; it must not be null");
}
/**
* 判断字符串是否为空
*
* @param str 字符串
* @param message errorMessage
*/
public static void notEmpty(String str, String message) {
if (StringUtils.isEmpty(str)) {
throw new ServiceException(message);
}
}
/**
* 判断字符串是否为空
*
* @param str 字符串
*/
public static void notEmpty(String str) {
notEmpty(str, "[Assertion failed] - this string must not be empty");
}
/**
* 判断集合是否为空
*
* @param collection 集合
* @param message errorMessage
*/
public static void notEmpty(Collection<?> collection, String message) {
if (CollectionUtils.isEmpty(collection)) {
throw new ServiceException(message);
}
}
/**
* 判断集合是否为空
*
* @param collection 集合
*/
public static void notEmpty(Collection<?> collection) {
notEmpty(collection, "[Assertion failed] - this collection must not be empty: it must contain at least 1 element");
}
/**
* 判断map是否为空
*
* @param map map集合
* @param message errorMessage
*/
public static void notEmpty(Map<?, ?> map, String message) {
if (MapUtils.isEmpty(map)) {
throw new ServiceException(message);
}
}
/**
* 判断map是否为空
*
* @param map map集合
*/
public static void notEmpty(Map<?, ?> map) {
notEmpty(map, "[Assertion failed] - this map must not be empty: it must contain at least 1 element");
}
}
package com.starcharge.base.util;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.Random;
/**
* 图片验证码工具类
*/
public class CaptchaUtilsEx {
// 使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
public static final String VERIFY_CODES_NUMBER = "0123456789";
private static Random random = new Random();
private BufferedImage image;
private String imageCode;
public BufferedImage getImage() {
return image;
}
public String getImageCode() {
return imageCode;
}
public CaptchaUtilsEx(Integer width, Integer height, Integer verifySize) {
this.imageCode = generateVerifyCode(verifySize, false);
this.image = getImage(width, height, verifySize, this.imageCode);
}
public CaptchaUtilsEx(Integer width, Integer height, Integer verifySize, boolean onlyNumber) {
this.imageCode = generateVerifyCode(verifySize, onlyNumber);
this.image = getImage(width, height, verifySize, this.imageCode);
}
public static String generateVerifyCode(int verifySize, boolean onlyNumber) {
String verifyCodeLib = onlyNumber ? VERIFY_CODES_NUMBER : VERIFY_CODES;
int codesLen = verifyCodeLib.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++) {
verifyCode.append(verifyCodeLib.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d =
(double)(period >> 1) * Math.sin((double)i / (double)period + (6.2831853071795862D * (double)phase) / (double)frames);
g.copyArea(0, i, w1, 1, (int)d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int)d, i, 0, i);
g.drawLine((int)d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d =
(double)(period >> 1) * Math.sin((double)i / (double)period + (6.2831853071795862D * (double)phase) / (double)frames);
g.copyArea(i, 0, 1, h1, 0, (int)d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int)d, i, 0);
g.drawLine(i, (int)d + h1, i, h1);
}
}
}
public static BufferedImage getImage(int w, int h, Integer verifySize, String code) {
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces =
new Color[]{Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW};
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h - 4);
// 绘制干扰线
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int)(yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使图片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h - 4;
//设置验证码字体, 如"Algerian"
Font font = new Font(null, Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++) {
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 6 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2,
h / 2);
g2.setTransform(affine);
// g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
g2.drawChars(chars, i, 1, (w / verifySize) * i , h / 2 + fontSize / 2 - 5);
}
g2.dispose();
return image;
}
}
package com.starcharge.base.util;
import javax.servlet.http.HttpServletRequest;
/**
* 网络工具类
*
* @author zhaohui
* @version [版本号, 2016年12月17日]
*/
public final class NetUtil {
/**
* 得到客户端ip
*
* @param request 请求
* @return 真实ip
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
// ipAddress = request.getRemoteAddr();
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.getHeader("HTTP_CLIENT_IP");
}
if (ipAddress == null || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
/*
* if (ipAddress.equals("127.0.0.1")) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet =
* InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress =
* inet.getHostAddress(); }
*/
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
return ipAddress;
}
}
package com.starcharge.component.datastore;
import com.ihidea.core.base.CoreService;
import com.ihidea.core.support.cache.CacheSupport;
import com.ihidea.core.support.exception.ServiceException;
import com.ihidea.core.support.orm.mybatis3.util.IbatisServiceUtils;
import com.ihidea.core.util.FileUtilsEx;
import com.starcharge.base.redis.RedisClient;
import com.starcharge.component.datastore.dao.CptDataStoreMapper;
import com.starcharge.component.datastore.dao.model.CptDataStore;
import com.starcharge.component.datastore.dao.model.CptDataStoreCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service("fileStoreService")
public class DataStoreService extends CoreService {
@Autowired
private CptDataStoreMapper dao;
@Autowired
private JdbcTemplate jdbcTemplate;
private static Map<String, CptDataStore> dataStoreMap = new HashMap<>();
/**
* 添加
* @param record
* @return
*/
public int insertDataStore(CptDataStore record) {
if ("2".equals(record.getType())) {
if (!isExists(record.getPath())) {
throw new ServiceException("文件路径不存在");
}
record.setPath(FileUtilsEx.filterPath(record.getPath()));
// 备份
if (!isExists(record.getBakPath())) {
throw new ServiceException("备份文件路径不存在");
}
record.setBakPath(FileUtilsEx.filterPath(record.getBakPath()));
}
return dao.insert(record);
}
/**
* 文件路径是否存在
* @param path
* @return
*/
private boolean isExists(String path) {
File file = new File(path);
return file.exists();
}
/**
* 删除
* @param id
* @return
*/
public int deleteDataStore(String id) {
// TODO
// 删除前判断是否还有文件,如果还有,则无法删除
return dao.deleteByPrimaryKey(id);
}
/**
* 更新
* @param record
* @return
*/
public int updateDataStore(CptDataStore record) {
if ("2".equals(record.getType())) {
record.setPath(FileUtilsEx.filterPath(record.getPath()));
record.setBakPath(FileUtilsEx.filterPath(record.getBakPath()));
}
return dao.updateByPrimaryKey(record);
}
/**
* 查询
* @param record
* @return
* @throws Exception
*/
public List<CptDataStore> selectDataStores(CptDataStore record) throws Exception {
CptDataStoreCriteria example = new CptDataStoreCriteria();
CptDataStoreCriteria.Criteria criteria = example.createCriteria();
IbatisServiceUtils.createCriteriaByEntity(criteria, record);
example.setOrderByClause("id");
return dao.selectByExample(example);
}
/**
* 查询
* @param id
* @return
*/
public CptDataStore selectDataStore(String id) {
return dao.selectByPrimaryKey(id);
}
/**
* 通过存储名称得到存储信息
* @param name
* @return
*/
public CptDataStore getInfoByName(String name) {
CptDataStore result = dataStoreMap.get("DataStoreService.getInfoByName:"+name);
if (result == null) {
result = jdbcTemplate.queryForObject("select id, name, type, path, type, bak_path from cpt_datastore where name = ?",
new Object[] { name }, new BeanPropertyRowMapper<CptDataStore>(CptDataStore.class));
dataStoreMap.put("DataStoreService.getInfoByName:"+name, result);
}
return result;
}
}
package com.starcharge.component.datastore;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ihidea.core.support.SpringContextLoader;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//@WebServlet(urlPatterns = "/download/*", loadOnStartup = 2)
public class FileServlet extends HttpServlet {
protected Log logger = LogFactory.getLog(FileServlet.class);
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getPathInfo().substring(1);
String fileId = id, fileImgSize = null, downloadFlag = null, mineType = null;
if (StringUtils.isNotBlank(id)) {
// 兼容编码后的参数,主要是七牛云
// ae1f7c89-7e7e-4a29-a284-1c8c284b1e0e?fileImgSize=20x20
if (id.indexOf("?") > 0) {
fileId = id.substring(0, id.indexOf("?"));
int _i = -1;
if ((_i = id.indexOf("fileImgSize=")) > 0) {
int _j = id.indexOf("&", _i);
fileImgSize = id.substring(_i + "fileImgSize=".length(), _j == -1 ? id.length() : _j);
}
if ((_i = id.indexOf("downloadFlag=")) > 0) {
int _j = id.indexOf("&", _i);
downloadFlag = id.substring(_i + "downloadFlag=".length(), _j == -1 ? id.length() : _j);
}
if ((_i = id.indexOf("mineType=")) > 0) {
int _j = id.indexOf("&", _i);
mineType = id.substring(_i + "mineType=".length(), _j == -1 ? id.length() : _j);
}
} else {
fileImgSize = request.getParameter("fileImgSize");
downloadFlag = request.getParameter("downloadFlag");
mineType = request.getParameter("mineType");
}
} else {
response.sendError(404);
return;
}
FileController fileController = SpringContextLoader.getBean(FileController.class);
try {
fileController.download(request, response, fileId, downloadFlag, fileImgSize, mineType);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public void destroy() {
}
public void init() throws ServletException {
}
}
package com.starcharge.component.datastore.dao;
import com.ihidea.core.base.CoreDao;
import com.starcharge.component.datastore.dao.model.CptDataInfo;
import com.starcharge.component.datastore.dao.model.CptDataInfoCriteria;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface CptDataInfoMapper extends CoreDao {
int countByExample(CptDataInfoCriteria example);
int deleteByExample(CptDataInfoCriteria example);
int deleteByPrimaryKey(String id);
int insert(CptDataInfo record);
int insertSelective(CptDataInfo record);
List<CptDataInfo> selectByExample(CptDataInfoCriteria example);
CptDataInfo selectByPrimaryKey(String id);
int updateByExampleSelective(@Param("record") CptDataInfo record, @Param("example") CptDataInfoCriteria example);
int updateByExample(@Param("record") CptDataInfo record, @Param("example") CptDataInfoCriteria example);
int updateByPrimaryKeySelective(CptDataInfo record);
int updateByPrimaryKey(CptDataInfo record);
}
\ No newline at end of file
package com.starcharge.component.datastore.dao;
import com.ihidea.core.base.CoreDao;
import com.starcharge.component.datastore.dao.model.CptDataStore;
import com.starcharge.component.datastore.dao.model.CptDataStoreCriteria;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface CptDataStoreMapper extends CoreDao {
int countByExample(CptDataStoreCriteria example);
int deleteByExample(CptDataStoreCriteria example);
int deleteByPrimaryKey(String id);
int insert(CptDataStore record);
int insertSelective(CptDataStore record);
List<CptDataStore> selectByExample(CptDataStoreCriteria example);
CptDataStore selectByPrimaryKey(String id);
int updateByExampleSelective(@Param("record") CptDataStore record, @Param("example") CptDataStoreCriteria example);
int updateByExample(@Param("record") CptDataStore record, @Param("example") CptDataStoreCriteria example);
int updateByPrimaryKeySelective(CptDataStore record);
int updateByPrimaryKey(CptDataStore record);
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.starcharge.component.datastore.dao.CptDataStoreMapper" >
<resultMap id="BaseResultMap" type="com.starcharge.component.datastore.dao.model.CptDataStore" >
<id column="Id" property="id" jdbcType="VARCHAR" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="type" property="type" jdbcType="VARCHAR" />
<result column="path" property="path" jdbcType="VARCHAR" />
<result column="bak_path" property="bakPath" jdbcType="VARCHAR" />
</resultMap>
<sql id="Example_Where_Clause" >
<where >
<foreach collection="oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
</when>
<when test="criterion.singleValue" >
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue" >
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue" >
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause" >
<where >
<foreach collection="example.oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
</when>
<when test="criterion.singleValue" >
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue" >
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue" >
and ${criterion.condition}
<foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List" >
Id, name, type, path, bak_path
</sql>
<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.starcharge.component.datastore.dao.model.CptDataStoreCriteria" >
select
<if test="distinct" >
distinct
</if>
<include refid="Base_Column_List" />
from cpt_datastore
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null" >
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from cpt_datastore
where Id = #{id,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
delete from cpt_datastore
where Id = #{id,jdbcType=VARCHAR}
</delete>
<delete id="deleteByExample" parameterType="com.starcharge.component.datastore.dao.model.CptDataStoreCriteria" >
delete from cpt_datastore
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.starcharge.component.datastore.dao.model.CptDataStore" >
insert into cpt_datastore (Id, name, type,
path, bak_path)
values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR},
#{path,jdbcType=VARCHAR}, #{bakPath,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.starcharge.component.datastore.dao.model.CptDataStore" >
insert into cpt_datastore
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
Id,
</if>
<if test="name != null" >
name,
</if>
<if test="type != null" >
type,
</if>
<if test="path != null" >
path,
</if>
<if test="bakPath != null" >
bak_path,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=VARCHAR},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="type != null" >
#{type,jdbcType=VARCHAR},
</if>
<if test="path != null" >
#{path,jdbcType=VARCHAR},
</if>
<if test="bakPath != null" >
#{bakPath,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.starcharge.component.datastore.dao.model.CptDataStoreCriteria" resultType="java.lang.Integer" >
select count(*) from cpt_datastore
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map" >
update cpt_datastore
<set >
<if test="record.id != null" >
Id = #{record.id,jdbcType=VARCHAR},
</if>
<if test="record.name != null" >
name = #{record.name,jdbcType=VARCHAR},
</if>
<if test="record.type != null" >
type = #{record.type,jdbcType=VARCHAR},
</if>
<if test="record.path != null" >
path = #{record.path,jdbcType=VARCHAR},
</if>
<if test="record.bakPath != null" >
bak_path = #{record.bakPath,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map" >
update cpt_datastore
set Id = #{record.id,jdbcType=VARCHAR},
name = #{record.name,jdbcType=VARCHAR},
type = #{record.type,jdbcType=VARCHAR},
path = #{record.path,jdbcType=VARCHAR},
bak_path = #{record.bakPath,jdbcType=VARCHAR}
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.starcharge.component.datastore.dao.model.CptDataStore" >
update cpt_datastore
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="type != null" >
type = #{type,jdbcType=VARCHAR},
</if>
<if test="path != null" >
path = #{path,jdbcType=VARCHAR},
</if>
<if test="bakPath != null" >
bak_path = #{bakPath,jdbcType=VARCHAR},
</if>
</set>
where Id = #{id,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="com.starcharge.component.datastore.dao.model.CptDataStore" >
update cpt_datastore
set name = #{name,jdbcType=VARCHAR},
type = #{type,jdbcType=VARCHAR},
path = #{path,jdbcType=VARCHAR},
bak_path = #{bakPath,jdbcType=VARCHAR}
where Id = #{id,jdbcType=VARCHAR}
</update>
</mapper>
\ No newline at end of file
package com.starcharge.component.datastore.dao.model;
import com.ihidea.core.base.CoreEntity;
import java.util.Date;
public class CptDataInfo extends CoreEntity {
private String id;
private String storeName;
private String description;
private String fileName;
private Integer fileSize;
private Integer status;
private String createAccount;
private Date createTime;
private String prefix;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName == null ? null : storeName.trim();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName == null ? null : fileName.trim();
}
public Integer getFileSize() {
return fileSize;
}
public void setFileSize(Integer fileSize) {
this.fileSize = fileSize;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCreateAccount() {
return createAccount;
}
public void setCreateAccount(String createAccount) {
this.createAccount = createAccount == null ? null : createAccount.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix == null ? null : prefix.trim();
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CptDataInfo other = (CptDataInfo) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getStoreName() == null ? other.getStoreName() == null : this.getStoreName().equals(other.getStoreName()))
&& (this.getDescription() == null ? other.getDescription() == null : this.getDescription().equals(other.getDescription()))
&& (this.getFileName() == null ? other.getFileName() == null : this.getFileName().equals(other.getFileName()))
&& (this.getFileSize() == null ? other.getFileSize() == null : this.getFileSize().equals(other.getFileSize()))
&& (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus()))
&& (this.getCreateAccount() == null ? other.getCreateAccount() == null : this.getCreateAccount().equals(other.getCreateAccount()))
&& (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()))
&& (this.getPrefix() == null ? other.getPrefix() == null : this.getPrefix().equals(other.getPrefix()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getStoreName() == null) ? 0 : getStoreName().hashCode());
result = prime * result + ((getDescription() == null) ? 0 : getDescription().hashCode());
result = prime * result + ((getFileName() == null) ? 0 : getFileName().hashCode());
result = prime * result + ((getFileSize() == null) ? 0 : getFileSize().hashCode());
result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode());
result = prime * result + ((getCreateAccount() == null) ? 0 : getCreateAccount().hashCode());
result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode());
result = prime * result + ((getPrefix() == null) ? 0 : getPrefix().hashCode());
return result;
}
}
\ No newline at end of file
package com.starcharge.component.datastore.dao.model;
import com.ihidea.core.base.CoreEntity;
public class CptDataStore extends CoreEntity {
private String id;
private String name;
private String type;
private String path;
private String bakPath;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type == null ? null : type.trim();
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path == null ? null : path.trim();
}
public String getBakPath() {
return bakPath;
}
public void setBakPath(String bakPath) {
this.bakPath = bakPath == null ? null : bakPath.trim();
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CptDataStore other = (CptDataStore) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))
&& (this.getPath() == null ? other.getPath() == null : this.getPath().equals(other.getPath()))
&& (this.getBakPath() == null ? other.getBakPath() == null : this.getBakPath().equals(other.getBakPath()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getType() == null) ? 0 : getType().hashCode());
result = prime * result + ((getPath() == null) ? 0 : getPath().hashCode());
result = prime * result + ((getBakPath() == null) ? 0 : getBakPath().hashCode());
return result;
}
}
\ No newline at end of file
package com.starcharge.component.datastore.fileio;
import java.util.ArrayList;
import java.util.List;
import com.ihidea.core.support.exception.ServiceException;
import com.starcharge.component.datastore.DataStoreService;
import com.starcharge.component.datastore.dao.CptDataInfoMapper;
import com.starcharge.component.datastore.dao.model.CptDataInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
/**
* 存储数据库IO(不推荐使用)
*/
@Component
class FileIoDb implements IFileIo {
private Log logger = LogFactory.getLog(FileIoDb.class);
@Autowired
private DataStoreService dataStoreService;
@Autowired
private CptDataInfoMapper dataInfoDao;
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 保存到存储路径
*/
@Override
public void save(FileIoEntity entity) {
saveFile(entity.getDataInfo().getId(), entity.getContent(), dataStoreService.getInfoByName(entity.getDataInfo().getStoreName()).getPath());
}
/**
* 保存到备份存储路径
*/
@Override
public void saveBak(FileIoEntity entity) {
saveFile(entity.getDataInfo().getId(), entity.getContent(), dataStoreService.getInfoByName(entity.getDataInfo().getStoreName()).getBakPath());
}
/**
* 持久化
*/
private void saveFile(final String id, final byte[] content, String storePath) {
//TODO 序列化后存入数据库
}
@Override
public boolean remove(FileIoEntity entity) {
String storePath = dataStoreService.getInfoByName(entity.getDataInfo().getStoreName()).getPath();
try {
jdbcTemplate.update("delete from " + storePath + " where id = ?", new Object[] { entity.getDataInfo().getId() });
} catch (Exception e) {
logger.error(e.getMessage(), e);
return false;
}
return true;
}
@SuppressWarnings("unchecked")
public byte[] get(String id) {
CptDataInfo dataInfo = dataInfoDao.selectByPrimaryKey(id);
String storePath = dataStoreService.getInfoByName(dataInfo.getStoreName()).getPath();
final List<byte[]> byteBody = new ArrayList<byte[]>();
//TODO 从数据库取出并解析
return byteBody.get(0);
}
@Override
public void updateContent(final String id, final byte[] content) {
CptDataInfo dataInfo = dataInfoDao.selectByPrimaryKey(id);
String storePath = dataStoreService.getInfoByName(dataInfo.getStoreName()).getPath();
try {
//TODo 序列化后更新
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
@Override
public void execute(FileIoEntity fileIoEntity, IFileInputStream fileInputStreamImpl) {
throw new ServiceException("未实现");
}
}
package com.starcharge.component.datastore.fileio;
import com.starcharge.component.datastore.dao.model.CptDataInfo;
public class FileIoEntity {
private CptDataInfo dataInfo;
private byte[] content;
public FileIoEntity() {
}
public FileIoEntity(CptDataInfo dataInfo) {
this.dataInfo = dataInfo;
}
public CptDataInfo getDataInfo() {
return dataInfo;
}
public void setDataInfo(CptDataInfo dataInfo) {
this.dataInfo = dataInfo;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
}
package com.starcharge.component.datastore.fileio;
import com.ihidea.core.support.exception.ServiceException;
import com.starcharge.component.datastore.DataStoreService;
import com.starcharge.component.datastore.dao.model.CptDataStore;
import com.ihidea.core.support.SpringContextLoader;
public class FileIoFactory {
public static IFileIo getInstance(String dataStoreName) {
IFileIo fileIo = null;
DataStoreService dataStoreService = SpringContextLoader.getBean(DataStoreService.class);
CptDataStore cptDataStore = dataStoreService.getInfoByName(dataStoreName);
if ("1".equals(cptDataStore.getType())) {
fileIo = SpringContextLoader.getBean(FileIoDb.class);
} else if ("2".equals(cptDataStore.getType())) {
fileIo = SpringContextLoader.getBean(FileIoLocal.class);
} else if ("3".equals(cptDataStore.getType())) {
fileIo = SpringContextLoader.getBean(FileIoOSS.class);
} else {
throw new ServiceException("没有找到类型为:" + cptDataStore.getType() + "的数据存储方式!");
}
return fileIo;
}
}
package com.starcharge.component.datastore.fileio;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import com.ihidea.core.support.exception.ServiceException;
import com.ihidea.core.util.DateUtilsEx;
import com.starcharge.component.datastore.DataStoreService;
import com.starcharge.component.datastore.dao.CptDataInfoMapper;
import com.starcharge.component.datastore.dao.model.CptDataInfo;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 存储本地文件IO
* @author TYOTANN
*/
@Component
public class FileIoLocal implements IFileIo {
private Log logger = LogFactory.getLog(FileIoLocal.class);
@Autowired
private DataStoreService dataStoreService;
@Autowired
private CptDataInfoMapper dataInfoDao;
/**
* 保存到存储路径
*/
@Override
public void save(FileIoEntity entity) {
saveFile(entity.getDataInfo().getId(), entity.getContent(),
getPath(entity.getDataInfo().getStoreName(), entity.getDataInfo().getCreateTime()));
}
/**
* 保存到备份存储路径
*/
public void saveBak(FileIoEntity entity) {
saveFile(entity.getDataInfo().getId(), entity.getContent(),
getBakPath(entity.getDataInfo().getStoreName(), entity.getDataInfo().getCreateTime()));
}
/**
* 持久化
*/
private void saveFile(String id, byte[] content, String storePath) {
File file = new File(storePath + File.separator + id);
if (file.exists()) {
throw new ServiceException("文件:" + file.getPath() + "已经存在!");
}
// 文件夹不存在的话则创建
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try {
FileUtils.writeByteArrayToFile(file, content);
} catch (IOException e) {
throw new ServiceException(e);
}
}
@Override
public boolean remove(FileIoEntity entity) {
String path = getPath(entity.getDataInfo().getStoreName(), entity.getDataInfo().getCreateTime());
File file = new File(path + File.separator + entity.getDataInfo().getId());
// file.exists()==true?file.delete():true;
return file.delete();
}
public byte[] get(String id) {
CptDataInfo dataInfo = dataInfoDao.selectByPrimaryKey(id);
String path = getPath(dataInfo.getStoreName(), dataInfo.getCreateTime());
try {
File downloadFile = new File(path + File.separator + id);
if (downloadFile.exists()) {
return FileUtils.readFileToByteArray(downloadFile);
} else {
return null;
}
} catch (IOException e) {
throw new ServiceException(e);
}
}
@Override
public void execute(FileIoEntity fileIoEntity, IFileInputStream fileInputStreamImpl) throws Exception {
String filePath = getPath(fileIoEntity.getDataInfo().getStoreName(), fileIoEntity.getDataInfo().getCreateTime()) + File.separator
+ fileIoEntity.getDataInfo().getId();
File downloadFile = new File(filePath);
if (downloadFile.exists()) {
FileInputStream fis = null;
try {
fis = FileUtils.openInputStream(downloadFile);
fileInputStreamImpl.execute(fileIoEntity, fis);
} catch (ClientAbortException e) {
} catch (IOException e) {
throw new ServiceException(e);
} finally {
if (fis == null) {
IOUtils.closeQuietly(fis);
}
}
} else {
logger.info("文件不存在:" + filePath);
fileInputStreamImpl.execute(null, null);
}
}
private String getPath(String storeName, Date createDate) {
String storePath = dataStoreService.getInfoByName(storeName).getPath();
return storePath + DateUtilsEx.formatToString(createDate, DateUtilsEx.DATE_FORMAT_DAY).replace(".", File.separator);
}
private String getBakPath(String storeName, Date createDate) {
String storePath = dataStoreService.getInfoByName(storeName).getBakPath();
return storePath + DateUtilsEx.formatToString(createDate, DateUtilsEx.DATE_FORMAT_DAY).replace(".", File.separator);
}
@Override
public void updateContent(String id, byte[] content) {
CptDataInfo dataInfo = dataInfoDao.selectByPrimaryKey(id);
String path = getPath(dataInfo.getStoreName(), dataInfo.getCreateTime());
File file = new File(path + File.separator + id);
file.deleteOnExit();
try {
FileUtils.writeByteArrayToFile(file, content);
} catch (IOException e) {
throw new ServiceException(e);
}
}
}
package com.starcharge.component.datastore.fileio;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.aliyun.oss.OSSClientBuilder;
import com.ihidea.core.support.exception.ServiceException;
import com.ihidea.core.util.JSONUtilsEx;
import com.starcharge.component.datastore.DataStoreService;
import com.starcharge.component.datastore.dao.CptDataInfoMapper;
import com.starcharge.component.datastore.dao.model.CptDataInfo;
import com.starcharge.component.datastore.dao.model.CptDataStore;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
/**
* 阿里云存储对象OSS
* @author wenhao
*/
@Component
@Lazy
public class FileIoOSS implements IFileIo {
private static Map<String, Map<String, String>> bucketMap = new HashMap<String, Map<String, String>>();
private static OSS ossClient = null;
@Autowired
private DataStoreService dataStoreService;
@Autowired
private CptDataInfoMapper dataInfoDao;
@SuppressWarnings("unchecked")
private synchronized Map<String, String> initBucketInfo(String storeName) {
CptDataStore cptDataStore = dataStoreService.getInfoByName(storeName);
Map<String, String> bucketInfo = JSONUtilsEx.deserialize(cptDataStore.getPath(), Map.class);
bucketMap.put(storeName, bucketInfo);
return bucketInfo;
}
private synchronized void initOssClient(Map<String, String> bucketInfo) {
// ossClient = new OSSClient(bucketInfo.get("endpoint"), bucketInfo.get("accessKeyId"), bucketInfo.get("accessKeySecret"));
ossClient = new OSSClientBuilder().build(bucketInfo.get("endpoint"), bucketInfo.get("accessKeyId"), bucketInfo.get("accessKeySecret"));
}
public Map<String, String> getBucketInfo(String storeName){
Map<String, String> bucketInfo = bucketMap.get(storeName);
// 根据storeName得到参数
if (bucketInfo == null) {
bucketInfo = initBucketInfo(storeName);
}
if(ossClient == null){
initOssClient(bucketInfo);
}
return bucketInfo;
}
/**
* 保存到OSS
*/
@Override
public void save(FileIoEntity entity) {
String id= StringUtils.isNotBlank(entity.getDataInfo().getPrefix()) ? entity.getDataInfo().getPrefix()+"/"+entity.getDataInfo().getId() : entity.getDataInfo().getId();
saveFile(id, entity.getDataInfo().getFileName(), entity.getContent(), entity.getDataInfo().getStoreName());
}
/**
* 保存到备份存储OSS
*/
public void saveBak(FileIoEntity entity) {
throw new ServiceException("未实现");
}
private void saveFile(String id, String name, byte[] content, String storeName) {
try{
Map<String, String> bucketInfo = getBucketInfo(storeName);
ossClient.putObject(bucketInfo.get("bucketName"), bucketInfo.get("key") + id, new ByteArrayInputStream(content));
}catch (Exception e) {
throw new ServiceException("阿里云存储对象OSS上传出现异常:" + e.getMessage(), e);
}
}
@Override
public boolean remove(FileIoEntity entity) {
throw new ServiceException("未实现");
}
public byte[] get(String id) {
byte[] data = null;
CptDataInfo dataInfo = dataInfoDao.selectByPrimaryKey(id);
if(dataInfo != null){
Map<String, String> bucketInfo = getBucketInfo(dataInfo.getStoreName());
OSSObject ossObject = ossClient.getObject(bucketInfo.get("bucketName"), bucketInfo.get("key") + id);
try {
InputStream inputStream = ossObject.getObjectContent();
data=toByteArray(inputStream);
inputStream.close();
} catch (IOException e) {
throw new ServiceException("阿里云存储对象OSS获得对象出现异常:" + e.getMessage());
}
}
return data;
}
@Override
public void execute(FileIoEntity fileIoEntity, IFileInputStream fileInputStreamImpl) throws Exception {
throw new ServiceException("未实现");
}
@Override
public void updateContent(String id, byte[] content) {
throw new ServiceException("未实现");
}
private static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out=new ByteArrayOutputStream();
byte[] buffer=new byte[1024*4];
int n=0;
while ( (n=in.read(buffer)) !=-1) {
out.write(buffer,0,n);
}
return out.toByteArray();
}
public void deleteFile(String id, String storeName, String prefix) {
try{
Map<String, String> bucketInfo = getBucketInfo(storeName);
ossClient.deleteObject(bucketInfo.get("bucketName"), bucketInfo.get("key") +(StringUtils.isNotBlank(prefix) ? prefix+"/"+id : id));
}catch (Exception e) {
throw new ServiceException("阿里云OSS批量删除文件出现异常:" + e.getMessage(), e);
}
}
public void deleteFileBatch(List<String> idList, String storeName, String prefix) {
try{
Map<String, String> bucketInfo = getBucketInfo(storeName);
List<String> keys=new ArrayList<>();
for (String id : idList) {
keys.add(bucketInfo.get("key") + (StringUtils.isNotBlank(prefix) ? prefix+"/"+id : id));
}
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketInfo.get("bucketName")).withKeys(keys));
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
System.out.println("成功删除:"+deletedObjects.toString());
}catch (Exception e) {
throw new ServiceException("阿里云OSS批量删除文件出现异常:" + e.getMessage(), e);
}
}
public void copyFile(String sourceFileName, String destFileName, String storeName) {
try{
Map<String, String> bucketInfo = getBucketInfo(storeName);
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(bucketInfo.get("bucketName"), bucketInfo.get("key") + sourceFileName, bucketInfo.get("bucketName"), bucketInfo.get("key") +destFileName);
ossClient.copyObject(copyObjectRequest);
}catch (Exception e) {
throw new ServiceException("阿里云OSS复制文件出现异常:" + e.getMessage(), e);
}
}
public boolean exist(String id, String storeName, String prefix) {
try{
Map<String, String> bucketInfo = getBucketInfo(storeName);
return ossClient.doesObjectExist(bucketInfo.get("bucketName"), bucketInfo.get("key") + (StringUtils.isNotBlank(prefix) ? prefix+"/"+id : id));
}catch (Exception e) {
throw new ServiceException("阿里云检查文件是否存在出现异常:" + e.getMessage(), e);
}
}
/**
* 获取文件列表,最多100个
* @param prefix
* @param storeName
* @return
*/
public List<String> list(String prefix, String storeName) {
try{
Map<String, String> bucketInfo = getBucketInfo(storeName);
ObjectListing objectListing = ossClient.listObjects(bucketInfo.get("bucketName"), bucketInfo.get("key")+prefix);
List<String> fileIdList=new ArrayList<>();
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
for (OSSObjectSummary s : sums) {
fileIdList.add(s.getKey());
}
return fileIdList;
}catch (Exception e) {
throw new ServiceException("阿里云列举文件出现异常:" + e.getMessage(), e);
}
}
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("endpoint", "oss-cn-qingdao.aliyuncs.com");
map.put("key", "img/");
System.out.println(JSONUtilsEx.serialize(map));
}
}
package com.starcharge.component.datastore.fileio;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import com.ihidea.core.support.exception.ServiceException;
import com.ihidea.core.util.JSONUtilsEx;
import com.starcharge.component.datastore.DataStoreService;
import com.starcharge.component.datastore.dao.model.CptDataStore;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
/**
* 七牛云存储
* 暂未集成, 参考官方文档 https://developer.qiniu.com/kodo/sdk/1239/java
*/
@Component
@Lazy
public class FileIoQiniu implements IFileIo {
private static Log logger = LogFactory.getLog(FileIoQiniu.class);
@Autowired
private DataStoreService dataStoreService;
/**
* 保存到存储路径
*/
@Override
public void save(FileIoEntity entity) {
saveFile(entity.getDataInfo().getId(), entity.getContent(), entity.getDataInfo().getStoreName());
}
/**
* 保存到备份存储路径
*/
@Override
public void saveBak(FileIoEntity entity) {
throw new ServiceException("未实现");
}
private static Map<String, Map<String, String>> bucketMap = new HashMap<String, Map<String, String>>();
@SuppressWarnings("unchecked")
private synchronized Map<String, String> initBucketInfo(String storeName) {
CptDataStore cptDataStore = dataStoreService.getInfoByName(storeName);
Map<String, String> bucketInfo = JSONUtilsEx.deserialize(cptDataStore.getPath(), Map.class);
bucketMap.put(storeName, bucketInfo);
return bucketInfo;
}
/**
* 持久化
*/
private void saveFile(String id, InputStream is, String storeName) {
//TODO 集成上传
}
private void saveFile(String id, byte[] content, String storeName) {
try {
InputStream is = new ByteArrayInputStream(content);
saveFile(id, is, storeName);
} catch (Exception e) {
throw new ServiceException("云存储上传出现异常:" + e.getMessage(), e);
}
}
public boolean remove(String id, String sotreName) {
//TODO 集成删除
return false;
}
@Override
public boolean remove(FileIoEntity entity) {
return remove(entity.getDataInfo().getId(), entity.getDataInfo().getStoreName());
}
@Override
public byte[] get(String id) {
return null;
}
@Override
public void execute(FileIoEntity fileIoEntity, IFileInputStream fileInputStreamImpl) throws Exception {
throw new ServiceException("未实现");
}
/**
* 先删除,后上传
*/
@Override
public void updateContent(String id, byte[] content) {
throw new ServiceException("未实现");
}
}
package com.starcharge.component.datastore.fileio;
import java.io.InputStream;
public interface IFileInputStream {
public void execute(FileIoEntity entity, InputStream is) throws Exception;
}
package com.starcharge.component.datastore.fileio;
public interface IFileIo {
public void save(FileIoEntity entity);
public void saveBak(FileIoEntity entity);
public void updateContent(String id, final byte[] content);
public boolean remove(FileIoEntity entity);
public byte[] get(String id);
public void execute(FileIoEntity fileIoEntity, IFileInputStream fileInputStreamImpl) throws Exception;
}
package com.starcharge.component.pay.weixin;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.starcharge.wios.service.UserPayBillService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ihidea.core.util.ServletUtilsEx;
import com.ihidea.core.util.XMLUtilsEx;
/**
* 微信支付回调接口
* @author kevin
*/
@Controller
public class WeixinPayController {
private final static Logger logger = LoggerFactory.getLogger(WeixinPayController.class);
@Autowired
private UserPayBillService userPayBillService;
@SuppressWarnings("unchecked")
@RequestMapping(value = "/weixin.pay.notify.do")
public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
String xmlStr = IOUtils.toString(request.getInputStream(), Charset.defaultCharset());
logger.info("收到微信支付回调,数据:"+xmlStr);
Map<String, String> requestMap = XMLUtilsEx.deserialize(xmlStr, Map.class);
// 通知状态
String returnCode = requestMap.get("return_code");
// 订单状态
String resultCode = requestMap.get("result_code");
String signStr = requestMap.get("sign");
// 商户订单号
String out_trade_no = requestMap.get("out_trade_no");
requestMap.remove("sign");
String signedStr = WeixinPayCore.getSign(requestMap);
Map<String, String> responseMap = new HashMap<String, String>();
if (StringUtils.equals("SUCCESS", returnCode) && StringUtils.equals("SUCCESS", resultCode) && StringUtils.isNotBlank(signStr) && signStr.equals(signedStr)) {
// 支付成功更新账单
payBillSuccess(requestMap);
responseMap.put("return_code", "SUCCESS");
responseMap.put("return_msg", "ok");
} else {
responseMap.put("return_code", "FAIL");
responseMap.put("return_msg", requestMap.get("return_msg"));
}
ServletUtilsEx.renderText(response, "<xml>" + XMLUtilsEx.serialize(responseMap) + "</xml>");
}
public void payBillSuccess(Map requestMap){
// 商户订单号
String out_trade_no = (String)requestMap.get("out_trade_no");
logger.info("支付成功:"+out_trade_no);
// 交易号
String transaction_id = (String)requestMap.get("transaction_id");
// 微信openId
String openId = (String)requestMap.get("openid");
// 附加数据
String attach = (String)requestMap.get("attach");
// 更新支付信息
int source = StringUtils.equals(attach, "2") ? 2 : 1;
userPayBillService.paySuccess(out_trade_no.split("_")[0], 3, openId, transaction_id, new Date(), source);
}
}
package com.starcharge.component.pay.weixin;
import com.ihidea.component.pay.PayPropertySupport;
import com.ihidea.core.util.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
/**
* @author kevin
*/
@Component
public class WeixinPayCore {
private final static Logger logger = LoggerFactory.getLogger(WeixinPayCore.class);
private static String wiosApiUrl;
@Value("${url.api.wios}")
public void setWiosApiUrl(String wiosApiUrl){
WeixinPayCore.wiosApiUrl = wiosApiUrl;
}
/**
* 得到签名
* @param params
* @return
*/
public static String getSign(Map<String, String> params) {
// 参数排序
String preSingStr = createLinkString(params);
// 拼接API密钥
preSingStr = preSingStr + "&key=" + PayPropertySupport.getProperty("pay.weixin.key");
return DigitalUtils.byte2hex(SignatureUtils.md5(preSingStr));
}
private static String createLinkString(Map<String, String> params) {
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
// 拼接时,不包括最后一个&字符
if (i == keys.size() - 1) {
prestr = prestr + key + "=" + value;
} else {
prestr = prestr + key + "=" + value + "&";
}
}
return prestr;
}
/**
* 查询订单状态<br>
* SUCCESS—支付成功<br>
* REFUND—转入退款<br>
* NOTPAY—未支付<br>
* CLOSED—已关闭<br>
* REVOKED—已撤销<br>
* USERPAYING--用户支付中<br>
* NOPAY--未支付(输入密码或确认支付超时)<br>
* PAYERROR--支付失败(其他原因,如银行返回失败)<br>
* @param orderId
* @return
*/
public static Map<String, Object> queryOrder(String orderId) {
Map<String, String> params = new HashMap<String, String>();
// 公众账号ID
params.put("appid", PayPropertySupport.getProperty("pay.weixin.appid"));
// 商户号
params.put("mch_id", PayPropertySupport.getProperty("pay.weixin.mchId"));
// 商户订单号
params.put("out_trade_no", orderId);
// 随机字符串
params.put("nonce_str", String.valueOf(System.currentTimeMillis() / 1000));
// 签名
params.put("sign", getSign(params));
String resultJSON = HttpClientUtils.post("https://api.mch.weixin.qq.com/pay/orderquery",
"<xml>" + XMLUtilsEx.serialize(params) + "</xml>", "UTF-8", "UTF-8");
logger.info("查询订单支付返回结果:"+resultJSON);
Map<String, Object> resultMap = XMLUtilsEx.deserialize(resultJSON, Map.class);
if (resultMap.containsKey("trade_state")) {
if(StringUtils.equals("SUCCESS", (String)resultMap.get("trade_state"))){
return resultMap;
}
}
return null;
}
/**
* 得到统一下单的PrepayId
* @return
*/
public static String getPayPrepayId(String orderId, String orderName, BigDecimal price, String ipAddress, String tradeType, String openId) {
Map<String, Object> resultMap = payPrepay(orderId, orderName, price, ipAddress, tradeType, openId, null);
return (String) resultMap.get("prepay_id");
}
/**
* 获取统一下单的code_url
* @param orderId
* @param orderName
* @param price
* @param ipAddress
* @return
*/
public static String getCodeUrl(String orderId, String orderName, BigDecimal price, String ipAddress, String productId) {
Map<String, Object> resultMap = payPrepay(orderId, orderName, price, ipAddress, WeixinPayTradeType.NATIVE.toString(), null, productId);
return (String) resultMap.get("code_url");
}
/**
* 生成统一订单
* 在微信支付中,同一商户下的商户订单号必须唯一,否则提示商户订单号重复,除非多次请求时参数不变,微信支付会当做同一个订单;
* 当前wios支持扫码支付(NATIVE)和公众号支付(JSAPI),所以通过orderId + "_" + tradeType 进行区分,防止冲突,支付完成后的回调处理也按照相应方式反向处理
* @param openId
* @param orderId
* @param orderName
* @param price
* @param ipAddress
* @return
*/
@SuppressWarnings("unchecked")
private static Map<String, Object> payPrepay(String orderId, String orderName, BigDecimal price, String ipAddress, String tradeType, String openId, String productId) {
Map<String, String> params = new HashMap<String, String>();
// 公众账号ID
params.put("appid", PayPropertySupport.getProperty("pay.weixin.appid"));
// 商户号
params.put("mch_id", PayPropertySupport.getProperty("pay.weixin.mchId"));
// 随机字符串
params.put("nonce_str", String.valueOf(System.currentTimeMillis() / 1000));
// 商品描述
params.put("body", orderName);
// 商户订单号
params.put("out_trade_no", orderId+"_"+tradeType);
// 总金额(x100)
params.put("total_fee", String.valueOf(price.multiply(BigDecimal.valueOf(100)).setScale(0, RoundingMode.UP)));
// 终端IP
params.put("spbill_create_ip", ipAddress);
// 通知地址
params.put("notify_url", wiosApiUrl + "/" +PayPropertySupport.getProperty("pay.weixin.notifyUrl"));
// 交易类型
params.put("trade_type", tradeType);
if(StringUtils.equals(tradeType, WeixinPayTradeType.JSAPI.toString())){
params.put("openid", openId);
params.put("attach", "1");
}else if(StringUtils.equals(tradeType, WeixinPayTradeType.NATIVE.toString())){
params.put("product_id", productId);
params.put("attach", "2");
}
// 签名
params.put("sign", getSign(params));
String paramsXml=XMLUtilsEx.serialize(params);
logger.info("统一下单参数:"+paramsXml);
String resultJSON = HttpClientUtils.post("https://api.mch.weixin.qq.com/pay/unifiedorder", "<xml>" + paramsXml
+ "</xml>", "UTF-8", "UTF-8");
logger.info("统一下单返回:"+resultJSON);
Map<String, Object> resultMap = XMLUtilsEx.deserialize(resultJSON, Map.class);
if (resultMap.containsKey("return_code")) {
return resultMap;
}
return null;
}
public static Map<String, String> getJSPayParam(String orderId, String orderName, BigDecimal price, String ipAddress, String openId) {
Map<String, String> payParam = new HashMap<String, String>();
payParam.put("appId", PayPropertySupport.getProperty("pay.weixin.appid"));
String timestamp = String.valueOf((System.currentTimeMillis() / 1000));
payParam.put("timeStamp", timestamp);
payParam.put("nonceStr", StringUtilsEx.bytes2Hex(SignatureUtils.md5(timestamp)));
logger.debug("openId:"+openId+",orderId:"+orderId+",orderName:"+orderName+",price:"+price+",ipAddress:"+ipAddress);
String prepayId = getPayPrepayId(orderId, orderName, price, ipAddress, WeixinPayTradeType.JSAPI.toString(), openId);
payParam.put("package", "prepay_id="+prepayId);
payParam.put("signType", "MD5");
payParam.put("paySign", getSign(payParam));
logger.debug(payParam.toString());
return payParam;
}
public static void main(String[] args) throws Exception {
getJSPayParam("202011291739521101", "勘察安装增项费用", new BigDecimal(1), "10.0.0.57", "o3mCTwWDWjXOxkTRrTWT7NY_mDTs");
}
}
package com.starcharge.component.pay.weixin;
/**
* @author kevin
* @create 2020/11/18 14:39
*/
public enum WeixinPayTradeType {
// 公众号支付
JSAPI,
// 扫码支付
NATIVE,
// APP支付
APP
}
package com.starcharge.config;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import feign.Client;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
@Configuration
public class FeignOkhttpConfig {
@Bean
public OkHttpClient okHttpClient(){
return new OkHttpClient.Builder()
.connectionPool(new ConnectionPool(50, 5, TimeUnit.MINUTES))
.readTimeout(200, TimeUnit.MILLISECONDS)
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
}
@Bean
public Client feignClient(OkHttpClient okHttpClient){
return new feign.okhttp.OkHttpClient(okHttpClient);
}
}
\ No newline at end of file
package com.starcharge.config;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ihidea.component.api.v2.BaseResponse;
import com.ihidea.core.support.exception.ServiceException;
@ControllerAdvice
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(ServiceException.class)
@ResponseBody
public BaseResponse<String> serviceExceptionHandler(HttpServletRequest req, ServiceException e) {
String message = e.getMessage();
String code = e.getCode();
logger.error("ex:", e);
return BaseResponse.responseWithException(code, message);
}
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public BaseResponse<String> runtimeExceptionHandler(HttpServletRequest req, RuntimeException e) {
logger.error("ex:", e);
return BaseResponse.responseWithException(null, e.getMessage());
}
@ExceptionHandler(Exception.class)
@ResponseBody
public BaseResponse<String> defaultExceptionHandler(HttpServletRequest req, Exception e) {
logger.error("ex:", e);
return BaseResponse.responseWithException(null, e.getMessage());
}
}
\ No newline at end of file
package com.starcharge.config;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
public class JasksonConfig {
@Bean
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverterConfiguration() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(buildObjectMapper());
return converter;
}
@Bean
public ObjectMapper buildObjectMapper() {
ObjectMapper om = new ObjectMapper();
om.setDateFormat(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"));
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
om.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
om.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
return om;
}
}
\ No newline at end of file
package com.starcharge.config;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 配置redis序列化
*
* @author Kevin Yu
*/
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory, RedisSerializer<Object> redisSerializer) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//RedisTemplate对象需要指明Key序列化方式,如果声明StringRedisTemplate对象则不需要
template.setKeySerializer(StringRedisSerializer.UTF_8);
template.setValueSerializer(redisSerializer);
template.setHashKeySerializer(StringRedisSerializer.UTF_8);
template.setHashValueSerializer(redisSerializer);
//template.setEnableTransactionSupport(true);//是否启用事务
template.afterPropertiesSet();
return template;
}
/**
* 自定义redis序列化的机制
*
* @return
*/
@Bean
public RedisSerializer<Object> redisSerializer() {
ObjectMapper objectMapper = new ObjectMapper();
//反序列化时候遇到不匹配的属性并不抛出异常
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//序列化时候遇到空对象不抛出异常
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//反序列化的时候如果是无效子类型,不抛出异常
objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
//指定DATE序列化格式,默认时间戳
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//不使用默认的dateTime进行序列化,
objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
//使用JSR310提供的序列化类,里面包含了大量的JDK8时间序列化类
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
objectMapper.registerModule(javaTimeModule);
//指定序列化输入的类型@class JsonTypeInfo.As.PROPERTY-表示以对象属性的形式 WRAPPER_ARRAY-表示以数组的形式
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
//配置null值的序列化器
GenericJackson2JsonRedisSerializer.registerNullValueSerializer(objectMapper, null);
return new GenericJackson2JsonRedisSerializer(objectMapper);
}
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("id", 1);
map.put("name", "Kevin");
map.put("adult", Boolean.TRUE);
map.put("birthday", new Date());
map.put("createTime", LocalDateTime.now());
byte[] mapBytes=new RedisConfig().redisSerializer().serialize(map);
System.out.println(new String(mapBytes));
System.out.println(((Map)new RedisConfig().redisSerializer().deserialize(mapBytes)).get("name"));
}
}
//package com.starcharge.config;
//
//import org.springframework.cache.CacheManager;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.data.redis.cache.RedisCacheConfiguration;
//import org.springframework.data.redis.cache.RedisCacheManager;
//import org.springframework.data.redis.cache.RedisCacheWriter;
//import org.springframework.data.redis.connection.RedisConnectionFactory;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
//import org.springframework.data.redis.serializer.RedisSerializationContext;
//import org.springframework.data.redis.serializer.RedisSerializer;
//import org.springframework.data.redis.serializer.StringRedisSerializer;
//
///**
// * @Description redis序列化
// * @author liwenxiang
// * @date 2020/7/17 10:37
// */
//@Configuration
//public class RedisTemplateConfig {
// @Bean(name = "redisTemplate")
// public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
// redisTemplate.setConnectionFactory(redisConnectionFactory);
// redisTemplate.setKeySerializer(keySerializer());
// redisTemplate.setHashKeySerializer(keySerializer());
// redisTemplate.setValueSerializer(valueSerializer());
// redisTemplate.setHashValueSerializer(valueSerializer());
// return redisTemplate;
// }
//
// private RedisSerializer<String> keySerializer() {
// return new StringRedisSerializer();
// }
//
// private RedisSerializer<Object> valueSerializer() {
// return new GenericJackson2JsonRedisSerializer();
// }
//
// @Bean
// CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
// //初始化一个RedisCacheWriter
// RedisCacheWriter redisCacheWriter= RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
// //设置CacheManager的值序列化方式为json序列化
// RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
// RedisSerializationContext.SerializationPair<Object> pair= RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer);
// RedisCacheConfiguration defaultCacheConfig= RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
// // 设置默认超过期时间是30秒
// // defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
// // 初始化RedisCacheManager
// RedisCacheManager cacheManager= new RedisCacheManager(redisCacheWriter,defaultCacheConfig);
// return cacheManager;
// }
//
//}
package com.starcharge.config;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author SC5840
* @date 2021/8/20 11:29
* @Description: TODO
*/
@Configuration
public class RedissonConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private String port;
@Value("${spring.redis.password}")
private String password;
@Bean
public RedissonClient getRedisson() {
Config config = new Config();
config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password);
return Redisson.create(config);
}
}
package com.starcharge.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@EnableKnife4j
@ConditionalOnExpression("!'${spring.profiles.active}'.equals('prod')")
public class SwaggerConfig {
@Bean
public Docket createDocket() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(buildApiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.starcharge.wios")).paths(PathSelectors.ant("/api/**")).build()
.groupName("wios后台接口");
}
@Bean
public Docket web_api_prdt() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(buildApiInfo()).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.ant("/api2/**")).build().groupName("app接口").pathMapping("/");
}
@Bean
public Docket minaApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(buildApiInfo()).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.ant("/mina/**")).build().groupName("微信小程序接口").pathMapping("/");
}
@Bean
public Docket wxApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(buildApiInfo()).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.ant("/wx/**")).build().groupName("微信公众号接口").pathMapping("/");
}
private ApiInfo buildApiInfo() {
return new ApiInfoBuilder().version("v1.0.0").description("wios接口定义").title("wios API").build();
}
}
\ No newline at end of file
package com.starcharge.wios.Import;
import java.util.List;
public interface Import {
public List<?> handle(List<Object> list);
}
package com.starcharge.wios.Import;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import cn.hutool.core.date.DateUtil;
import jxl.*;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ihidea.core.support.SpringContextLoader;
import com.ihidea.core.support.exception.ServiceException;
import com.ihidea.core.support.servlet.ServletHolderFilter;
import com.ihidea.core.util.FileUtilsEx;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
* excel导入控制类
*
* @author xgl
* @version [版本号, 2018年7月25日]
*/
@RestController
@Api(tags = "导入模块")
public class ImportController {
/**
* excel导入数据解析
*
* @param file excel 表格
* @param serviceName 服务类型名称
* @param needUpload 是否需要上传文件至oss
* @param storeName 上传文件存储bucket
* @param uploadFilePath 上传文件路径
* @return 导入异常信息
*/
@PostMapping(value = "import.do")
@ApiOperation(value = "导入excel")
@ApiImplicitParams({
@ApiImplicitParam(name = "serviceName", value = "service名称", dataType = "String", paramType = "query", required = true),})
public List<?> importCommon(HttpServletRequest request, String serviceName) {
Map<String, Object> param = ServletHolderFilter.getContext().getParamMap();
List<Object[]> fileList = new ArrayList<Object[]>();
for (String nameKey : param.keySet()) {
Object _obj = param.get(nameKey);
if (_obj != null && _obj instanceof List && ((List)_obj).size() > 0) {
Object fileItem = ((List)_obj).get(0);
if (fileItem instanceof DiskFileItem) {
// 如果是servlet2上传的文件
List<DiskFileItem> diskFileItemList = (List<DiskFileItem>)_obj;
for (DiskFileItem file : diskFileItemList) {
String fileName = FileUtilsEx.getFileNameByPath(file.getName());
byte[] fileContent = file.get();
fileList.add(new Object[]{fileName, fileContent});
}
}
}
}
Import importClass = null;
if (!StringUtils.isEmpty(serviceName)) {
// 获取serviceName对应的bean
importClass = SpringContextLoader.getBean(serviceName, Import.class);
}
// 返回的结果list
List<Object> list = new ArrayList<>();
// if (!file.isEmpty()) {
Workbook rwb = null;
try {
// 输入流获取对象
rwb = Workbook.getWorkbook(new ByteArrayInputStream((byte[])fileList.get(0)[1]));
// 获取页数数组
Sheet[] sheetArr = rwb.getSheets();
for (Sheet rs : sheetArr) {
Cell[] headCells = rs.getRow(0);
int headCellSize = headCells.length;
// 每页行数
for (int i = 0; i < rs.getRows(); i++) {
List<String> cellList = new ArrayList<>();
// 每行单元数组
Cell[] cells = rs.getRow(i);
for (Cell cell : cells) {
if(cell.getType() == CellType.DATE){
DateCell dc = (DateCell)cell;
cellList.add(DateUtil.date(dc.getDate()).toDateStr());
}else{
cellList.add(cell.getContents());
}
}
if (headCellSize > cells.length) {
for (int k = 0; k < headCellSize - cells.length; k++) {
cellList.add("");
}
}
list.add(cellList);
}
}
} catch (Exception e) {
throw new ServiceException(e.getMessage());
} finally {
// 关闭数据流
if (rwb != null) {
rwb.close();
}
}
// } else {
// throw new ServiceException("文件为空");
// }
if (importClass != null) {
// 返回具体实现类处理结果
List<?> returnList = importClass.handle(list);
returnList.remove(0);
return returnList;
} else {
list.remove(0);
return list;
}
}
}
package com.starcharge.wios.Import.impl;
import cn.hutool.core.util.StrUtil;
import com.starcharge.wios.Import.Import;
import com.starcharge.wios.dao.OrderDao;
import com.starcharge.wios.dao.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class AudiInvoiceImport implements Import {
@Autowired
private OrderDao orderDao;
@SuppressWarnings("unchecked")
@Override
public List<?> handle(List<Object> list) {
for (int i = 1; i < list.size(); i++) {
List<String> childList = (List<String>) list.get(i);
String outOrderId = childList.get(2);// 车企安装单号
String packageDeviceInvoiceStatus = childList.get(10);// 套包内(设备)开票状态
String packageDeviceReceiveStatus = childList.get(12);// 套包内(设备)收款状态
String packageInstallInvoiceStatus = childList.get(14);// 车套包内(安装)开票状态
String packageInstallReceiveStatus = childList.get(16);// 套包内(安装)收款状态
if (StringUtils.isEmpty(outOrderId)) {
childList.add("error:缺少车企安装单号");
continue;
}
Order order = orderDao.selectByOutOrderId(outOrderId);
if (order == null) {
childList.add("error:订单不存在");
continue;
} else {
childList.set(2, outOrderId + "_" + order.getId());
}
if (StrUtil.isNotBlank(packageDeviceInvoiceStatus)) {
childList.set(10, packageDeviceInvoiceStatus + "_1");
} else {
childList.set(10, packageDeviceInvoiceStatus + "_0");
}
if (StrUtil.isNotBlank(packageDeviceReceiveStatus)) {
childList.set(12, packageDeviceReceiveStatus + "_1");
} else {
childList.set(12, packageDeviceReceiveStatus + "_0");
}
if (StrUtil.isNotBlank(packageInstallInvoiceStatus)) {
childList.set(14, packageInstallInvoiceStatus + "_1");
} else {
childList.set(14, packageInstallInvoiceStatus + "_0");
}
if (StrUtil.isNotBlank(packageInstallReceiveStatus)) {
childList.set(16, packageInstallReceiveStatus + "_1");
} else {
childList.set(16, packageInstallReceiveStatus + "_0");
}
}
return list;
}
}
package com.starcharge.wios.Import.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.starcharge.warehouse.dto.materials.MaterialsDTO;
import com.starcharge.wios.Import.Import;
import com.starcharge.wios.service.WarehouseService;
/**
* 合同增项导入
*
* @author xgl
* @version [版本号, 2020年10月24日]
*/
@Service
public class ContractItemExpandImport implements Import {
@Autowired
private WarehouseService warehouseService;
@SuppressWarnings("unchecked")
@Override
public List<?> handle(List<Object> list) {
for (int i = 1; i < list.size(); i++) {
List<String> childList = (List<String>)list.get(i);
String model = childList.get(0);// 规格型号
String code = childList.get(1);// 物料编码
String name = childList.get(2);// 物料名称
if (StringUtils.isEmpty(model) || StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) {
childList.add("error:参数不能未空");
continue;
}
List<MaterialsDTO> itemList = warehouseService.qryMaterialsCount(name, code, model, 2);
if (itemList.isEmpty()) {
childList.add("error:增项不存在");
continue;
} else {
childList.set(0, model + "_" + itemList.get(0).getId());
}
}
return list;
}
}
package com.starcharge.wios.Import.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.starcharge.warehouse.dto.materials.MaterialsDTO;
import com.starcharge.wios.Import.Import;
import com.starcharge.wios.service.WarehouseService;
/**
* 合同充电桩导入
*
* @author xgl
* @version [版本号, 2020年10月21日]
*/
@Service
public class ContractItemPriceImport implements Import {
@Autowired
private WarehouseService warehouseService;
@SuppressWarnings("unchecked")
@Override
public List<?> handle(List<Object> list) {
for (int i = 1; i < list.size(); i++) {
List<String> childList = (List<String>)list.get(i);
String model = childList.get(0);// 规格型号
String code = childList.get(1);// 物料编码
String name = childList.get(2);// 物料名称
// String price = childList.get(3);// 单价不含税
// String taxRate = childList.get(4);// 税率
if (StringUtils.isEmpty(model) || StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) {
childList.add("error:参数不能未空");
continue;
}
List<MaterialsDTO> itemList = warehouseService.qryMaterialsCount(name, code, model, 3);
if (itemList.isEmpty()) {
childList.add("error:充电桩不存在");
continue;
} else {
childList.set(0, model + "_" + itemList.get(0).getId());
}
}
return list;
}
}
package com.starcharge.wios.Import.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.starcharge.wios.Import.Import;
import com.starcharge.wios.dao.RegionDao;
import com.starcharge.wios.dao.entity.Region;
/**
* 主机厂合同区域价格导入
*
* @author xgl
* @version [版本号, 2020年10月22日]
*/
@Service
public class OemContractPriceImport implements Import {
@Autowired
private RegionDao regionDao;
@SuppressWarnings("unchecked")
@Override
public List<?> handle(List<Object> list) {
for (int i = 1; i < list.size(); i++) {
List<String> childList = (List<String>)list.get(i);
String regionName = childList.get(0);// 区域名称
if (StringUtils.isEmpty(regionName)) {
childList.add("error:参数不能未空");
continue;
}
Region region = regionDao.selectSingleByName(regionName);
if (region == null) {
childList.add("error:区域不存在");
continue;
} else {
childList.set(0, regionName + "_" + region.getIdTree());
}
}
return list;
}
}
package com.starcharge.wios.Import.impl;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.starcharge.warehouse.dto.materials.MaterialsDTO;
import com.starcharge.wios.Import.Import;
import com.starcharge.wios.dao.OemContractDao;
import com.starcharge.wios.dao.OemContractItemDao;
import com.starcharge.wios.dao.OemDao;
import com.starcharge.wios.dao.RegionDao;
import com.starcharge.wios.dao.entity.Oem;
import com.starcharge.wios.dao.entity.Region;
import com.starcharge.wios.enums.ContractStatus;
import com.starcharge.wios.service.WarehouseService;
import com.starcharge.wios.vo.OemContractItemVo;
import com.starcharge.wios.vo.OemContractVo;
@Service
public class SupplierContractPriceImport implements Import {
@Autowired
private RegionDao regionDao;
@Autowired
private OemDao oemDao;
@Autowired
private OemContractDao oemContractDao;
@Autowired
private OemContractItemDao oemContractItemDao;
@Autowired
private WarehouseService warehouseService;
@SuppressWarnings("unchecked")
@Override
public List<?> handle(List<Object> list) {
for (int i = 1; i < list.size(); i++) {
List<String> childList = (List<String>)list.get(i);
String regionName = childList.get(0);// 区域名称
String oemName = childList.get(1);// 主机厂名称
String deviceName = childList.get(2);// 设备名称
// String surveyPrice = childList.get(3);// 勘测价格(不含税)
// String installPrice = childList.get(4);// 勘测价格(含税)
// String remark = childList.get(5);// 备注
if (StringUtils.isEmpty(regionName) || StringUtils.isEmpty(oemName)) {
childList.add("error:参数不能未空");
continue;
}
Region region = regionDao.selectSingleByName(regionName);
if (region == null) {
childList.add("error:区域不存在");
continue;
} else {
childList.set(0, regionName + "_" + region.getIdTree());
}
Oem oem = oemDao.selectSingleByName(oemName);
if (oem == null) {
childList.add("error:主机厂/经销商不存在");
continue;
} else {
childList.set(1, oemName + "_" + oem.getId());
}
if (!StringUtils.isEmpty(deviceName)) {
List<OemContractVo> oemContractList =
oemContractDao.selectByStatusAndOemId(oem.getId().intValue(), ContractStatus.EFFECTIVE.getType());
if (oemContractList.isEmpty()) {
childList.add("error:该主机厂/经销商无此设备");
continue;
}
List<OemContractItemVo> contractItems = oemContractItemDao.selectByContractId(oemContractList.get(0).getId().intValue());
for (OemContractItemVo vo : contractItems) {
MaterialsDTO dto = warehouseService.getMaterialById(vo.getItemId());
if (dto != null) {
vo.setItemCode(dto.getMaterialsCode());
vo.setItemModel(dto.getRegularModel());
vo.setItemName(dto.getMaterialsName());
}
}
List<OemContractItemVo> ociList =
contractItems.stream().filter(item -> deviceName.equals(item.getItemName())).collect(Collectors.toList());
if (ociList.isEmpty()) {
childList.add("error:设备不存在");
continue;
} else {
childList.set(2, deviceName + "_" + ociList.get(0).getItemId());
}
}
}
return list;
}
}
package com.starcharge.wios.Import.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.starcharge.wios.Import.Import;
import com.starcharge.wios.auth.dao.AccountMapper;
import com.starcharge.wios.auth.dao.model.AccountCriteria;
import com.starcharge.wios.dao.SupplierDao;
import com.starcharge.wios.dao.entity.Supplier;
@Service
public class SupplierImport implements Import {
@Autowired
private SupplierDao supplierDao;
@Autowired
private AccountMapper accountMapper;
@SuppressWarnings("unchecked")
@Override
public List<?> handle(List<Object> list) {
for (int i = 1; i < list.size(); i++) {
List<String> childList = (List<String>)list.get(i);
String code = childList.get(0);// 编码
String supplierName = childList.get(1);// 服务商名称
String account = childList.get(7);// 管理账户
String type = childList.get(8);// 类别
if (StringUtils.isEmpty(code) || StringUtils.isEmpty(supplierName) || StringUtils.isEmpty(account)
|| StringUtils.isEmpty(type)) {
childList.add("error:缺少参数");
continue;
}
List<Supplier> supplierList = supplierDao.selectOnly(code, supplierName);
if (!supplierList.isEmpty()) {
childList.add("error:编码或服务商名称已存在");
continue;
}
AccountCriteria accountCriteria = new AccountCriteria();
accountCriteria.createCriteria().andAccountEqualTo(account);
int count = accountMapper.countByExample(accountCriteria);
if (count > 0) {
childList.add("error:登录账户已存在");
continue;
}
if (!"A".equals(type) && !"B".equals(type) && !"C".equals(type)) {
childList.add("error:类型只能是ABC中的一个");
}
}
return list;
}
}
package com.starcharge.wios.Import.impl;
import cn.hutool.core.util.StrUtil;
import com.starcharge.wios.Import.Import;
import com.starcharge.wios.dao.OrderDao;
import com.starcharge.wios.dao.SupplierDao;
import com.starcharge.wios.dao.entity.Order;
import com.starcharge.wios.dao.entity.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class SupplierInvoiceImport implements Import {
@Autowired
private OrderDao orderDao;
@Autowired
private SupplierDao supplierDao;
@SuppressWarnings("unchecked")
@Override
public List<?> handle(List<Object> list) {
for (int i = 1; i < list.size(); i++) {
List<String> childList = (List<String>) list.get(i);
String outOrderId = childList.get(1);// 车企安装单号
String supplierReceiveInvoiceStatus = childList.get(15);// 服务商收票状态
String supplierPayStatus = childList.get(17);// 服务商付款状态
if (StringUtils.isEmpty(outOrderId)) {
childList.add("error:缺少车企安装单号");
continue;
}
Order order = orderDao.selectByOutOrderId(outOrderId);
if (order == null) {
childList.add("error:订单不存在");
continue;
}else{
childList.set(1, outOrderId + "_" + order.getId());
}
Supplier supplier=supplierDao.selectById(order.getInstallSupplierId());
if("A".equals(supplier.getLevel())){
childList.add("error:自建服务商团队不需要结算");
continue;
}
if(StrUtil.isNotBlank(supplierReceiveInvoiceStatus)){
childList.set(15,supplierReceiveInvoiceStatus+"_1");
}else{
childList.set(15,supplierReceiveInvoiceStatus+"_0");
}
if(StrUtil.isNotBlank(supplierPayStatus)){
childList.set(17,supplierPayStatus+"_1");
}else{
childList.set(17,supplierPayStatus+"_0");
}
}
return list;
}
}
package com.starcharge.wios.Import.impl;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.starcharge.wios.Import.Import;
import com.starcharge.wios.dao.OrderDao;
import com.starcharge.wios.dao.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class VwInvoiceImport implements Import {
@Autowired
private OrderDao orderDao;
@SuppressWarnings("unchecked")
@Override
public List<?> handle(List<Object> list) {
for (int i = 1; i < list.size(); i++) {
List<String> childList = (List<String>) list.get(i);
String outOrderId = childList.get(1);// 车企安装单号
String packageDeviceInvoiceStatus = childList.get(10);// 套包内(设备)开票状态
String packageDeviceReceiveStatus = childList.get(12);// 套包内(设备)收款状态
String packageInstallInvoiceStatus = childList.get(14);// 车套包内(安装)开票状态
String packageInstallReceiveStatus = childList.get(16);// 套包内(安装)收款状态
if (StringUtils.isEmpty(outOrderId)) {
childList.add("error:缺少车企安装单号");
continue;
}
Order order = orderDao.selectByOutOrderId(outOrderId);
if (order == null) {
childList.add("error:订单不存在");
continue;
}else{
childList.set(1, outOrderId + "_" + order.getId());
}
if(StrUtil.isNotBlank(packageDeviceInvoiceStatus)){
childList.set(10,packageDeviceInvoiceStatus+"_1");
}else{
childList.set(10,packageDeviceInvoiceStatus+"_0");
}
if(StrUtil.isNotBlank(packageDeviceReceiveStatus)){
childList.set(12,packageDeviceReceiveStatus+"_1");
}else{
childList.set(12,packageDeviceReceiveStatus+"_0");
}
if(StrUtil.isNotBlank(packageInstallInvoiceStatus)){
childList.set(14,packageInstallInvoiceStatus+"_1");
}else{
childList.set(14,packageInstallInvoiceStatus+"_0");
}
if(StrUtil.isNotBlank(packageInstallReceiveStatus)){
childList.set(16,packageInstallReceiveStatus+"_1");
}else{
childList.set(16,packageInstallReceiveStatus+"_0");
}
}
return list;
}
}
package com.starcharge.wios.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ihidea.component.api.v2.BaseResponse;
import com.ihidea.core.support.exception.ServiceException;
import com.starcharge.base.util.Assert;
import com.starcharge.wios.app.dto.AppOrderDTO;
import com.starcharge.wios.app.dto.AppOrderDetailDTO;
import com.starcharge.wios.app.dto.AppOrderInstallDTO;
import com.starcharge.wios.app.dto.AppPayBillDTO;
import com.starcharge.wios.app.service.AppOrderService;
import com.starcharge.wios.dao.entity.MaterialConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
* 订单相关接口
*
* @author xgl
* @version [版本号, 2020年10月27日]
*/
@RestController
@RequestMapping("api2")
@Api(tags = "订单相关接口")
public class AppOrderController {
@Autowired
private AppOrderService orderService;
@GetMapping(value = "order/qryList")
@ApiOperation(value = "查询订单列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "camsPhone", value = "cams手机号", dataType = "String", paramType = "query", required = true),})
public BaseResponse<List<AppOrderDTO>> getList(String camsPhone) {
Assert.notEmpty(camsPhone, "手机号不能为空");
return new BaseResponse<>(orderService.getList(camsPhone));
}
@GetMapping(value = "order/qryInstallDetail")
@ApiOperation(value = "查询安装订单详情")
@ApiImplicitParams({@ApiImplicitParam(name = "orderId", value = "工单号", dataType = "String", paramType = "query", required = true),})
public BaseResponse<AppOrderInstallDTO> qryInstallDetail(String orderId) {
Assert.notEmpty(orderId, "工单号不能为空");
AppOrderInstallDTO orderInstallDTO = orderService.getInstallDetail(orderId);
return new BaseResponse<AppOrderInstallDTO>(orderInstallDTO);
}
@GetMapping(value = "order/qryOrderDetail")
@ApiOperation(value = "查询订单详情")
@ApiImplicitParams({@ApiImplicitParam(name = "orderId", value = "工单号", dataType = "String", paramType = "query", required = true),})
public BaseResponse<AppOrderDetailDTO> qryOrderDetail(String orderId) {
Assert.notEmpty(orderId, "工单号不能为空");
AppOrderDetailDTO result = orderService.getOrderDetail(orderId);
return new BaseResponse<AppOrderDetailDTO>(result);
}
@GetMapping(value = "order/qryExpandIntro")
@ApiOperation(value = "查询报装说明")
@ApiImplicitParams({@ApiImplicitParam(name = "orderId", value = "工单号", dataType = "String", paramType = "query", required = true),})
public BaseResponse<String> getExpandIntro(String orderId) {
Assert.notEmpty(orderId, "缺少参数");
MaterialConfig mc = orderService.getExpandIntro(orderId);
if (mc != null)
return new BaseResponse<String>(mc.getContent());
else
return new BaseResponse<String>();
}
/**
* 报装
*
* @param orderId
* @param expandStatus
* @param expandFailReason
* @param expandFailOperate
*/
@PostMapping(value = "order/expand")
@ApiOperation(value = "报装")
@ApiImplicitParams({@ApiImplicitParam(name = "orderId", value = "订单id", dataType = "String", paramType = "query", required = true),
@ApiImplicitParam(name = "expandStatus", value = "报装状态 1:通过 2:不通过", dataType = "int", paramType = "query", required = true),
@ApiImplicitParam(name = "expandFailReason", value = "报装不通过原因", dataType = "String", paramType = "query", required = false),
@ApiImplicitParam(name = "expandFailOperate", value = "报装不通过后订单后续操作 1:换其他用电类型继续安装 2:不安装了", dataType = "int", paramType = "query", required = false),})
public BaseResponse<Object> expand(String orderId, Integer expandStatus, String expandFailReason, Integer expandFailOperate) {
if (StringUtils.isEmpty(orderId) || expandStatus == null) {
throw new ServiceException("缺少参数");
}
if (expandStatus.intValue() != 1 && expandStatus.intValue() != 2) {
throw new ServiceException("状态不合法");
}
orderService.expand(orderId, expandStatus, expandFailReason, expandFailOperate);
return new BaseResponse<>();
}
/**
* 查询账单列表
*
* @param camsPhone
* @return
*/
@GetMapping(value = "order/qryBillList")
@ApiOperation(value = "查询账单列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "camsPhone", value = "cams手机号", dataType = "String", paramType = "query", required = false),
@ApiImplicitParam(name = "orderId", value = "工单号", dataType = "String", paramType = "query", required = false),
@ApiImplicitParam(name = "status", value = "状态 0-未支付 1-已支付", dataType = "int", paramType = "query", required = false),})
public BaseResponse<List<AppPayBillDTO>> qryBillList(String camsPhone, String orderId, Integer status) {
if (!StringUtils.isEmpty(camsPhone) && !StringUtils.isEmpty(orderId)) {
throw new ServiceException("cams手机号和工单号不能同时为空");
}
List<AppPayBillDTO> list = orderService.qryBill(camsPhone, orderId, status);
return new BaseResponse<>(list);
}
}
package com.starcharge.wios.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ihidea.component.api.v2.BaseResponse;
import com.ihidea.core.support.exception.ServiceException;
import com.ihidea.core.util.StringUtilsEx;
import com.starcharge.wios.dao.entity.OrderScore;
import com.starcharge.wios.service.OrderScoreService;
import com.starcharge.wios.service.OrderService;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
* 订单评分表 管理 API
*
* @author yongfu.liu@wanbangauto.com 2020-10-10 14:08:14
*/
@RestController
@RequestMapping("api2")
@Api(tags = "订单评分表的接口")
public class AppOrderScoreController {
@Autowired
private OrderScoreService orderScoreService;
@Autowired
private OrderService orderService;
/**
* 查询订单评分
*
* @return
*/
@GetMapping(value = "orderScore/getOrderScoreByOrderId")
@ApiOperation(value = "查询订单评分")
@ApiImplicitParam(paramType = "query", name = "orderId", value = "订单表ID", required = true, dataType = "String")
public BaseResponse<Object> list(String orderId) {
return new BaseResponse<Object>(orderScoreService.getOrderScoreByOrderId(orderId));
}
/**
* 保存订单回访信息
*
* @param list
*/
@PostMapping(value = "orderScore/save")
@ApiOperation(value = "保存订单回访信息")
@ApiImplicitParams({@ApiImplicitParam(name = "orderId", value = "订单id", dataType = "String", paramType = "query", required = true),
@ApiImplicitParam(name = "visitContent", value = "意见或建议", dataType = "String", paramType = "query", required = true),
@ApiImplicitParam(name = "files", value = "图片地址,多个逗号分割", dataType = "String", paramType = "query", required = true),
@ApiImplicitParam(name = "list", value = "格式:[{\"id\":9,\"score\":70},{\"id\":12,\"score\":60}]", dataType = "String", paramType = "query", required = true),
})
public BaseResponse<Object> save(String orderId, String visitContent, String files, String list) {
if (StringUtils.isEmpty(orderId)) {
throw new ServiceException("缺少参数");
}
if (!StringUtils.isEmpty(files)) {
files = StringUtilsEx.unescapeXss(files);
}
//更新评分明细
JSONArray jsonArray = JSONUtil.parseArray(list);
if(jsonArray.size()>0){
for(int i = 0 ;i<jsonArray.size();i++){
JSONObject jsonObject =jsonArray.getJSONObject(i);
OrderScore orderScore = new OrderScore();
orderScore.setId(Long.parseLong(String.valueOf(jsonObject.get("id"))));
orderScore.setScore(Double.valueOf(String.valueOf(jsonObject.get("score"))));
orderScoreService.update(orderScore);
}
}
//增加已回访的状态
orderService.visitOrder(orderId, visitContent, files, jsonArray);
return new BaseResponse<>();
}
}
package com.starcharge.wios.app.controller;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.starcharge.wios.app.service.AppOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
* 回调通知
*
* @author xgl
* @version [版本号, 2020年10月27日]
*/
@RestController
@RequestMapping("api2")
@Api(tags = "回调通知")
public class CallbackController {
@Autowired
private AppOrderService appOrderService;
private Logger logger = LoggerFactory.getLogger(CallbackController.class);
/**
* 增项费用支付成功
*
* @param orderId
* @param status
* @return
*/
@PostMapping(value = "order/paySuccess")
@ApiOperation(value = "增项费用支付成功")
@ApiImplicitParams({@ApiImplicitParam(name = "orderId", value = "工单号", dataType = "String", paramType = "query", required = true),
@ApiImplicitParam(name = "thirdUserId", value = "用户唯一识别号", dataType = "String", paramType = "query", required = true),
@ApiImplicitParam(name = "status", value = "支付状态 1:成功", dataType = "int", paramType = "query", required = true),
@ApiImplicitParam(name = "payMethod", value = "支付方式 3:微信 4:支付宝", dataType = "int", paramType = "query", required = true),})
public Map<String, Object> paySuccess(String orderId, String thirdUserId, Integer status, Integer payMethod) {
logger.info("[增项费用支付成功回调]orderId={},thirdUserId={},status={}", orderId, thirdUserId, status);
Map<String, Object> returnMap = new HashMap<String, Object>();
if (StringUtils.isEmpty(orderId) || status == null || payMethod == null || StringUtils.isEmpty(thirdUserId)) {
returnMap.put("code", 400);
returnMap.put("msg", "缺少参数");
return returnMap;
}
if (status.intValue() == 1)
appOrderService.updateInstallOrderPayStatus(orderId, thirdUserId, 1, payMethod.intValue());
returnMap.put("code", 200);
returnMap.put("msg", "");
return returnMap;
}
}
package com.starcharge.wios.app.dto;
import io.swagger.annotations.ApiModelProperty;
public class AppOperateLogDTO {
@ApiModelProperty(value = "名称")
private String name;
@ApiModelProperty(value = "值")
private String value;
@ApiModelProperty(value = "日期")
private String date;
@ApiModelProperty(value = "是否显示查看评价按钮")
private boolean showRating = false;// 是否显示查看评价按钮
public String getName() {
return name;
}
public String getValue() {
return value;
}
public String getDate() {
return date;
}
public void setName(String name) {
this.name = name;
}
public void setValue(String value) {
this.value = value;
}
public void setDate(String date) {
this.date = date;
}
public boolean isShowRating() {
return showRating;
}
public void setShowRating(boolean showRating) {
this.showRating = showRating;
}
}
package com.starcharge.wios.app.dto;
import java.math.BigDecimal;
import io.swagger.annotations.ApiModelProperty;
public class AppOrderDTO {
@ApiModelProperty(value = "工单号")
private String orderId;// 工单号
@ApiModelProperty(value = "地址")
private String address;// 地址
@ApiModelProperty(value = "用户姓名")
private String userName;// 用户姓名
@ApiModelProperty(value = "车主性别 0-女 1-男")
private Integer userSex;
@ApiModelProperty(value = "订单状态(全部)")
private Integer status;// 订单状态
@ApiModelProperty(value = "订单状态(1:接单 2:预约 3:勘察 4:安装 5:评价)")
private Integer relativeStatus;// 订单状态(1:接单 2:预约 3:勘察 4:安装 5:评价)
@ApiModelProperty(value = "订单状态说明")
private String statusText;// 状态说明
@ApiModelProperty(value = "时间")
private String time;// 时间
@ApiModelProperty(value = "派单时间")
private String dispatchTime;// 派单时间
@ApiModelProperty(value = "勘测预约时间")
private String surveyReserveTime;// 勘测预约时间
@ApiModelProperty(value = "开始勘测时间")
private String surveyStartTime;// 开始勘测时间
@ApiModelProperty(value = "安装预约时间")
private String installReserveTime;// 安装预约时间
@ApiModelProperty(value = "开始安装时间")
private String installStartTime;// 开始安装时间
@ApiModelProperty(value = "回访时间")
private String returnVisitTime;// 回访时间
@ApiModelProperty(value = "联系人")
private String contactName;// 联系人
@ApiModelProperty(value = "联系电话")
private String contactPhone;// 联系电话
@ApiModelProperty(value = "账单费用")
private BigDecimal fee;
@ApiModelProperty(value = "安装完成时间")
private String installFinishTime;
@ApiModelProperty(value = "账单id")
private String billId;
@ApiModelProperty(value = "账单状态 0-未支付 1-已支付")
private Integer billStatus;
@ApiModelProperty(value = "报装状态 1:通过 2:不通过")
private Integer expandStatus;
@ApiModelProperty(value = "报装不通过后订单后续操作 1:换其他用电类型继续安装 2:不安装了")
private Integer expandFailOperate;
public String getOrderId() {
return orderId;
}
public String getAddress() {
return address;
}
public Integer getStatus() {
return status;
}
public String getTime() {
return time;
}
public String getContactName() {
return contactName;
}
public String getContactPhone() {
return contactPhone;
}
public BigDecimal getFee() {
return fee;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public void setAddress(String address) {
this.address = address;
}
public void setStatus(Integer status) {
this.status = status;
}
public void setTime(String time) {
this.time = time;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public String getStatusText() {
return statusText;
}
public void setStatusText(String statusText) {
this.statusText = statusText;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getRelativeStatus() {
return relativeStatus;
}
public void setRelativeStatus(Integer relativeStatus) {
this.relativeStatus = relativeStatus;
}
public String getBillId() {
return billId;
}
public Integer getBillStatus() {
return billStatus;
}
public void setBillId(String billId) {
this.billId = billId;
}
public void setBillStatus(Integer billStatus) {
this.billStatus = billStatus;
}
public Integer getExpandStatus() {
return expandStatus;
}
public Integer getExpandFailOperate() {
return expandFailOperate;
}
public void setExpandStatus(Integer expandStatus) {
this.expandStatus = expandStatus;
}
public void setExpandFailOperate(Integer expandFailOperate) {
this.expandFailOperate = expandFailOperate;
}
public String getInstallFinishTime() {
return installFinishTime;
}
public void setInstallFinishTime(String installFinishTime) {
this.installFinishTime = installFinishTime;
}
public Integer getUserSex() {
return userSex;
}
public void setUserSex(Integer userSex) {
this.userSex = userSex;
}
public String getDispatchTime() {
return dispatchTime;
}
public String getSurveyReserveTime() {
return surveyReserveTime;
}
public String getSurveyStartTime() {
return surveyStartTime;
}
public String getInstallReserveTime() {
return installReserveTime;
}
public String getInstallStartTime() {
return installStartTime;
}
public String getReturnVisitTime() {
return returnVisitTime;
}
public void setDispatchTime(String dispatchTime) {
this.dispatchTime = dispatchTime;
}
public void setSurveyReserveTime(String surveyReserveTime) {
this.surveyReserveTime = surveyReserveTime;
}
public void setSurveyStartTime(String surveyStartTime) {
this.surveyStartTime = surveyStartTime;
}
public void setInstallReserveTime(String installReserveTime) {
this.installReserveTime = installReserveTime;
}
public void setInstallStartTime(String installStartTime) {
this.installStartTime = installStartTime;
}
public void setReturnVisitTime(String returnVisitTime) {
this.returnVisitTime = returnVisitTime;
}
}
package com.starcharge.wios.app.dto;
import java.util.List;
import io.swagger.annotations.ApiModelProperty;
public class AppOrderDetailDTO {
@ApiModelProperty(value = "用户姓名")
private String userName;
@ApiModelProperty(value = "地址")
private String address;// 地址
@ApiModelProperty(value = "工单号")
private String orderId;// 工单号
@ApiModelProperty(value = "订单状态")
private String statusText;// 订单状态
@ApiModelProperty(value = "账单编号")
private String billId;
@ApiModelProperty(value = "账单状态0-未支付 1-已支付")
private Integer billStatus;
@ApiModelProperty(value = "操作日志列表")
private List<AppOperateLogDTO> operateLogList;// 操作日志列表
public String getAddress() {
return address;
}
public String getOrderId() {
return orderId;
}
public String getStatusText() {
return statusText;
}
public void setAddress(String address) {
this.address = address;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public void setStatusText(String statusText) {
this.statusText = statusText;
}
public List<AppOperateLogDTO> getOperateLogList() {
return operateLogList;
}
public void setOperateLogList(List<AppOperateLogDTO> operateLogList) {
this.operateLogList = operateLogList;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getBillId() {
return billId;
}
public Integer getBillStatus() {
return billStatus;
}
public void setBillId(String billId) {
this.billId = billId;
}
public void setBillStatus(Integer billStatus) {
this.billStatus = billStatus;
}
}
package com.starcharge.wios.app.dto;
import java.math.BigDecimal;
import java.util.List;
import io.swagger.annotations.ApiModelProperty;
public class AppOrderInstallDTO {
// @ApiModelProperty(value = "外部订单号")
// private String outOrderId;// 外部订单号
@ApiModelProperty(value = "地址")
private String address;// 地址
@ApiModelProperty(value = "工单号")
private String orderId;// 工单号
@ApiModelProperty(value = "安装完成时间")
private String installFinishTime;// 安装完成时间
@ApiModelProperty(value = "增项费用明细")
private List<AdditionFeeItem> additionFeeList;// 费用明细
@ApiModelProperty(value = "增项总费用")
private BigDecimal additionTotalFee = BigDecimal.ZERO;// 增项总费用
@ApiModelProperty(value = "报装费用")
private BigDecimal expandFee = BigDecimal.ZERO;// 报装费用
@ApiModelProperty(value = "总费用")
private BigDecimal totalFee;// 总费用
@ApiModelProperty(value = "账单id")
private String billId;
@ApiModelProperty(value = "账单状态 0-未支付 1-已支付")
private Integer billStatus;
@ApiModelProperty(value = "账单支付时间")
private String billPayTime;
@ApiModelProperty(value = "用户手机号")
private String billUserPhone;
@ApiModelProperty(value = "账单支付方式 0-未知 3-微信")
private Integer billPayMethod;
@ApiModelProperty(value = "工单状态")
private Integer orderStatus;
@ApiModelProperty(value = "工单状态说明")
private String orderStatusText;
@ApiModelProperty(value = "评价详情")
private OrderScore orderScore;
public class AdditionFeeItem {
@ApiModelProperty(value = "项目名称")
private String name;// 项目名称
@ApiModelProperty(value = "数量")
private Integer quantity;// 数量
@ApiModelProperty(value = "费用")
private BigDecimal fee;// 费用
public String getName() {
return name;
}
public Integer getQuantity() {
return quantity;
}
public BigDecimal getFee() {
return fee;
}
public void setName(String name) {
this.name = name;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
}
public class OrderScore {
@ApiModelProperty(value = "综合分数")
private Double score;
@ApiModelProperty(value = "评价内容")
private String content;
@ApiModelProperty(value = "评价图片,多个逗号分割")
private String files;
@ApiModelProperty(value = "评价时间")
private String time;
public Double getScore() {
return score;
}
public String getContent() {
return content;
}
public String getFiles() {
return files;
}
public String getTime() {
return time;
}
public void setScore(Double score) {
this.score = score;
}
public void setContent(String content) {
this.content = content;
}
public void setFiles(String files) {
this.files = files;
}
public void setTime(String time) {
this.time = time;
}
}
public String getAddress() {
return address;
}
public String getOrderId() {
return orderId;
}
public BigDecimal getTotalFee() {
return totalFee;
}
public void setAddress(String address) {
this.address = address;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public void setTotalFee(BigDecimal totalFee) {
this.totalFee = totalFee;
}
public BigDecimal getExpandFee() {
return expandFee;
}
public void setExpandFee(BigDecimal expandFee) {
this.expandFee = expandFee;
}
public BigDecimal getAdditionTotalFee() {
return additionTotalFee;
}
public void setAdditionTotalFee(BigDecimal additionTotalFee) {
this.additionTotalFee = additionTotalFee;
}
public List<AdditionFeeItem> getAdditionFeeList() {
return additionFeeList;
}
public void setAdditionFeeList(List<AdditionFeeItem> additionFeeList) {
this.additionFeeList = additionFeeList;
}
public String getBillId() {
return billId;
}
public Integer getBillStatus() {
return billStatus;
}
public void setBillId(String billId) {
this.billId = billId;
}
public void setBillStatus(Integer billStatus) {
this.billStatus = billStatus;
}
public String getBillPayTime() {
return billPayTime;
}
public Integer getBillPayMethod() {
return billPayMethod;
}
public Integer getOrderStatus() {
return orderStatus;
}
public String getOrderStatusText() {
return orderStatusText;
}
public void setBillPayTime(String billPayTime) {
this.billPayTime = billPayTime;
}
public void setBillPayMethod(Integer billPayMethod) {
this.billPayMethod = billPayMethod;
}
public void setOrderStatus(Integer orderStatus) {
this.orderStatus = orderStatus;
}
public void setOrderStatusText(String orderStatusText) {
this.orderStatusText = orderStatusText;
}
public OrderScore getOrderScore() {
return orderScore;
}
public void setOrderScore(OrderScore orderScore) {
this.orderScore = orderScore;
}
public String getInstallFinishTime() {
return installFinishTime;
}
public void setInstallFinishTime(String installFinishTime) {
this.installFinishTime = installFinishTime;
}
public String getBillUserPhone() {
return billUserPhone;
}
public void setBillUserPhone(String billUserPhone) {
this.billUserPhone = billUserPhone;
}
}
package com.starcharge.wios.app.dto;
import java.math.BigDecimal;
import io.swagger.annotations.ApiModelProperty;
public class AppPayBillDTO {
@ApiModelProperty(value = "支付时间")
private String payTime;
@ApiModelProperty(value = "账单编号")
private String billId;
@ApiModelProperty(value = "账单金额")
private BigDecimal amount;
@ApiModelProperty(value = "安装订单状态")
private Integer orderStatus;
@ApiModelProperty(value = "安装订单状态文字")
private String orderStatusText;
@ApiModelProperty(value = "工单编号")
private String orderId;
@ApiModelProperty(value = "工单安装完成时间")
private String installFinishTime;
@ApiModelProperty(value = "支付状态 0-未支付 1-已支付")
private Integer payStatus;
public String getPayTime() {
return payTime;
}
public String getBillId() {
return billId;
}
public BigDecimal getAmount() {
return amount;
}
public Integer getOrderStatus() {
return orderStatus;
}
public String getOrderStatusText() {
return orderStatusText;
}
public void setPayTime(String payTime) {
this.payTime = payTime;
}
public void setBillId(String billId) {
this.billId = billId;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public void setOrderStatus(Integer orderStatus) {
this.orderStatus = orderStatus;
}
public void setOrderStatusText(String orderStatusText) {
this.orderStatusText = orderStatusText;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getInstallFinishTime() {
return installFinishTime;
}
public void setInstallFinishTime(String installFinishTime) {
this.installFinishTime = installFinishTime;
}
public Integer getPayStatus() {
return payStatus;
}
public void setPayStatus(Integer payStatus) {
this.payStatus = payStatus;
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论