Commit 189a0148 by wangzy

初始化

0 parents
Showing 354 changed files with 4842 additions and 0 deletions
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>micro-base</artifactId>
<groupId>com.polysoft.framework.micro</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>micro-gateway-zuul</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin-stream</artifactId>
</dependency>-->
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
<!--JJWT库-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.4.0</version>
<scope>compile</scope>
</dependency>
<!-- 引入 redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file \ No newline at end of file
package com.polysoft.micro.zuul;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@EnableZuulProxy
@EnableCircuitBreaker
@EnableDiscoveryClient
//@EnableApolloConfig
public class ZuulBootstrap {
public static void main(String[] args) {
SpringApplication.run(ZuulBootstrap.class, args);
}
@Bean
@RefreshScope
@ConfigurationProperties("zuul")
public ZuulProperties zuulProperties() {
return new ZuulProperties();
}
}
\ No newline at end of file \ No newline at end of file
package com.polysoft.micro.zuul.interceptor;
import com.alibaba.fastjson.JSON;
import com.polysoft.micro.zuul.utils.BaseAction;
import com.polysoft.micro.zuul.utils.RedisDealUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* token校验过滤器
* @author wzy
* @Date 2019\7\24
*/
@Component
@WebFilter(urlPatterns="/**",filterName="tokenFilter")
public class LoginFilter extends BaseAction implements Filter {
private Logger log = Logger.getLogger(LoginFilter.class);
@Autowired
private RedisTemplate redisTemplate;
//排除不拦截的url
private static List<String> urlList = Arrays.asList("4ALogin","login",".js",".css",".ico",".jpg",".png",".json",
".html","demo","imgToData2","export",
"soaReceiveInterface","soaAggregateReceiveInterface","pushPropertyData","downloadFile2","downloadFile","dealInwardItem","pushPropertyDataOne",
"submit","caixianSubmit","caixianSubmit2","redisTest","syncInwardtreatyinfo","getFileInfo");
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("---------------------开始进入请求地址拦截----------------------------");
HttpServletRequest httpServletRequest = (HttpServletRequest)request;
HttpServletResponse httpServletResponse = (HttpServletResponse)response;
//获取请求地址
String requestURI = httpServletRequest.getRequestURI();
// ServletRequest requestWrapper = null;
// if(request instanceof HttpServletRequest) {
// requestWrapper = new RequestWrapper((HttpServletRequest) request);
// }
//如果不需要拦截的,则直接放行
if(!StringUtils.isEmpty(requestURI) && isPast(requestURI)){
log.info("=======================放行,当前url为:" + requestURI);
// if(requestWrapper == null) {
//
// } else {
// chain.doFilter(requestWrapper, response);
// }
// RedisDealUtil.setObject("111","哈哈");
// System.out.println(RedisDealUtil.getObject("111"));
chain.doFilter(request, response);
}else{//如果需要拦截的,则进行验证
//获取请求头中的token
String token = httpServletRequest.getHeader("token");
//判断token是否为空,
//如果为空,认为登录校验失败,进行拦截
if(StringUtils.isEmpty(token)){
log.info("token为空,当前url为:" + requestURI);
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsFailCode(2,"token为空")).toString());
}else{
log.info("token的值为:" + token);
System.out.println("获取token中的值为:"+ RedisDealUtil.getObject(token));
try {
if(null == RedisDealUtil.getObject(token)){
log.info("token不存在或者已失效");
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsFailCode(2,"token不存在或者已失效")).toString());
}else{
log.info("token校验成功");
//再次更新token的过期时间
RedisDealUtil.setObject(token,RedisDealUtil.getObject(token),60 * 60 * 1);//两个小时过期
chain.doFilter(request, response);
return;
}
}catch(Exception e) {
log.error("token校验失败,当前url为:" + requestURI);
e.printStackTrace();
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsFailCode(2,"token校验失败")).toString());
}
}
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
//
@Override
public void destroy(){}
/**
* 获取POST请求中Body参数
* @param request
* @return 字符串
*/
public String getParm(ServletRequest request) {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) {
e.printStackTrace();
}
return jb.toString();
}
/**
* 是否不需要过滤
*
* @param requestUrl
* 请求的url
* @return
*/
public boolean isPast(String requestUrl) {
boolean flag = false;
for (String url : urlList) {
if (requestUrl.indexOf(url) != -1) {
flag = true;
break;
}
}
return flag;
}
/**
* 统一返回信息结构
* @param httpServletResponse
* @return
*/
public HttpServletResponse httpServletResponse(HttpServletResponse httpServletResponse,String msg){
try{
httpServletResponse.setHeader("tokenstatus", "timeout");//在响应头设置token状态
// httpServletResponse.setCharacterEncoding("text/html;charset=utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
httpServletResponse.getWriter().print(msg);
}catch (Exception e){
e.printStackTrace();
}
return httpServletResponse;
}
}
package com.polysoft.micro.zuul.interceptor;
import com.alibaba.fastjson.JSON;
import com.polysoft.micro.zuul.utils.BaseAction;
import com.polysoft.micro.zuul.utils.JwtUtils;
import com.polysoft.micro.zuul.utils.RsaUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.List;
/**
* token校验过滤器
* @author wzy
* @Date 2019\7\24
*/
//@Component
//@WebFilter(urlPatterns="/**",filterName="tokenFilter")
public class LoginFilterCopy extends BaseAction implements Filter {
private Logger log = Logger.getLogger(LoginFilterCopy.class);
@Value("${keyPublicPath}")
private String keyPublicPath;
@Value("${keyPrivatePath}")
private String keyPrivatePath;
private PublicKey publicKey;
private PrivateKey privateKey;
//排除不拦截的url
private static List<String> urlList = Arrays.asList("login",".js",".css",".ico",".jpg",".png",".json",".html","demo","imgToData2","export",
"soaReceiveInterface","soaAggregateReceiveInterface","pushPropertyData","downloadFile2","downloadFile","dealInwardItem","pushPropertyDataOne",
"submit","caixianSubmit","caixianSubmit2");
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("---------------------开始进入请求地址拦截----------------------------");
HttpServletRequest httpServletRequest = (HttpServletRequest)request;
HttpServletResponse httpServletResponse = (HttpServletResponse)response;
//获取请求地址
String requestURI = httpServletRequest.getRequestURI();
// ServletRequest requestWrapper = null;
// if(request instanceof HttpServletRequest) {
// requestWrapper = new RequestWrapper((HttpServletRequest) request);
// }
//如果不需要拦截的,则直接放行
if(!StringUtils.isEmpty(requestURI) && isPast(requestURI)){
log.info("=======================放行");
// if(requestWrapper == null) {
//
// } else {
// chain.doFilter(requestWrapper, response);
// }
chain.doFilter(request, response);
}else{//如果需要拦截的,则进行验证
//获取请求头中的token
String token = httpServletRequest.getHeader("token");
//判断token是否为空,
//如果为空,认为登录校验失败,进行拦截
if(StringUtils.isEmpty(token)){
log.info("token为空,当前url为:" + requestURI);
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsFailCode(2,"token为空")).toString());
}else{
log.info("token的值为:" + token);
try {
publicKey = RsaUtils.getPublicKey(keyPublicPath);//获取公钥
String userInfo = JwtUtils.getInfoFromToken(token, publicKey);//获取用户信息
//校验用户信息,判断用户是否存在
if(StringUtils.isEmpty(userInfo)){
log.info("用户信息为空");
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsFailCode(2,"用户信息为空")).toString());
}else {
log.info("用户信息的值: " + userInfo);
//校验用户的具体信息
//TODO
// httpServletResponse(httpServletResponse,JSON.toJSON(toResponsSuccess("token校验成功")).toString());
// chain.doFilter(requestWrapper, response);
chain.doFilter(request, response);
return;
}
}catch(io.jsonwebtoken.MalformedJwtException e) {
log.error("通过token,获取用户信息异常",e);
System.out.println("通过token,获取用户信息异常,当前url为:" + requestURI);
e.printStackTrace();
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsFailCode(2,"通过token,获取用户信息异常")).toString());
}catch(io.jsonwebtoken.ExpiredJwtException e) {
log.error("token失效",e);
e.printStackTrace();
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsFailCode(2,"token失效")).toString());
}catch(Exception e) {
log.error("token校验失败,当前url为:" + requestURI);
e.printStackTrace();
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsFailCode(2,"token校验失败")).toString());
}
}
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
//
@Override
public void destroy(){}
/**
* 获取POST请求中Body参数
* @param request
* @return 字符串
*/
public String getParm(ServletRequest request) {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) {
e.printStackTrace();
}
return jb.toString();
}
/**
* 是否不需要过滤
*
* @param requestUrl
* 请求的url
* @return
*/
public boolean isPast(String requestUrl) {
boolean flag = false;
for (String url : urlList) {
if (requestUrl.indexOf(url) != -1) {
flag = true;
break;
}
}
return flag;
}
/**
* 统一返回信息结构
* @param httpServletResponse
* @return
*/
public HttpServletResponse httpServletResponse(HttpServletResponse httpServletResponse,String msg){
try{
httpServletResponse.setHeader("tokenstatus", "timeout");//在响应头设置token状态
// httpServletResponse.setCharacterEncoding("text/html;charset=utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
httpServletResponse.getWriter().print(msg);
}catch (Exception e){
e.printStackTrace();
}
return httpServletResponse;
}
}
package com.polysoft.micro.zuul.interceptor;
import com.alibaba.fastjson.JSON;
import com.polysoft.micro.zuul.utils.BaseAction;
import com.polysoft.micro.zuul.utils.JwtUtils;
import com.polysoft.micro.zuul.utils.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* 登录拦截器
* @author wzy
* @Date 2019\7\24
*/
@Slf4j
public class LoginInterceptor extends BaseAction implements HandlerInterceptor {
private String keyPublicPath = "D:/cjp/key.pub";
private String keyPrivatePath = "D:/cjp/key.pri";
private PublicKey publicKey;
private PrivateKey privateKey;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("---------------------开始进入请求地址拦截----------------------------");
//获取请求地址
String requestURI = httpServletRequest.getRequestURI();
//获取请求头中的token
String token = httpServletRequest.getHeader("token");
//判断token是否为空,
//如果为空,认为登录校验失败,进行拦截
if(StringUtils.isEmpty(token)){
log.info("token为空,当前url为:" + requestURI);
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsSuccess("token为空")).toString());
}else{
log.info("token的值为:" + token);
try {
publicKey = RsaUtils.getPublicKey(this.keyPublicPath);//获取公钥
String userInfo = JwtUtils.getInfoFromToken(token, publicKey);//获取用户信息
//校验用户信息,判断用户是否存在
if(StringUtils.isEmpty(userInfo)){
log.info("用户信息为空");
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsSuccess("用户信息为空")).toString());
}else {
log.info("用户信息的值: " + userInfo);
//校验用户的具体信息
//TODO
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsSuccess("token校验成功")).toString());
}
}catch(io.jsonwebtoken.MalformedJwtException e) {
log.error("通过token,获取用户信息异常",e);
System.out.println("通过token,获取用户信息异常,当前url为:" + requestURI);
e.printStackTrace();
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsSuccess("通过token,获取用户信息异常")).toString());
return false;
}catch(io.jsonwebtoken.ExpiredJwtException e) {
log.error("token失效",e);
e.printStackTrace();
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsSuccess("token失效")).toString());
return false;
}catch(Exception e) {
log.error("token校验失败,当前url为:" + requestURI);
e.printStackTrace();
httpServletResponse(httpServletResponse,JSON.toJSON(toResponsSuccess("token校验失败")).toString());
return false;
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("--------------处理请求完成后视图渲染之前的处理操作---------------");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("---------------视图渲染之后的操作-------------------------");
}
/**
* 统一返回信息结构
* @param httpServletResponse
* @return
*/
public HttpServletResponse httpServletResponse(HttpServletResponse httpServletResponse,String msg){
try{
httpServletResponse.setHeader("tokenstatus", "timeout");//在响应头设置token状态
// httpServletResponse.setCharacterEncoding("text/html;charset=utf-8");
httpServletResponse.setContentType("text/html;charset=utf-8");
httpServletResponse.getWriter().print(msg);
}catch (Exception e){
e.printStackTrace();
}
return httpServletResponse;
}
}
package com.polysoft.micro.zuul.interceptor;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
/**
* @author wzy
* @Date 2019\7\24
*/
public class RequestWrapper extends HttpServletRequestWrapper {
private final String body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {}
@Override
public int read() {
return byteArrayInputStream.read();
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
}
package com.polysoft.micro.zuul.interceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author wzy
* @Date 2019\7\23
*/
@RestController
@RequestMapping(value={"/test/"})
public class TestController {
//@Value("${keyPublicPath}")
//private String keyPublicPath;
/**
*
* @return
*/
@RequestMapping("test")
public String test(){
return "2222222222222";
}
/**
*
* @return
*/
@RequestMapping("login")
public String login(){
//System.out.println(keyPublicPath);
return "登录成功";
}
}
package com.polysoft.micro.zuul.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.*;
import java.util.List;
/**
* 拦截器管理
* @author wzy
* @Date 2019\7\23
*/
//@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry){
//注册自定义拦截器,添加拦截路径和排除拦截路径
// registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/login/**");//拦截除登录以外的其他接口
// registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/test/login");
}
@Override
public void configurePathMatch(PathMatchConfigurer pathMatchConfigurer) {
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer) {
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer asyncSupportConfigurer) {
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer defaultServletHandlerConfigurer) {
}
@Override
public void addFormatters(FormatterRegistry formatterRegistry) {
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {
}
@Override
public void addCorsMappings(CorsRegistry corsRegistry) {
}
@Override
public void addViewControllers(ViewControllerRegistry viewControllerRegistry) {
}
@Override
public void configureViewResolvers(ViewResolverRegistry viewResolverRegistry) {
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {
}
@Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> list) {
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> list) {
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> list) {
}
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {
}
@Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {
}
@Override
public Validator getValidator() {
return null;
}
@Override
public MessageCodesResolver getMessageCodesResolver() {
return null;
}
}
package com.polysoft.micro.zuul.utils;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
/**
* 基础控制类
*/
@Slf4j
public class BaseAction {
/**
* 成功返回,带数据
* @param data
* @return
*/
public Map<String, Object> toResponsSuccess(Object data) {
Map<String, Object> rp = toResponsObject(0, "执行成功", data);
log.info("response:" + rp);
return rp;
}
/**
* 成功返回,自定义信息
* @param msg
* @return
*/
public Map<String, Object> toResponsMsgSuccess(String msg) {
return toResponsObject(0, msg, "");
}
/**
* 失败返回,自定义信息
* @param msg
* @return
*/
public Map<String, Object> toResponsFail(String msg) {
return toResponsObject(1, msg, null);
}
/**
* 失败返回,自定义信息,自定义状态
* @param msg
* @return
*/
public Map<String, Object> toResponsFailCode(int requestCode, String msg) {
Map<String, Object> obj = new HashMap<String, Object>();
obj.put("errno", requestCode);
obj.put("errmsg", msg);
return obj;
}
public Map<String, Object> toResponsObject(int requestCode, String msg, Object data) {
Map<String, Object> obj = new HashMap<String, Object>();
obj.put("errno", requestCode);
obj.put("errmsg", msg);
if (data != null)
obj.put("data", data);
return obj;
}
}
package com.polysoft.micro.zuul.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
public class JwtUtils {
/**
* 私钥加密token
*
* @param userMap 载荷中的数据
* @param privateKey 私钥
* @param expireMinutes 过期时间,单位是分钟
* @return
* @throws Exception
*/
public static String generateToken(Map<String,Object> userMap, PrivateKey privateKey, int expireMinutes) throws Exception {
return Jwts.builder()
.claim("userInfo", userMap)
.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
.signWith(SignatureAlgorithm.RS256, privateKey)
.compact();
}
/**
* 私钥加密token
*
* @param userMap 载荷中的数据
* @param privateKey 私钥字节数组
* @param expireMinutes 过期时间,单位秒
* @return
* @throws Exception
*/
public static String generateToken(Map<String,Object> userMap, byte[] privateKey, int expireMinutes) throws Exception {
return Jwts.builder()
.claim("userInfo", userMap)
.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
.signWith(SignatureAlgorithm.RS256, RsaUtils.getPrivateKey(privateKey))
.compact();
}
/**
* 公钥解析token
*
* @param token 用户请求中的token
* @param publicKey 公钥
* @return
* @throws Exception
*/
private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
}
/**
* 公钥解析token
*
* @param token 用户请求中的token
* @param publicKey 公钥字节数组
* @return
* @throws Exception
*/
private static Jws<Claims> parserToken(String token, byte[] publicKey) throws Exception {
return Jwts.parser().setSigningKey(RsaUtils.getPublicKey(publicKey))
.parseClaimsJws(token);
}
/**
* 获取token中的用户信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
* @throws Exception
*/
public static String getInfoFromToken(String token, PublicKey publicKey) throws Exception {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
return body+"";
}
/**
* 获取token中的用户信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
* @throws Exception
*/
public static String getInfoFromToken(String token, byte[] publicKey) throws Exception {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
return body+"";
}
public static void main(String[] args) {
Integer userId = 123;
String userName = "张三";
PrivateKey privateKey = null;
PublicKey publicKey = null;
String infoFromToken = null;
Map<String,Object> userMap = new HashMap<String,Object>();
userMap.put("userId",userId);
userMap.put("userName",userName);
try {
privateKey = RsaUtils.getPrivateKey("D:/cjp/key.pri");
publicKey = publicKey = RsaUtils.getPublicKey("D:/cjp/key.pub");
} catch (Exception e) {
e.printStackTrace();
}
int expireMinutes = 5;//过期时间,1分钟
String token = "";
try{
token = generateToken(userMap,privateKey,expireMinutes);
infoFromToken = getInfoFromToken(token, publicKey);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("获取token " + token);
System.out.println("获取用户信息 " + infoFromToken);
}
}
package com.polysoft.micro.zuul.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import javax.annotation.PostConstruct;
@Component
public class RedisDealUtil {
private static Logger logger = LoggerFactory.getLogger(RedisDealUtil.class);
@Value("${spring.redis.host}")
private String ADDR2;
@Value("${spring.redis.port}")
private int PORT2;
@Value("${spring.redis.password}")
private String AUTH2;
//Redis服务器IP
private static String ADDR = "";
//Redis的端口号
private static int PORT = 6379;
//访问密码
private static String AUTH = "";
//可用连接实例的最大数目,默认值为8;
//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_ACTIVE = 1024;
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 200;
//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int MAX_WAIT = 10000;
private static int TIMEOUT = 10000;
//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
/**
* 初始化Redis连接池
*/
// static {
// try {
// JedisPoolConfig config = new JedisPoolConfig();
// config.setMaxTotal(MAX_ACTIVE);
// config.setMaxIdle(MAX_IDLE);
// config.setMaxWaitMillis(MAX_WAIT);
// config.setTestOnBorrow(TEST_ON_BORROW);
// jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/**
* 初始化Redis连接池
*/
@PostConstruct
public void init() {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR2, PORT2, TIMEOUT, AUTH2);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取Jedis实例
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 释放jedis资源
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
/**
* 获取redis键值-object
*
* @param key
* @return
*/
public static Object getObject(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
byte[] bytes = jedis.get(key.getBytes());
if(!StringUtils.isEmpty(bytes)) {
return SerializeUtil.deserialize(bytes);
}
} catch (Exception e) {
logger.error("getObject获取redis键值异常:key=" + key + " cause:" + e.getMessage());
} finally {
jedis.close();
}
return null;
}
/**
* 设置redis键值-object
* @param key
* @param value
* @return
*/
public static String setObject(String key, Object value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.set(key.getBytes(), SerializeUtil.serialize(value));
} catch (Exception e) {
logger.error("setObject设置redis键值异常:key=" + key + " value=" + value + " cause:" + e.getMessage());
return null;
} finally {
if(jedis != null)
{
jedis.close();
}
}
}
public static String setObject(String key, Object value,int expiretime) {
String result = "";
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
result = jedis.set(key.getBytes(), SerializeUtil.serialize(value));
if(result.equals("OK")) {
jedis.expire(key.getBytes(), expiretime);
}
return result;
} catch (Exception e) {
logger.error("setObject设置redis键值异常:key=" + key + " value=" + value + " cause:" + e.getMessage());
} finally {
if(jedis != null)
{
jedis.close();
}
}
return result;
}
/**
* 删除key
*/
public static Long delkeyObject(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.del(key.getBytes());
}catch(Exception e) {
e.printStackTrace();
return null;
}finally{
if(jedis != null)
{
jedis.close();
}
}
}
public static Boolean existsObject(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.exists(key.getBytes());
}catch(Exception e) {
e.printStackTrace();
return null;
}finally{
if(jedis != null)
{
jedis.close();
}
}
}
}
package com.polysoft.micro.zuul.utils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/***
* 此类是利用RSA算法生成公私秘钥。(底层是欧拉函数)
* 在非对称加密中利用私有秘钥进行加密,传输到另一端之后可以使用公有秘钥解密。反之亦然
* 举例如在: jwt中使用的密钥就可以是该算法生成的公私秘钥
* (因为该算法的特殊性,所以加密时使用公钥,解密时用私钥仍可以加解密无误。不用使用同一把钥匙,提高了安全性(非对称加密,消耗性能、降低效率、延缓时间))
* @author wzy
* @Date 2019\7\23 002313:50
* */
public class RsaUtils {
/**
* 从文件中读取公钥
*
* @param filename 公钥保存路径,相对于classpath
* @return 公钥对象
* @throws Exception
*/
public static PublicKey getPublicKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPublicKey(bytes);
}
/**
* 从文件中读取密钥
*
* @param filename 私钥保存路径,相对于classpath
* @return 私钥对象
* @throws Exception
*/
public static PrivateKey getPrivateKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPrivateKey(bytes);
}
/**
* 获取公钥
*
* @param bytes 公钥的字节形式
* @return 公钥对象
* @throws Exception
*/
public static PublicKey getPublicKey(byte[] bytes) throws Exception {
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(spec);
}
/**
* 获取密钥
*
* @param bytes 私钥的字节形式
* @return 私钥对象
* @throws Exception
*/
public static PrivateKey getPrivateKey(byte[] bytes) throws Exception {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(spec);
}
/**
* 根据密文,生存rsa公钥和私钥,并写入指定文件
*
* @param publicKeyFilename 公钥文件路径
* @param privateKeyFilename 私钥文件路径
* @param secret 生成密钥的明文
* @throws Exception
*/
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// 获取公钥并写出
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
writeFile(publicKeyFilename, publicKeyBytes);
// 获取私钥并写出
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
writeFile(privateKeyFilename, privateKeyBytes);
}
private static byte[] readFile(String fileName) throws Exception {
return Files.readAllBytes(new File(fileName).toPath());
}
private static void writeFile(String destPath, byte[] bytes) throws IOException {
File dest = new File(destPath);
if (!dest.exists()) {
dest.createNewFile();
}
Files.write(dest.toPath(), bytes);
}
/**
* 测试使用
* @param args
*/
public static void main(String[] args) throws Exception {
// 调用generateKey方法,输入公私钥的地址,生成秘钥的明文(原料)。即可在指定的地方生成秘钥
RsaUtils.generateKey("D:/cjp/key.pub","D:/cjp/key.pri","程熙");
// 这是输入地址获取公有秘钥的,还有一个是输入字节对象获取的。下面获取私有秘钥同理
PublicKey publicKey = RsaUtils.getPublicKey("D:/cjp/key.pub");
System.out.println("这是公有的秘钥:"+publicKey);
PrivateKey privateKey = RsaUtils.getPrivateKey("D:/cjp/key.pri");
System.out.println("这是私有的秘钥:"+privateKey);
}
}
package com.polysoft.micro.zuul.utils;
import java.io.*;
public class SerializeUtil {
public static byte[] serialize(Object value) {
if (value == null) {
throw new NullPointerException("Can‘t serialize null");
}
byte[] rv = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
os.writeObject(value);
os.close();
bos.close();
rv = bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(os);
close(bos);
}
return rv;
}
public static Object deserialize(byte[] in) {
return deserialize(in, Object.class);
}
@SuppressWarnings("unchecked")
public static <T> T deserialize(byte[] in, Class<T> requiredType) {
Object rv = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
rv = is.readObject();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(is);
close(bis);
}
return (T) rv;
}
private static void close(Closeable closeable) {
if (closeable != null)
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#\u7AEF\u53E3
server.port=20000
# \u6CE8\u518C\u4E2D\u5FC3\u914D\u7F6E
#\u5F00\u53D1
eureka.client.service-url.defaultZone=http://localhost:21000/eureka/
#\u83B7\u53D6\u4E3B\u673Aip\u4F5C\u4E3A\u5730\u5740\u6CE8\u518C\u5230\u6CE8\u518C\u4E2D\u5FC3
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ipAddress}:${server.port}
info.version=@project.version@
# \u83B7\u53D6\u6CE8\u518C\u4FE1\u606F\u95F4\u9694\u65F6\u95F4 default 30
eureka.client.registry-fetch-interval-seconds=30
# \u66F4\u65B0\u5B9E\u4F8B\u53D8\u5316\u5230\u670D\u52A1\u7AEF default 30
eureka.client.instance-info-replication-interval-seconds=30
# \u52A8\u6001\u5237\u65B0eureka\u7684serviceURl\u5730\u5740\u7684\u95F4\u9694\u65F6\u95F4 \u4E0EConfig\u96C6\u6210\u9700\u8981 default 300
eureka.client.eureka-service-url-poll-interval-seconds=300
#\u5F00\u542F\u5065\u5EB7\u68C0\u67E5\uFF08\u9700\u8981spring-boot-starter-actuator\u4F9D\u8D56\uFF09
eureka.client.healthcheck.enabled = true
#\u79DF\u671F\u66F4\u65B0\u65F6\u95F4\u95F4\u9694\uFF08\u9ED8\u8BA430\u79D2\uFF09
eureka.instance.lease-renewal-interval-in-seconds =30
#\u79DF\u671F\u5230\u671F\u65F6\u95F4\uFF08\u9ED8\u8BA490\u79D2\uFF09
eureka.instance.lease-expiration-duration-in-seconds =90
#================= \u4E0B\u9762\u914D\u7F6E\u53EF\u4EE5\u901A\u8FC7\u914D\u7F6E\u4E2D\u5FC3\u7684\u5916\u90E8\u914D\u7F6E\u8986\u76D6
## * \u6240\u6709\u7684\u670D\u52A1\u90FD\u4E0D\u81EA\u52A8\u521B\u5EFA\u6620\u5C04
zuul.ignored-services=*
# \u8D1F\u8F7D\u5747\u8861\u914D\u7F6E Eureka\u7BA1\u7406
ribbon.eureka.enabled=true
# \u5F00\u542F\u91CD\u8BD5\u673A\u667A
spring.cloud.loadbalancer.retry.enabled=true
#\u7EBF\u7A0B\u9694\u79BB
#hystrix.command.default.execution.isolation.strategy=THREAD
# \u65AD\u8DEF\u5668\u8D85\u65F6\u65F6\u95F4
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=600000
#\u8BBE\u7F6E\u6307\u5B9AURl\u8D85\u65F6\u65F6\u95F4
zuul.host.connect-timeout-millis: 600000
zuul.host.socket-timeout-millis: 600000
#\u8FDE\u63A5\u5EFA\u7ACB\u7684\u65F6\u95F4
ribbon.ConnectTimeout=600000
# \u8F6C\u53D1\u8BF7\u6C42\u7684\u65F6\u95F4
ribbon.ReadTimeout=600000
# \u6240\u6709\u64CD\u4F5C\u91CD\u8BD5
ribbon.OkToRetryOnAllOperations=true
# \u5207\u6362\u5B9E\u4F8B\u91CD\u8BD5\u6B21\u6570
ribbon.MaxAuto=2
# \u5F53\u524D\u5B9E\u4F8B\u91CD\u8BD5\u6B21\u6570
ribbon.MaxAutoRetries=0
spring.zipkin.enabled=true
#spring.zipkin.base-url=http://localhost:22000
spring.sleuth.enabled=true
#\u91C7\u6837\u7387\u9ED8\u8BA4\u4E3A0.1
spring.sleuth.sampler.percentage=0.1
zuul.retryable=true
# ======================= \u516C\u5171\u6CE8\u518C \u672C\u5730DEBUG \u914D\u7F6E
#
zuul.routes.user.path=/user/**
zuul.routes.user.serviceId=service-user
zuul.routes.template.path=/template/**
zuul.routes.template.serviceId=service-template
zuul.routes.api.path=/api/**
zuul.routes.api.serviceId=service-api
# \u4E0D\u53D6\u6D88\u524D\u7F00 \u5373\u539FURL\u8F6C\u53D1\u5230\u76EE\u6807\u670D\u52A1
zuul.routes.user.stripPrefix=false
zuul.routes.template.stripPrefix=false
keyPublicPath=D:/cjp/key.pub
keyPrivatePath=D:/cjp/key.pri
#redis\u914D\u7F6E
#redis\u914D\u7F6E
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=123456
\ No newline at end of file \ No newline at end of file
server.port=20000
eureka.client.service-url.defaultZone=http://10.129.202.76:21000/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ipAddress}:${server.port}
info.version=@project.version@
eureka.client.registry-fetch-interval-seconds=30
eureka.client.instance-info-replication-interval-seconds=30
eureka.client.eureka-service-url-poll-interval-seconds=300
eureka.client.healthcheck.enabled = true
eureka.instance.lease-renewal-interval-in-seconds =30
eureka.instance.lease-expiration-duration-in-seconds =90
zuul.ignored-services=*
ribbon.eureka.enabled=true
spring.cloud.loadbalancer.retry.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=600000
zuul.host.connect-timeout-millis: 600000
zuul.host.socket-timeout-millis: 600000
ribbon.ConnectTimeout=600000
ribbon.ReadTimeout=600000
ribbon.OkToRetryOnAllOperations=true
ribbon.MaxAuto=2
ribbon.MaxAutoRetries=0
spring.zipkin.enabled=true
spring.sleuth.enabled=true
spring.sleuth.sampler.percentage=0.1
zuul.retryable=true
zuul.routes.template.path=/template/**
zuul.routes.template.serviceId=service-template
zuul.routes.user.stripPrefix=false
zuul.routes.template.stripPrefix=false
zuul.routes.demo.stripPrefix=false
keyPublicPath=/opt/picc/jwt/cjp/key.pub
keyPrivatePath=/opt/picc/jwt/cjp/key.pri
app.id=service-zuul
#redis\u914D\u7F6E
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=123456
spring.redis.timeout=2000
spring.cloud.config.enabled=false
spring.cloud.config.fail-fast=false
spring.application.name=service-zuul
spring.profiles.active=dev
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>micro-base</artifactId>
<groupId>com.polysoft.framework.micro</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>micro-registry-eureka</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-cloud-starter-archaius</artifactId>
<groupId>org.springframework.cloud</groupId>
</exclusion>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.polysoft.micro.registry.eureka.EurekaBootstrap</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package com.polysoft.micro.registry.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaBootstrap {
public static void main(String[] args) {
SpringApplication.run(EurekaBootstrap.class, args);
}
}
server.port=21000
eureka.instance.hostname=localhost
# \u662F\u5426\u5C06\u81EA\u8EAB\u5B9E\u4F8B\u6CE8\u518C\u5230Eureka default true
eureka.client.register-with-eureka=false
# \u662F\u5426\u4ECEEureka \u83B7\u53D6\u6CE8\u518C\u4FE1\u606F
eureka.client.fetch-registry=false
#\u6D4B\u8BD5
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
eureka.instance.lease-renewal-interval-in-seconds=30
eureka.instance.lease-expiration-duration-in-seconds=90
#\uFF08\u8BBE\u4E3Afalse\uFF0C\u5173\u95ED\u81EA\u6211\u4FDD\u62A4\u4E3B\u8981\uFF09
eureka.server.enable-self-preservation=false
#\u6E05\u7406\u95F4\u9694\uFF08\u5355\u4F4D\u6BEB\u79D2\uFF0C\u9ED8\u8BA4\u662F60*1000\uFF09
eureka.server.eviction-interval-timer-in-ms= 30000
#security.basic.enabled=true
#security.user.name=admin
#security.user.password=admin123
# \u4E0D\u62A5\u544AZipkin
#spring.zipkin.enabled=false
server.port=21000
eureka.instance.hostname=localhost
# \u662F\u5426\u5C06\u81EA\u8EAB\u5B9E\u4F8B\u6CE8\u518C\u5230Eureka default true
eureka.client.register-with-eureka=false
# \u662F\u5426\u4ECEEureka \u83B7\u53D6\u6CE8\u518C\u4FE1\u606F
eureka.client.fetch-registry=false
#\u751F\u4EA7
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
eureka.instance.lease-renewal-interval-in-seconds=30
eureka.instance.lease-expiration-duration-in-seconds=90
#\uFF08\u8BBE\u4E3Afalse\uFF0C\u5173\u95ED\u81EA\u6211\u4FDD\u62A4\u4E3B\u8981\uFF09
eureka.server.enable-self-preservation=false
#\u6E05\u7406\u95F4\u9694\uFF08\u5355\u4F4D\u6BEB\u79D2\uFF0C\u9ED8\u8BA4\u662F60*1000\uFF09
eureka.server.eviction-interval-timer-in-ms= 30000
#security.basic.enabled=true
#security.user.name=admin
#security.user.password=admin123
# \u4E0D\u62A5\u544AZipkin
spring.zipkin.enabled=false
spring.cloud.config.enabled=false
spring.cloud.config.fail-fast=false
spring.application.name=service-eureka
spring.profiles.active=dev
#spring.profiles.active=test
#spring.profiles.active=reg
#spring.profiles.active=prod
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.polysoft.framework.micro</groupId>
<artifactId>micro-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>micro-base</artifactId>
<packaging>pom</packaging>
<modules>
<module>micro-registry-eureka</module>
<module>micro-gateway-zuul</module>
</modules>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>micro-business</artifactId>
<groupId>com.polysoft.framework.micro</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<packaging>jar</packaging>
<modelVersion>4.0.0</modelVersion>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.ctrip.framework.apollo</groupId>-->
<!--<artifactId>apollo-client</artifactId>-->
<!--<version>1.1.0</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>com.ctrip.framework.apollo</groupId>-->
<!--<artifactId>apollo-client</artifactId>-->
<!--<version>RELEASE</version>-->
<!--</dependency>-->
<!--文件转图片相关依赖-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.11</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cells</artifactId>
<version>8.5.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<!--文件转图片相关依赖-->
<dependency>
<groupId>org.artofsolving.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>3.0-beta-4-jahia2</version>
</dependency>
<!--<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.2.2</version>
</dependency>-->
<!--<dependency>-->
<!--<groupId>org.openoffice</groupId>-->
<!--<artifactId>juh</artifactId>-->
<!--<version>4.1.2</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.openoffice</groupId>-->
<!--<artifactId>jurt</artifactId>-->
<!--<version>4.1.2</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.openoffice</groupId>-->
<!--<artifactId>ridl</artifactId>-->
<!--<version>4.1.2</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.openoffice</groupId>-->
<!--<artifactId>unoil</artifactId>-->
<!--<version>4.1.2</version>-->
<!--</dependency>-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>jurt</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>ridl</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>juh</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>unoil</artifactId>
<version>4.1.2</version>
</dependency>
<!--jodconverter2.2.1必须依赖slf4j-jdk14必须这个版本,不然源码中日志会报错,很low的一个问题-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.4.3</version>
</dependency>
</dependencies>
<artifactId>ServiceSdk</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<skip>true</skip>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.polysoft.utils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
public class Base64Image {
public static void main(String[] args) {
// 测试从Base64编码转换为图片文件
String strImg = "iVBORw0KGgoAAAANSUhEUgAAAMgAAAA2CAYAAACCwNb3AAAHh0lEQVR4Xu2dd+jlRBDHPXvvvcCJHRv23isiKoqi2MWOvYBiARFFwS6K3VMUG9hFESx/iNgLdgW9syD2gopdvx9+ieytKZv3kpdN3gwM7yXZMvPNTnazO7OZNIORIWAI5CIwybAxBAyBfATMQCaweUM8ew0NZYUayrAiIkKgbwZyuLBNdfpH//cXbxoR3ohypCPPtZHJZuJ4CHTNQL7wnvTz9uiO/ujocpD+39cj3TqrSkwGcrpQnClB8gT9LtRZVEcj+FlONfSWn4pvGU3Vna1lTkl+jPhc8azi9cUvFmkzagOZLRHmTP3CsRIN7g8xv6EEloAeI7nvV38nusUoZxMycV8WFk8Tz+FV8LKO123TQC5PKj+uCc0rlPme0l7tpP9d/6+pkL/upAuqwH3F/gMqxavu+orKw2DuEn/lJfpTxyePUpCa62LChJHIURk4p1XtneieW3WdPQg3nXeCj2pWtKw4buTnSSK6zwfLMnTk+meSc0lPVu7XO+K5nPNgPl8LOk1VnZsn9fL+9EMLMvhVLpoYBcP1PPpaFw4VPxAibx0GcocqwhIHoX2UifxViKHPAeLfxH1/kd1IOj7rgBNyvzZR+mWSPOvo95Qq4NaQ9s6kjPQ+1VBkYRFn6Opq4j3F6TtsVoaLdPIK8SdVBAoB3C+PJ9Ye4psCK2J481OSNh3vceNeCsxfOk4MLKerydz3oEHuV57ePG0fymhUc+scw5MZGwLsF5W7vfhXr3z0/Euc6ktjR19X57t1jPHPEijbx0qHAd0WmP5/yaoAPkW5dxEvEFDZNkmaJ720T+h464D82ykNlo5xjTs1ZSBVcd1CGdInND13rFPsGB7t9FUxw6mhqMxAVlHpb4nL0j2mNPQo9+RIs6POP1og6VO6doH48aG06V9mcNkyUYteeJ7IVeT9b2bxsuKVRyQr7z4MQ5mEebjuOvMa/mGq6BzxEgUV8mRbQ/xmiVBv6zqG5hMzSQy1yvLXrXNXymMIxMJoSjw8duiK8I6cK+l/OiS6UP8ZXmFEgxDvNUeIXxDTO7j4DFJeaR7fQK5SjqNLcl2q6yeVljwxlGJI5dPtOrFfQP5xT+KvwZT14uOOVyP6u6C/rxrynO2YNrtO/G2gFK8p3ZoZaRfTuS8DyxjnZD9LeVZ9U9pLf/KGr+OMU+O6FxkIC0iXiE+tKAXd33peHoZZq1YsZxyTbyCln/MUp7em1zZqAQG/2067dab4qrhZpKJjVH6ZG+rc8y3o1sUqfcw5bmq6tYv4jFzmOse1WQa1uDRq/EVq5KjVXyEzfMz0uURPwkKhUYsI1GEgOICx+OMS7h+hizktqt961TjR+T5QCMVMDe98Ri0jUIeB+D3HjdIJXxejYgSYt8eRzqcDdeJWAy8OBIYxkPmlwneeGs/oeLM4VItWClwlcIHwiZ6EtQ+jiBAYxkD8nuNm6XVIRLrFKIq7Mu7KZ71ujHdLMg1iILi1f+Pp87SOt4pUxxjE2klCPJIhCKvBa4mJBjSKEIFBDMTvOWxlvPjGZsV1kAN3nhsibBMmkoNAVQNhexx871PCOW1XQzQTAZw3D864gmMdMRtGHUCgioHgVOiuht+rY+JCjKZHAFfw3XJAmazz0wyw7iAQaiCEfjJUcCk0b3fQGE5Swn2vzCmCWHPio406hkBoI/d7DxYH/Yiwjqlem7i48jP0zAv3ZMGUhVOjDiIQYiD+egc7YAwag95BiHJFJl7m7Jyr+KTheBgaVtwnXHqlS4iBEPDyrqN1SJ5egeQpQ1SfuwuiexmXG3fHkT7jMBa6hTR2C9yZaAp5riFpQyEOmk0QjHqEQFUD2Va6Z0UJ9giS6VRZOtF3xRwFCf4iCMyopwhUNRB8hbK8T/sGDzt4EMG3SIFiO+ta1up437AYa33KDORioePGn5el7zKYGMPG4vsLlPhQ15brspImezUEyhr8ZSrueKfIsvTVao8j9fISY4q4aHWbbY3YBfL7OEQ2KUaFQFmDdw2kb09PNo8u23GPbWpOG9XNsHriQ6CKgbwi8dnHquvElDVT10XES/kHXVfU5B8egSoGgg/R5OGrHHkJfJOET7FdX1IznrV42BoZAv8hUMVAyFSWPiZo2Tt2qrhsL2HiW/zIyJj0MFlaRCCkwbsLhbGvFLMfFxtfn1eC6fm6zq7fRoZAIQIhBsJ+qO5equyazbvIIPtmNXE7kI19t9YuKRw9Yv1EWhO4WJk1IBBiIDRAGpdP7K9LNGEbxPAJZ8EQF/ITlY7ZOCNDoDICIQaSFpq1ayLX2J606W/ZLZUIERq7TewKbiJGhsBQCFQxEOIdGF6tnlMj08B8P2/YndvZxCA1OBbnQrfePFZpkcH9ZNlQ4FhmQ6CKgbho8TGXGNy62UUegzIyBBpBYFADQRg8ewmeYpp0VMTEAB+RIR7DNsQeFepjXM8wBuLCxtdDWZ3m60F1Ufo5ti5+VakuDKyclhGoy0B8NdyP5xCWunuGnsRpp1+9TS+/3jIeVr0hMB0CTRmIwWwI9AIBM5Be3EZToikEzECaQtbK7QUCZiC9uI2mRFMImIE0hayV2wsE/gVJ5Po3zKlb7gAAAABJRU5ErkJggg==";
GenerateImage(strImg, "D:\\wangyc.jpg");
// 测试从图片文件转换为Base64编码
// System.out.println(GetImageStr("D:\\微信图片_20190318151320.jpg"));
}
public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgFilePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.polysoft.utils;
/**
* Base64 工具类
*/
public class Base64Util {
private static final char last2byte = (char) Integer.parseInt("00000011", 2);
private static final char last4byte = (char) Integer.parseInt("00001111", 2);
private static final char last6byte = (char) Integer.parseInt("00111111", 2);
private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
public Base64Util() {
}
public static String encode(byte[] from) {
StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
int num = 0;
char currentByte = 0;
int i;
for (i = 0; i < from.length; ++i) {
for (num %= 8; num < 8; num += 6) {
switch (num) {
case 0:
currentByte = (char) (from[i] & lead6byte);
currentByte = (char) (currentByte >>> 2);
case 1:
case 3:
case 5:
default:
break;
case 2:
currentByte = (char) (from[i] & last6byte);
break;
case 4:
currentByte = (char) (from[i] & last4byte);
currentByte = (char) (currentByte << 2);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
}
break;
case 6:
currentByte = (char) (from[i] & last2byte);
currentByte = (char) (currentByte << 4);
if (i + 1 < from.length) {
currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
}
}
to.append(encodeTable[currentByte]);
}
}
if (to.length() % 4 != 0) {
for (i = 4 - to.length() % 4; i > 0; --i) {
to.append("=");
}
}
return to.toString();
}
}
package cn.com.polysoft.utils;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
/**
* 基础控制类
*/
@Slf4j
public class BaseAction {
/**
* 成功返回,带数据
* @param data
* @return
*/
public Map<String, Object> toResponsSuccess(Object data) {
Map<String, Object> rp = toResponsObject(0, "执行成功", data);
log.info("response:" + rp);
return rp;
}
/**
* 成功返回,自定义信息
* @param msg
* @return
*/
public Map<String, Object> toResponsMsgSuccess(String msg) {
return toResponsObject(0, msg, "");
}
/**
* 失败返回,自定义信息
* @param msg
* @return
*/
public Map<String, Object> toResponsFail(String msg) {
return toResponsObject(1, msg, null);
}
public Map<String, Object> toResponsObject(int requestCode, String msg, Object data) {
Map<String, Object> obj = new HashMap<String, Object>();
obj.put("errno", requestCode);
obj.put("errmsg", msg);
if (data != null)
obj.put("data", data);
return obj;
}
/**
* 分页计算
@return
*/
public static int [] getPaging(Integer pageNO,Integer pageSize){
if(0 == pageSize){
pageSize = 10;
}
int [] paging = new int[2];
int startNum = (pageNO-1)*pageSize;
int endNum = pageSize*pageNO;
paging[0] = startNum;
paging[1] = endNum;
return paging;
}
/**
* 成功返回,带数据,并分页
* @return
*/
public Map<String, Object> toResponsListPage(long total,Object list) {
Map listMap = new HashMap();
listMap.put("total",total);
listMap.put("list",list);
Map<String, Object> rp = toResponsObject(0, "执行成功", listMap);
log.info("response:" + rp);
return rp;
}
/**
* 失败返回,自定义信息,自定义状态
* @param msg
* @return
*/
public Map<String, Object> toResponsFailCode(int requestCode, String msg) {
Map<String, Object> obj = new HashMap<String, Object>();
obj.put("errno", requestCode);
obj.put("errmsg", msg);
return obj;
}
}
package cn.com.polysoft.utils;
public class Constant {
public static final String FILE_SUFFIX[] = { ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".txt" };
public static final String PDF_SUFFIX = ".pdf";
public static final String OFFICE_HOME = "/opt/openoffice4";
public static final int PORT = 8100;
public static final long EXECUTE_OVERTIME = 2 * 60 * 1000;
public static final long QUEUE_OVERTIME = 5 * 60 * 1000;
}
package cn.com.polysoft.utils;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.sun.star.awt.Size;
import com.sun.star.beans.PropertyValue;
import com.sun.star.lang.XComponent;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.view.PaperFormat;
import com.sun.star.view.XPrintable;
/**
* @author weijixiang
* @Description
* @date 2019/10/24.
*/
public class ConverterDocument extends OpenOfficeDocumentConverter {
public ConverterDocument(OpenOfficeConnection connection) {
super(connection);
}
public final static Size A5, A4, A3;
public final static Size B4, B5, B6;
public final static Size KaoqinReport;
static {
A5 = new Size(14800, 21000);
A4 = new Size(21000, 29700);
A3 = new Size(29700, 42000);
B4 = new Size(25000, 35300);
B5 = new Size(17600, 25000);
B6 = new Size(12500, 17600);
KaoqinReport = new Size(29700, 27940); //最大限度 宽 1600000
}
@Override
protected void refreshDocument(XComponent document) {
super.refreshDocument(document);
// The default paper format and orientation is A4 and portrait. To
// change paper orientation
// re set page size
XPrintable xPrintable = (XPrintable) UnoRuntime.queryInterface(XPrintable.class, document);
PropertyValue[] printerDesc = new PropertyValue[2];
// Paper Orientation
// printerDesc[0] = new PropertyValue();
// printerDesc[0].Name = "PaperOrientation";
// printerDesc[0].Value = PaperOrientation.PORTRAIT;
// Paper Format
printerDesc[0] = new PropertyValue();
printerDesc[0].Name = "PaperFormat";
printerDesc[0].Value = PaperFormat.USER;
// Paper Size
printerDesc[1] = new PropertyValue();
printerDesc[1].Name = "PaperSize";
printerDesc[1].Value = KaoqinReport;
try {
xPrintable.setPrinter(printerDesc);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package cn.com.polysoft.utils;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
*
*
* 日期转换处理
*/
public class DateUtil {
public static final String C_DATE_DIVISION = "-";
public static final String C_TIME_PATTON_DEFAULT = "yyyy-MM-dd HH:mm:ss";
public static final String C_DATE_PATTON_DEFAULT = "yyyy-MM-dd";
public static final String C_TIMES_PATTON_DEFAULT = "HH:mm:ss";
/**
* 返回当前时间
* @return
*/
public static Date getCurrentDate() {
Calendar cal = Calendar.getInstance();
Date currDate = cal.getTime();
return currDate;
}
/**
* 返回当前日期(String)
* @return
*/
public static String getCurrentDateStr() {
Calendar cal = Calendar.getInstance();
Date currDate = cal.getTime();
return format(currDate,C_DATE_PATTON_DEFAULT);
}
/**
* 返回当前时间(String)
* @return
*/
public static String getCurrentTimeStr() {
Calendar cal = Calendar.getInstance();
Date currDate = cal.getTime();
return format(currDate,C_TIMES_PATTON_DEFAULT);
}
/**
* 格式化日期字符串
* @param dateValue
* @return
*/
public static Date parseDate(String dateValue) {
return parseDate(C_DATE_PATTON_DEFAULT, dateValue);
}
/**
* 格式化时间字符串
* @param dateValue
* @return
*/
public static Date parseDateTime(String dateValue) {
return parseDate(C_TIME_PATTON_DEFAULT, dateValue);
}
/**
* 时间格式化
* @param strFormat
* @param dateValue
* @return
*/
public static Date parseDate(String strFormat, String dateValue) {
if (dateValue == null)
return null;
if (strFormat == null)
strFormat = C_TIME_PATTON_DEFAULT;
SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat);
Date newDate = null;
try {
newDate = dateFormat.parse(dateValue);
} catch (ParseException pe) {
newDate = null;
}
return newDate;
}
/**
* 将Timestamp类型的日期转换为系统参数定义的格式的字符串(yyyy-MM-dd)
*
* @param timestamp 需要转换的日期。
* @return 转换后符合给定格式的日期字符串
*/
public static String format(Date timestamp) {
return format(timestamp, C_DATE_PATTON_DEFAULT);
}
/**
* 将Timestamp类型的日期转换为系统参数定义的格式的字符串(yyyy-MM-dd HH:mm:ss)
*
* @param timestamp 需要转换的日期。
* @return 转换后符合给定格式的日期字符串
*/
public static String formatTime(Date timestamp) {
return format(timestamp, C_TIME_PATTON_DEFAULT);
}
/**
* 将Date类型的日期转换为系统参数定义的格式的字符串。
*
* @param timestamp
* @param pattern
* @return
*/
public static String format(Date timestamp, String pattern) {
if (timestamp == null || pattern == null)
return null;
SimpleDateFormat dateFromat = new SimpleDateFormat();
dateFromat.applyPattern(pattern);
return dateFromat.format(timestamp);
}
/**
* 取得格式化时间字符串(指定format)
* @param aTs_Datetime
* @param as_Format
* @return
*/
public static String formatTime(Date aTs_Datetime, String as_Format) {
if (aTs_Datetime == null || as_Format == null)
return null;
SimpleDateFormat dateFromat = new SimpleDateFormat();
dateFromat.applyPattern(as_Format);
return dateFromat.format(aTs_Datetime);
}
/**
* 取得格式化时间字符串(指定pattern)
* @return
*/
public static String format(Timestamp dateTime, String pattern) {
if (dateTime == null || pattern == null)
return null;
SimpleDateFormat dateFromat = new SimpleDateFormat();
dateFromat.applyPattern(pattern);
return dateFromat.format(dateTime);
}
/**
* 取得指定日期N天后的日期
*
* @param date
* @param days
* @return
*/
public static Date addDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}
/**
* 取得指定日期N天前的日期
*
* @param days
* @return
*/
public static String beforeDays(String dateString, int days) {
String dateBefore = "";
Integer day = Integer.parseInt(dateString.substring(8));
if(day > days){
dateBefore= dateString.substring(0,4) + C_DATE_DIVISION +dateString.substring(5,7) +C_DATE_DIVISION+ (day - days);
}else{
dateBefore = dateString.substring(0,4) + C_DATE_DIVISION + (Integer.parseInt(dateString.substring(5,7))-1)+ C_DATE_DIVISION + day;
}
return dateBefore;
}
/**
* 计算两个日期之间相差的天数
*
* @param date1
* @param date2
* @return
*/
public static int daysBetween(Date date1, Date date2) {
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
long time1 = cal.getTimeInMillis();
cal.setTime(date2);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
* 计算当前日期相对于"1977-12-01"的天数
*
* @param date
* @return
*/
public static long getRelativeDays(Date date) {
Date relativeDate = DateUtil.parseDate("yyyy-MM-dd", "1977-12-01");
return DateUtil.daysBetween(relativeDate, date);
}
/**
* 传入时间字符串,加一天后返回Date
*
* @param date 时间 格式 YYYY-MM-DD
* @return
*/
public static Date addDate(String date) {
if (date == null) {
return null;
}
Date tempDate = parseDate(C_DATE_PATTON_DEFAULT, date);
String year = format(tempDate, "yyyy");
String month = format(tempDate, "MM");
String day = format(tempDate, "dd");
GregorianCalendar calendar = new GregorianCalendar(Integer
.parseInt(year), Integer.parseInt(month) - 1, Integer
.parseInt(day));
calendar.add(Calendar.DATE, 1);
return calendar.getTime();
}
/**
* 取得12月前的日期
* @return
*/
public static Date getDateBeforTwelveMonth() {
String date = "";
Calendar cla = Calendar.getInstance();
cla.setTime(getCurrentDate());
int year = cla.get(Calendar.YEAR) - 1;
int month = cla.get(Calendar.MONTH) + 1;
if (month > 9) {
date = String.valueOf(year) + C_DATE_DIVISION
+ String.valueOf(month) + C_DATE_DIVISION + "01";
} else {
date = String.valueOf(year) + C_DATE_DIVISION + "0"
+ String.valueOf(month) + C_DATE_DIVISION + "01";
}
Date dateBefore = parseDate(date);
return dateBefore;
}
/**
* 取得指定日期所在周开始
* @param date
* @return
*/
public static String getWeekStartDate(String date){
Calendar cal =Calendar.getInstance();
if (date!=null) {
cal.setTime(DateUtil.parseDate(date));
}
cal.add(Calendar.WEEK_OF_YEAR, 0);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
String theWeekStartDate = format(cal.getTime());
cal.clear();
return theWeekStartDate;
}
/**
* 取得指定日期所在周结束
* @param date
* @return
*/
public static String getWeekEndDate(String date){
Calendar cal =Calendar.getInstance();
if (date!=null) {
cal.setTime(DateUtil.parseDate(date));
}
cal.add(Calendar.WEEK_OF_YEAR, 0);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String theWeekStartDate = format(cal.getTime());
cal.clear();
return theWeekStartDate;
}
/**
* 取得指定日期所在月开始
* @param date
* @return
*/
public static String getMonthStartDate(String date){
Calendar cal =Calendar.getInstance();
if (date!=null&&date.trim().length()!=0) {
cal.setTime(DateUtil.parseDate(date));
}
cal.add(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH,1 );
String theWeekStartDate = format(cal.getTime(), C_DATE_PATTON_DEFAULT);
cal.clear();
return theWeekStartDate;
}
/**
* 取得指定日期所在月开始
* @param date
* @return
*/
public static String getMonthEndDate(String date){
Calendar cal =Calendar.getInstance();
if (date!=null&&date.trim().length()!=0) {
cal.setTime(DateUtil.parseDate(date));
}
cal.add(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DAY_OF_MONTH));
String theWeekStartDate = format(cal.getTime(), C_DATE_PATTON_DEFAULT);
cal.clear();
return theWeekStartDate;
}
/**
* 得到两个日期之间相差的年数
*
* @param date1
* @param date2
* @author mowei
*/
public static int getDifferYear(Date date1, Date date2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(date1);
c2.setTime(date2);
return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
}
public static void main(String[]args){
System.out.println(getDifferYear(new Date(),parseDate("2000-12-31")));
}
}
package cn.com.polysoft.utils;
/**
*
* @author H.Yang
* @date 2017年9月8日
*/
public enum FileSuffixType {
DOC(".doc", "Word文档"), //
DOCX(".docx", "Word文档"), //
XLS(".xls", "Excel文档"), //
XLSX(".xlsx", "Excel文档"), //
PPT(".ppt", "PowerPoint文档"), //
PPTX(".pptx", "PowerPoint文档"), //
TXT(".text", "记事本文档"), //
RETURNTYPE(".pdf", "便携式文档格式"), //
FILEPATH("/opt/openoffice4", "OpenOffice安装路径"), //
PORT(8100, "设置转换端口,默认为8100"), //
EXECUTE_OVERTIME(2 * 60 * 1000, "设置任务执行超时为2分钟"), //
QUEUE_OVERTIME(5 * 60 * 1000, "设置任务队列超时为5分钟");
private Object value;
private String name;
private String explain;
FileSuffixType(String name, String explain) {
this.name = name;
this.explain = explain;
}
FileSuffixType(Object value, String explain) {
this.value = value;
this.explain = explain;
}
public Object getValue() {
return value;
}
public String getName() {
return name;
}
public String getExplain() {
return explain;
}
}
package cn.com.polysoft.utils;
import org.springframework.util.StringUtils;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 文件读取工具类
*/
public class FileUtil {
/**
* 读取文件内容,作为字符串返回
*/
public static String readFileAsString(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
}
if (file.length() > 1024 * 1024 * 1024) {
throw new IOException("File is too large");
}
StringBuilder sb = new StringBuilder((int) (file.length()));
// 创建字节输入流
FileInputStream fis = new FileInputStream(filePath);
// 创建一个长度为10240的Buffer
byte[] bbuf = new byte[10240];
// 用于保存实际读取的字节数
int hasRead = 0;
while ( (hasRead = fis.read(bbuf)) > 0 ) {
sb.append(new String(bbuf, 0, hasRead));
}
fis.close();
return sb.toString();
}
/**
* 根据文件路径读取byte[] 数组
*/
public static byte[] readFileByBytes(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
short bufSize = 1024;
byte[] buffer = new byte[bufSize];
int len1;
while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
bos.write(buffer, 0, len1);
}
byte[] var7 = bos.toByteArray();
return var7;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException var14) {
var14.printStackTrace();
}
bos.close();
}
}
}
/**
* 保存文件
* @param path
* @param fileName
* @param str
* @return
*/
public static boolean saveFile(String path,String fileName,String str){
boolean flag = true;
if(!StringUtils.isEmpty(path) && !StringUtils.isEmpty(fileName) && !StringUtils.isEmpty(str)){
createFileByGBK(path, fileName, str);
LogUtils.logInfo("---------文件保存成功--------");
}else{
flag = false;
LogUtils.logError("--------文件保存失败--------");
}
return flag;
}
/**
*
* @param path
* @param fileName
* @param str
* @return
*/
public static boolean saveFile2(String path,String fileName,String str){
boolean flag = true;
if(str != null && !str.equals("")){
String dateDir = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
path = path + "/" + dateDir + "/";
try {
createFileByGBK(path,fileName,str);
} catch (Exception e) {
flag = false;
LogUtils.logInfo("------- 文件保存失败-----------"+e);
}
}else{
flag = false;
LogUtils.logError("------- 文件信息内容为空-----------");
}
return flag;
}
/**
* 以GBK编码存储文件
*2018年5月7日
@param path
@param fileName
@param str
*/
private static void createFileByGBK(String path, String fileName,String str) {
StringBuffer sb = new StringBuffer(str);
try {
createFile(path,sb, "GBK",fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 写文件到指定目录
@param path
@param str
@param encode
@param fileName
*/
public static synchronized void createFile(String path, StringBuffer str, String encode,String fileName) {
boolean type = createDir(path);
if(type == true ){
BufferedWriter writer = null;
try {
FileOutputStream writerStream = new FileOutputStream(path+ "/" + fileName);
writer = new BufferedWriter(new OutputStreamWriter(writerStream,encode));
writer.write(str.toString());
LogUtils.logInfo("------------文件写入完成--------------");
} catch (Exception e) {
LogUtils.logError("-------------文件写入失败-------------");
e.printStackTrace();
}finally{
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
LogUtils.logInfo("-------------文件路径不存在--------------path:"+path+"---fileName:"+fileName+".xml");
}
}
/**
* 根据传入path,创建目录
*2018年5月7日
@param path
@return
*/
private static boolean createDir(String path) {
File dir = new File(path);
if(dir.exists()) {
LogUtils.logInfo("--------文件夹已经存在---------:");
return true;
}else{
if(!path.endsWith(File.separator))
path = path + File.separator;
// 创建单个目录
if(dir.mkdirs()) {
LogUtils.logInfo("创建目录:" + path + " 成功!");
return true;
} else {
LogUtils.logInfo("创建目录:" + path + " 失败!");
return false;
}
}
}
public static void CopySingleFileTo(String oldPathFile, String targetPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPathFile);
String targetfile = targetPath ;
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPathFile); //读入原文件
FileOutputStream fs = new FileOutputStream(targetfile);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
//System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package cn.com.polysoft.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* http 工具类
*/
public class HttpUtil {
public static String post(String requestUrl, String accessToken, String params)
throws Exception {
String contentType = "application/x-www-form-urlencoded";
return HttpUtil.post(requestUrl, accessToken, contentType, params);
}
public static String post(String requestUrl, String accessToken, String contentType, String params)
throws Exception {
String encoding = "UTF-8";
if (requestUrl.contains("nlp")) {
encoding = "GBK";
}
return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
}
public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
throws Exception {
String url = requestUrl + "?access_token=" + accessToken;
return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
}
public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
throws Exception {
URL url = new URL(generalUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
// 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(params.getBytes(encoding));
out.flush();
out.close();
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> headers = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.err.println(key + "--->" + headers.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), encoding));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
// System.err.println("result:" + result);
return result;
}
}
package cn.com.polysoft.utils;
/**
* id生成策略
* @author weijixiang
* @Description
* @date 2019/7/31.
*/
public class IDUtils {
private static byte[] lock = new byte[0];
/**
* 5位数
*/
private final static long w = 100000;
/**
* 使用时间戳+5位随机数作为主键ID
* @return
*/
public static String createID() {
long r = 0;
synchronized (lock) {
r = (long) ((Math.random() + 1) * w);
}
return System.currentTimeMillis() + String.valueOf(r).substring(1);
}
}
package cn.com.polysoft.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
public class LogUtils {
/**
* 错误输入日志
*/
public static final Logger log = LoggerFactory.getLogger(LogUtils.class);
/**
* 获得模块方法中文
* 新模块自己添加key value
*
* @param moduleName
* @return
*/
public static String getModuleName(String moduleName) {
Map<String,String> map=new HashMap<>();
map.put("user","用户模块");
map.put("template","模板模块");
map.put("uploadFile","文件上传模块");
map.put("fileToImg","文件转图片");
String newModuleName = map.get(moduleName);
return newModuleName;
}
/**
* 记录一直 info信息
*
* @param message
*/
public static void logInfo(String message) {
StringBuilder s = new StringBuilder();
s.append((message));
log.info(s.toString());
}
public static void logInfo(String message, Throwable e) {
StringBuilder s = new StringBuilder();
s.append(("exception : -->>"));
s.append((message));
log.info(s.toString(), e);
}
/**
* 日志正常输出
*
* @param message 日志打印信息
* @param moduleName 模块名
* @param className 当前类
* @param methodsName 方法名
*/
public static void logInfo(String message, String moduleName,Class className,String methodsName) {
String newModuleName = getModuleName(moduleName);
StringBuilder s = new StringBuilder();
//去除多余字符串
s.append(("["+newModuleName+"]:"));
//s.append(("当前类路径:-->>"));
//去除多余字符串
String substring = className.toString().substring(5);
s.append(("[类路径:"+substring+"]"));
//s.append("当前方法:-->>");
s.append(("[方法名:"+methodsName+"]"));
s.append("[打印信息:"+message+"]");
//s.append(message);
log.info(s.toString());
}
public static void logWarn(String message) {
StringBuilder s = new StringBuilder();
s.append((message));
log.warn(s.toString());
}
public static void logWarn(String message, Throwable e) {
StringBuilder s = new StringBuilder();
s.append(("exception : -->>"));
s.append((message));
log.warn(s.toString(), e);
}
public static void logDebug(String message) {
StringBuilder s = new StringBuilder();
s.append((message));
log.debug(s.toString());
}
public static void logDebug(String message, Throwable e) {
StringBuilder s = new StringBuilder();
s.append(("exception : -->>"));
s.append((message));
log.debug(s.toString(), e);
}
public static void logError(String message) {
StringBuilder s = new StringBuilder();
s.append(message);
log.error(s.toString());
}
/**
* 日志异常输出
*
* @param message 日志打印信息
* @param e 异常信息
* @param moduleName 模块名
* @param methodsName 方法名
*/
public static void logError(String message, Throwable e, String moduleName,Class className,String methodsName) {
String newModuleName = getModuleName(moduleName);
StringBuilder s = new StringBuilder();
s.append(("["+newModuleName+"]:"));
//s.append(("当前类路径:-->>"));
//去除多余字符串
String substring = className.toString().substring(5);
s.append(("[类路径:"+substring+"]"));
//s.append("当前方法:-->>");
s.append(("[方法名:"+methodsName+"]"));
s.append(("[错误信息:"+message+"]"));
//s.append((message));
log.error(s.toString(), e);
}
public static void main(String[] args) {
try {
Integer a=1;
Integer b=0;
Integer c=a/b;
logInfo("成功执行","user",UploadFileUtils.class,"main");
}catch (Exception e){
logError(e.getMessage(),e,"user",LogUtils.class,"main");
}
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.polysoft.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5Utils {
// 全局数组
private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public static String getFileMD5(byte[] bytes){
try {
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(bytes);
// digest()最后确定返回md5 hash值,返回值为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示,得到字符串形式的hash值
return new BigInteger(1,md.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
// 返回形式为数字跟字符串
private static String byteToArrayString(byte bByte) {
int iRet = bByte;
// System.out.println("iRet="+iRet);
if (iRet < 0) {
iRet += 256;
}
int iD1 = iRet / 16;
int iD2 = iRet % 16;
return strDigits[iD1] + strDigits[iD2];
}
// 返回形式只为数字
@SuppressWarnings("unused")
private static String byteToNum(byte bByte) {
int iRet = bByte;
System.out.println("iRet1=" + iRet);
if (iRet < 0) {
iRet += 256;
}
return String.valueOf(iRet);
}
// 转换字节数组为16进制字串
private static String byteToString(byte[] bByte) {
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < bByte.length; i++) {
sBuffer.append(byteToArrayString(bByte[i]));
}
return sBuffer.toString();
}
public static String GetMD5Code(String strObj) {
String resultString = null;
try {
resultString = new String(strObj);
MessageDigest md = MessageDigest.getInstance("MD5");
// md.digest() 该函数返回值为存放哈希值结果的byte数组
resultString = byteToString(md.digest(strObj.getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return resultString;
}
public static void main(String[] args) {
System.out.println(GetMD5Code("123"));
}
}
package cn.com.polysoft.utils;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormatRegistry;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import org.apache.commons.lang3.StringUtils;
public class OpenOfficeUtils {
public static final String LOCAL_HOST = "localhost";
public static final int LOCAL_PORT = 8100;
// Format
public static DocumentFormatRegistry formatFactory = new DefaultDocumentFormatRegistry();
/**
*
* @desc
* @auth josnow
* @date 2017年6月9日 下午4:11:04
* @param inputFilePath
* 待转换的文件路径
* @param outputFilePath
* 输出文件路径
*/
public static void convert(String inputFilePath, String outputFilePath) throws ConnectException {
convert(inputFilePath, outputFilePath, LOCAL_HOST, LOCAL_PORT);
}
/**
*
* @desc
* @auth josnow
* @date 2017年6月9日 下午4:12:29
* @param inputFilePath
* 待转换的文件路径
* @param outputFilePath
* 输出文件路径
* @param connectIp
* 远程调用ip
* @param connectPort
* 远程调用端口
*/
public static void convert(String inputFilePath, String outputFilePath, String connectIp, int connectPort)
throws ConnectException {
if (StringUtils.isEmpty(inputFilePath) || StringUtils.isEmpty(outputFilePath)
|| StringUtils.isEmpty(connectIp)) {
throw new IllegalArgumentException("参数异常!!");
}
OpenOfficeConnection connection = new SocketOpenOfficeConnection(connectIp,connectPort);
connection.connect();
// TODO Excel转成PDF默认是A4纸
// DocumentConverter converter = getConverter(connectIp, connection);
// converter.convert(new File(inputFilePath), new File(outputFilePath));
// TODO Excel转成PDF默认是A4纸, 如果现实折行,则自定义ConverterDocument,改变纸张大小
ConverterDocument converterDocument = new ConverterDocument(connection);
converterDocument.convert(new File(inputFilePath), new File(outputFilePath));
connection.disconnect();
}
/**
*
* @desc
* @auth josnow
* @date 2017年6月9日 下午4:08:26
* @param inputStream
* @param inputFileExtension
* 待转换文件的扩展名,例如: xls,doc
* @param outputStream
* @param outputFileExtension
* 输出文件扩展名,例如:pdf
*/
public static void convert(InputStream inputStream, String inputFileExtension, OutputStream outputStream,
String outputFileExtension) throws ConnectException {
convert(inputStream, inputFileExtension, outputStream, outputFileExtension, LOCAL_HOST, LOCAL_PORT);
}
/**
*
* @desc
* @auth josnow
* @date 2017年6月9日 下午4:10:21
* @param inputStream
* @param inputFileExtension
* 待转换文件的扩展名,例如: xls,doc
* @param outputStream
* @param outputFileExtension
* 输出文件扩展名,例如:pdf
* @param connectIp
* 远程调用ip
* @param connectPort
* 远程调用端口
*/
public static void convert(InputStream inputStream, String inputFileExtension, OutputStream outputStream,
String outputFileExtension, String connectIp, int connectPort) throws ConnectException {
if (inputStream == null || StringUtils.isEmpty(inputFileExtension) || outputStream == null
|| StringUtils.isEmpty(outputFileExtension) || StringUtils.isEmpty(connectIp)) {
throw new IllegalArgumentException("参数异常!!");
}
OpenOfficeConnection connection = new SocketOpenOfficeConnection(connectIp,connectPort);
connection.connect();
DocumentConverter converter = getConverter(connectIp, connection);
converter.convert(inputStream, formatFactory.getFormatByFileExtension(inputFileExtension), outputStream,
formatFactory.getFormatByFileExtension(outputFileExtension));
connection.disconnect();
}
private static DocumentConverter getConverter(String connectIp, OpenOfficeConnection connection) {
DocumentConverter converter = "localhost".equals(connectIp) || "127.0.0.1".equals(connectIp)
|| "0:0:0:0:0:0:0:1".equals(connectIp) ? new OpenOfficeDocumentConverter(connection)
: new StreamOpenOfficeDocumentConverter(connection);
return converter;
}
}
package cn.com.polysoft.utils;
import lombok.Data;
/**
* 返回信息封装类
*/
@Data
public class Result {
/**
* 方法返回状态
*/
private int status;
/**
* 方法返回信息
*/
private String message;
/**
* 方法返回数据
*/
private Object data = "";
}
package cn.com.polysoft.utils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import java.io.File;
/**
*
* @author H.Yang
* @date 2017年9月8日
*/
public class SingleOpenOffice {
private static SingleOpenOffice start = new SingleOpenOffice();
private static OfficeManager officeManager;
// 获取唯一可用的对象
public static SingleOpenOffice getStart() {
DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
System.out.println("准备启动服务....");
configuration.setOfficeHome(FileSuffixType.FILEPATH.getName()); // 设置OpenOffice.org安装目录
configuration.setPortNumber((int) FileSuffixType.PORT.getValue()); // 设置转换端口,默认为8100
configuration.setTaskExecutionTimeout(Long.valueOf(String.valueOf(FileSuffixType.EXECUTE_OVERTIME.getValue())));
configuration.setTaskQueueTimeout(Long.valueOf(String.valueOf(FileSuffixType.QUEUE_OVERTIME.getValue())));
officeManager = configuration.buildOfficeManager();
officeManager.start(); // 启动服务
System.out.println("office服务启动成功!");
return start;
}
/**
* 文档转换
* <hr>
* 将doc,docx,xls,xlsx,ppt,pptx,txt等文档转换成PDF文档,如果不指定输出地址默认当前文件地址
*
* @author H.Yang
* @date 2016年12月13日
* @explain
*
* @param inputFilePath
* - 转换文件地址(必须)
* @param outputFilePath
* - 输出地址(可空)
* @param newFileName
* - 新文件名(可空)
* @return
*/
public String execute2Pdf(String inputFilePath, String outputFilePath, String newFileName) {
File inputFile = new File(inputFilePath);
String fileName = inputFile.getName();
String prefix = fileName.substring(fileName.lastIndexOf(".") + 0);
String outputPath = null;
boolean isTrue = false;
if (!inputFile.exists()) {
System.out.println("文件不存在!");
return null;
}
for (String name : Constant.FILE_SUFFIX) {
if (fileName.endsWith(name)) {
isTrue = true;
break;
}
}
if (!isTrue) {
System.out.println("文件格式错误");
return null;
}
if (outputFilePath != null) {
outputPath = newFileName == null ? outputFilePath : outputFilePath;
} else {
outputPath = newFileName == null ? inputFile.getPath().replace(prefix, Constant.PDF_SUFFIX) : inputFile.getPath().replace(fileName, newFileName)
+ Constant.PDF_SUFFIX;
}
File outputFile = new File(outputPath);
if (!outputFile.exists()) {
// 执行方法服务功能
execute(inputFile, outputFile);
} else {
System.out.println("文件已存在");
}
return outputPath;
}
/**
* 执行方法服务功能
*
* @author H.Yang
* @date 2016年12月13日
* @explain
*
* @param inputFile
* @param outputFile
*/
private static void execute(File inputFile, File outputFile) {
long startTime = System.currentTimeMillis();// 获取开始时间
try {
System.out.println("进行文档转换转换:" + inputFile + " --> " + outputFile);
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
//OpenOfficeConnection connection=new SocketOpenOfficeConnection(8100);
//ConverterDocument document=new ConverterDocument(connection);
//document.convert(inputFile, outputFile);
converter.convert(inputFile, outputFile);
System.out.println("Office转换成功");
} catch (Exception e) {
getStop();
e.printStackTrace();
}
long endTime = System.currentTimeMillis(); // 获取结束时间
System.out.println("程序运行时间: " + (endTime - startTime) / 1000 + "s");
}
public static void getStop() {
if (officeManager != null) {
officeManager.stop();
}
System.out.println("office关闭成功!");
}
}
package cn.com.polysoft.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import static com.fasterxml.jackson.databind.util.ISO8601Utils.format;
public class TimeUtils {
/**
* 英文简写(默认)如:2010-12-01
*/
public static String FORMAT_SHORT = "yyyy-MM-dd";
/**
* 英文全称 如:2010-12-01 23:15:06
*/
public static String FORMAT_LONG = "yyyy-MM-dd HH:mm:ss";
/**
* 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.S
*/
public static String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss.S";
/**
* 中文简写 如:2010年12月01日
*/
public static String FORMAT_SHORT_CN = "yyyy年MM月dd";
/**
* 中文全称 如:2010年12月01日 23时15分06秒
*/
public static String FORMAT_LONG_CN = "yyyy年MM月dd日 HH时mm分ss秒";
/**
* 精确到毫秒的完整中文时间
*/
public static String FORMAT_FULL_CN = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒";
/**
* 精确到毫秒的完整中文时间
*/
public static String FORMAT_FULL_CN2 = "yyyyMMddHHmmssSSS";
/**
* 获取时间戳
*/
public static String getTimeString() {
SimpleDateFormat df = new SimpleDateFormat(FORMAT_FULL);
Calendar calendar = Calendar.getInstance();
return df.format(calendar.getTime());
}
/**
* 获取日期年份
* @param date 日期
* @return
*/
public static String getYear(Date date) {
return format(date).substring(0, 4);
}
/**
* 功能描述:返回月
*
* @param date
* Date 日期
* @return 返回月份
*/
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 功能描述:返回日
*
* @param date
* Date 日期
* @return 返回日份
*/
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 功能描述:返回小
*
* @param date
* 日期
* @return 返回小时
*/
public static int getHour(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.HOUR_OF_DAY);
}
/**
* 功能描述:返回分
*
* @param date
* 日期
* @return 返回分钟
*/
public static int getMinute(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MINUTE);
}
/**
* 返回秒钟
*
* @param date
* Date 日期
* @return 返回秒钟
*/
public static int getSecond(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.SECOND);
}
/**
* 功能描述:返回毫
*
* @param date
* 日期
* @return 返回毫
*/
public static long getMillis(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.getTimeInMillis();
}
/**
* 功能描述:返回 年-月-日
*
* @param date
* 日期
* @return 返回yyyy-MM-dd
*/
public static String getYearMonthDay(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateNowStr = sdf.format(date);
return dateNowStr;
}
/**
* 功能描述:返回 年-月-日
*
* @param date
* 日期
* @return 返回yyyy-MM-dd
*/
public static String getYearMonthDay2(Date date){
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_FULL_CN2);
String dateNowStr = sdf.format(date);
return dateNowStr;
}
public static void main(String[] args) {
System.out.println(getYearMonthDay2(new Date()).length());
}
}
package cn.com.polysoft.utils;
import java.text.DecimalFormat;
public class UploadFileUtils {
//计算文件大小
public static String getFileSize(long filesize){
String size = "";
DecimalFormat df = new DecimalFormat("#.00");
if (filesize < 1024) {
size = df.format((double) filesize) + "BT";
} else if (filesize < 1048576) {
size = df.format((double) filesize / 1024) + "KB";
} else if (filesize < 1073741824) {
size = df.format((double) filesize / 1048576) + "MB";
} else {
size = df.format((double) filesize / 1073741824) + "GB";
}
return size;
}
}
package cn.com.polysoft.utils;
import java.util.UUID;
/**
* @author weijixiang
* @Description
* @date 2019/7/18.
*/
public class UuidUtil {
/**
* 获取UUID
* @return
*/
public static String getUUID(){
return UUID.randomUUID().toString().replace("-","");
}
}
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>
sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
</Signature>
</License>
\ No newline at end of file \ No newline at end of file
package cn.com.polysoft.template;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
/**
* @author weijixiang
* @Description
* @date 2019/8/9.
*/
@Configuration
public class Config {
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws IOException {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setMapperLocations(resolver.getResources("classpath:/mapper/**/**.xml"));
try {
//开启驼峰命名转换
bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
package cn.com.polysoft.template;
public class MyException extends Exception{ //创建自定义异常
public MyException(String ErrorExceptin){ //构造方法
super(ErrorExceptin); //父类构造方法
}
}
package cn.com.polysoft.template;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
//import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
//import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.spring.annotation.MapperScan;
//@EnableEurekaClient
//@EnableFeignClients
@EnableScheduling
@SpringBootApplication
@MapperScan("cn.com.polysoft.template.dao")
public class TemplateStarter
{
public static void main(String[] args) throws Exception{
SpringApplication.run(TemplateStarter.class, args);
}
/**
* 解决 使用redisTemplate 存储后的键出现 \x 十六进制编码
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerialize 替换默认序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 设置value的序列化规则和 key的序列化规则
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
redisTemplate.setEnableDefaultSerializer(true);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
// 启动的时候要注意,由于我们在controller中注入了RestTemplate,所以启动的时候需要实例化该类的一个实例
@Autowired
private RestTemplateBuilder builder;
// 使用RestTemplateBuilder来实例化RestTemplate对象,spring默认已经注入了RestTemplateBuilder实例
@Bean
public RestTemplate restTemplate() {
return builder.build();
}
}
package cn.com.polysoft.template.common.annotation;
public @interface WebLog {
/**
* 属性
* 日志描述信息
* 默认为空字符串
*
* @return
*/
String description() default "";
}
package cn.com.polysoft.template.common.aspect;
import lombok.Data;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName RequestLogAspect
* @Description TDD
* Author long
* @Date 2021/8/7
* Version 1.0
**/
@Component
@Aspect
public class LogAspect {
private final static Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);
@Pointcut("@annotation(cn.com.polysoft.template.common.annotation.WebLog)")
public void requestServer() {
}
@Around("requestServer()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long start = System.currentTimeMillis();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Object result = proceedingJoinPoint.proceed();
RequestInfo requestInfo = new RequestInfo();
requestInfo.setIp(request.getRemoteAddr());
requestInfo.setUrl(request.getRequestURL().toString());
requestInfo.setHttpMethod(request.getMethod());
requestInfo.setClassMethod(String.format("%s.%s", proceedingJoinPoint.getSignature().getDeclaringTypeName(),
proceedingJoinPoint.getSignature().getName()));
requestInfo.setRequestParams(getRequestParamsByProceedingJoinPoint(proceedingJoinPoint));
requestInfo.setResult(result);
requestInfo.setTimeCost(System.currentTimeMillis() - start);
// System.err.println("类型====" + requestInfo.getRequestParams().getClass().getTypeName());
//requestInfo.setRequestParams(null);
// requestInfo.setResult(null);
// LOGGER.info("Request Info : {}", JSON.toJSONString(requestInfo));
LOGGER.info("Request Info : {}", requestInfo);
return result;
}
@AfterThrowing(pointcut = "requestServer()", throwing = "e")
public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
RequestErrorInfo requestErrorInfo = new RequestErrorInfo();
requestErrorInfo.setIp(request.getRemoteAddr());
requestErrorInfo.setUrl(request.getRequestURL().toString());
requestErrorInfo.setHttpMethod(request.getMethod());
requestErrorInfo.setClassMethod(String.format("%s.%s", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName()));
requestErrorInfo.setRequestParams(getRequestParamsByJoinPoint(joinPoint));
requestErrorInfo.setException(e);
requestErrorInfo.setException(null);
// LOGGER.info("Error Request Info : {}", JSON.toJSONString(requestErrorInfo));
LOGGER.info("Error Request Info : {}", requestErrorInfo);
}
/**
* 获取入参
*
* @param proceedingJoinPoint
* @return
*/
private Map<String, Object> getRequestParamsByProceedingJoinPoint(ProceedingJoinPoint proceedingJoinPoint) {
//参数名
String[] paramNames = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterNames();
//参数值
Object[] paramValues = proceedingJoinPoint.getArgs();
return buildRequestParam(paramNames, paramValues);
}
private Map<String, Object> getRequestParamsByJoinPoint(JoinPoint joinPoint) {
//参数名
String[] paramNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
//参数值
Object[] paramValues = joinPoint.getArgs();
return buildRequestParam(paramNames, paramValues);
}
private Map<String, Object> buildRequestParam(String[] paramNames, Object[] paramValues) {
Map<String, Object> requestParams = new HashMap<>();
for (int i = 0; i < paramNames.length; i++) {
Object value = paramValues[i];
//如果是文件对象
if (value instanceof MultipartFile) {
MultipartFile file = (MultipartFile) value;
value = file.getOriginalFilename(); //获取文件名
}
requestParams.put(paramNames[i], value);
}
return requestParams;
}
@Data
public class RequestInfo {
private String ip;
private String url;
private String httpMethod;
private String classMethod;
private Object requestParams;
private Object result;
private Long timeCost;
}
@Data
public class RequestErrorInfo {
private String ip;
private String url;
private String httpMethod;
private String classMethod;
private Object requestParams;
private RuntimeException exception;
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.polysoft.template.common.core.domain;
import cn.com.polysoft.template.common.utils.StringUtils;
import java.util.HashMap;
/**
* 操作消息提醒
*
* @author ruoyi
*/
public class AjaxResult extends HashMap<String, Object>
{
private static final long serialVersionUID = 1L;
/** 状态码 */
public static final String CODE_TAG = "code";
/** 返回内容 */
public static final String MSG_TAG = "msg";
/** 数据对象 */
public static final String DATA_TAG = "data";
/**
* 状态类型
*/
public enum Type
{
/** 成功 */
SUCCESS(0),
/** 警告 */
WARN(301),
/** 错误 */
ERROR(500);
private final int value;
Type(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
/**
* 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
*/
public AjaxResult()
{
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param type 状态类型
* @param msg 返回内容
*/
public AjaxResult(Type type, String msg)
{
super.put(CODE_TAG, type.value);
super.put(MSG_TAG, msg);
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param type 状态类型
* @param msg 返回内容
* @param data 数据对象
*/
public AjaxResult(Type type, String msg, Object data)
{
super.put(CODE_TAG, type.value);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data))
{
super.put(DATA_TAG, data);
}
}
/**
* 方便链式调用
*
* @param key 键
* @param value 值
* @return 数据对象
*/
@Override
public AjaxResult put(String key, Object value)
{
super.put(key, value);
return this;
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public static AjaxResult success()
{
return AjaxResult.success("操作成功");
}
/**
* 返回成功数据
*
* @return 成功消息
*/
public static AjaxResult success(Object data)
{
return AjaxResult.success("操作成功", data);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @return 成功消息
*/
public static AjaxResult success(String msg)
{
return AjaxResult.success(msg, null);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static AjaxResult success(String msg, Object data)
{
return new AjaxResult(Type.SUCCESS, msg, data);
}
/**
* 返回警告消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult warn(String msg)
{
return AjaxResult.warn(msg, null);
}
/**
* 返回警告消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static AjaxResult warn(String msg, Object data)
{
return new AjaxResult(Type.WARN, msg, data);
}
/**
* 返回错误消息
*
* @return
*/
public static AjaxResult error()
{
return AjaxResult.error("操作失败");
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult error(String msg)
{
return AjaxResult.error(msg, null);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static AjaxResult error(String msg, Object data)
{
return new AjaxResult(Type.ERROR, msg, data);
}
}
package cn.com.polysoft.template.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
/**
* @ClassName ExcelUtil
* @Description TDD
* Author long
* @Date 2021/9/24
* Version 1.0
**/
@Slf4j
public class ExcelUtils<T> {
/**
* 实体对象
*/
public Class<T> clazz;
public ExcelUtils(Class<T> clazz) {
this.clazz = clazz;
}
// public void exportExcel(Class t, List<T> list, HttpServletResponse response) {
//
// //设置响应头
// response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// response.setCharacterEncoding("utf-8");
//
// response.setHeader("Content-disposition", "attachment;filename=" + UUID.randomUUID() + ".xlsx");
//
// /* 数据生成Excel,并导出 */
// try {
// EasyExcel.write(response.getOutputStream(), t).sheet().doWrite(list);
// } catch (IOException e) {
// log.error("【方法异常-EasyExcel.write-Excel生成并导出】未知,待处理");
// e.printStackTrace();
// }
//
// }
}
package cn.com.polysoft.template.common.utils;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
/**
* @ClassName StringUtils
* @Description TDD
* Author long
* @Date 2021/9/24
* Version 1.0
**/
public class StringUtils extends org.apache.commons.lang3.StringUtils {
/** 空字符串 */
private static final String NULLSTR = "";
/** 下划线 */
private static final char SEPARATOR = '_';
/**
* 获取参数不为空值
*
* @param value defaultValue 要判断的value
* @return value 返回值
*/
public static <T> T nvl(T value, T defaultValue)
{
return value != null ? value : defaultValue;
}
/**
* * 判断一个Collection是否为空, 包含List,Set,Queue
*
* @param coll 要判断的Collection
* @return true:为空 false:非空
*/
public static boolean isEmpty(Collection<?> coll)
{
return isNull(coll) || coll.isEmpty();
}
/**
* * 判断一个Collection是否非空,包含List,Set,Queue
*
* @param coll 要判断的Collection
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Collection<?> coll)
{
return !isEmpty(coll);
}
/**
* * 判断一个对象数组是否为空
*
* @param objects 要判断的对象数组
** @return true:为空 false:非空
*/
public static boolean isEmpty(Object[] objects)
{
return isNull(objects) || (objects.length == 0);
}
/**
* * 判断一个对象数组是否非空
*
* @param objects 要判断的对象数组
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Object[] objects)
{
return !isEmpty(objects);
}
/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true:为空 false:非空
*/
public static boolean isEmpty(Map<?, ?> map)
{
return isNull(map) || map.isEmpty();
}
/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Map<?, ?> map)
{
return !isEmpty(map);
}
/**
* * 判断一个字符串是否为空串
*
* @param str String
* @return true:为空 false:非空
*/
public static boolean isEmpty(String str)
{
return isNull(str) || NULLSTR.equals(str.trim());
}
/**
* * 判断一个字符串是否为非空串
*
* @param str String
* @return true:非空串 false:空串
*/
public static boolean isNotEmpty(String str)
{
return !isEmpty(str);
}
/**
* * 判断一个对象是否为空
*
* @param object Object
* @return true:为空 false:非空
*/
public static boolean isNull(Object object)
{
return object == null;
}
/**
* * 判断一个对象是否非空
*
* @param object Object
* @return true:非空 false:空
*/
public static boolean isNotNull(Object object)
{
return !isNull(object);
}
/**
* * 判断一个对象是否是数组类型(Java基本型别的数组)
*
* @param object 对象
* @return true:是数组 false:不是数组
*/
public static boolean isArray(Object object)
{
return isNotNull(object) && object.getClass().isArray();
}
/**
* 去空格
*/
public static String trim(String str)
{
return (str == null ? "" : str.trim());
}
public static String getUUID() {
return UUID.randomUUID().toString();
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @return 结果
*/
public static String substring(final String str, int start)
{
if (str == null)
{
return NULLSTR;
}
if (start < 0)
{
start = str.length() + start;
}
if (start < 0)
{
start = 0;
}
if (start > str.length())
{
return NULLSTR;
}
return str.substring(start);
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @param end 结束
* @return 结果
*/
public static String substring(final String str, int start, int end)
{
if (str == null)
{
return NULLSTR;
}
if (end < 0)
{
end = str.length() + end;
}
if (start < 0)
{
start = str.length() + start;
}
if (end > str.length())
{
end = str.length();
}
if (start > end)
{
return NULLSTR;
}
if (start < 0)
{
start = 0;
}
if (end < 0)
{
end = 0;
}
return str.substring(start, end);
}
}
package cn.com.polysoft.template.common.utils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* @ClassName TxtUtils
* @Description TDD
* Author long
* @Date 2021/9/28
* Version 1.0
**/
public class TxtUtils {
/* 导出txt文件
* @author
* @param response
* @param text 导出的字符串
* @return
*/
public static void exportTxt(String text,HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
//设置响应的内容类型
response.setContentType("text/plain");
//设置文件的名称和格式
response.addHeader("Content-Disposition", "attachment;filename="
+ genAttachmentFileName(StringUtils.getUUID(), "JSON_FOR_UCC_")//设置名称格式,没有这个中文名称无法显示
+ ".txt");
BufferedOutputStream buff = null;
ServletOutputStream outStr = null;
try {
outStr = response.getOutputStream();
buff = new BufferedOutputStream(outStr);
buff.write(text.getBytes("UTF-8"));
buff.flush();
buff.close();
} catch (Exception e) {
//LOGGER.error("导出文件文件出错:{}",e);
} finally {
try {
buff.close();
outStr.close();
} catch (Exception e) {
//LOGGER.error("关闭流对象出错 e:{}",e);
}
}
}
//防止中文文件名显示出错
public static String genAttachmentFileName(String cnName, String defaultName) {
try {
cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
} catch (Exception e) {
cnName = defaultName;
}
return cnName;
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.polysoft.template.controller;
import cn.com.polysoft.template.dto.ImgDto;
import cn.com.polysoft.template.service.TemplateService;
import cn.com.polysoft.template.service.UploadFileService;
import cn.com.polysoft.utils.BaseAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @description:
* @author: wzy
* @time: 2022/2/28 9:00
*/
@RestController
@RequestMapping("/api")
public class ApiController extends BaseAction {
@Autowired
private UploadFileService uploadFileService;
@Autowired
private HttpServletRequest httpServletRequest;
@Autowired
private TemplateService templateService;
@PostMapping(value = "/fileDiscern")
public Map<String, Object> fileDiscern(@RequestParam("fromServer")String fromServer,
@RequestBody MultipartFile[] file){
Map<String, Object> reBackMap = new HashMap<>();
reBackMap.put("1","123");
//信息验证
System.out.println();
//处理文件
reBackMap = uploadFileService.fileToImg(file, httpServletRequest);
if (reBackMap == null) {
return toResponsFail("账单文件处理失败");
}
//账单识别
Map<String, Object> fileData = (Map<String, Object>) reBackMap.get("data");
String filePath = null;//账单文件路径
List<String> imgList = null;//账单图片
if (fileData != null) {
if (fileData.get("filePath") != null) {
filePath = fileData.get("filePath").toString();
}
if (fileData.get("list") != null) {
imgList = (List<String>) fileData.get("list");
}
}
ImgDto dto = new ImgDto();
if (filePath != null && imgList != null) {
dto.setFilePath(filePath);
dto.setList(imgList);
}
reBackMap = templateService.discernFileData(dto);
//信息返回
return reBackMap;
}
}
package cn.com.polysoft.template.controller;
import cn.com.polysoft.template.dto.BillBaseInfoDTO;
import cn.com.polysoft.template.dto.BillDTO;
import cn.com.polysoft.template.dto.InwardtreatyInfoDto;
import cn.com.polysoft.template.service.BillBaseInfoService;
import cn.com.polysoft.template.utils.BeanUtil;
import cn.com.polysoft.template.vo.BillIFileInfo;
import cn.com.polysoft.template.vo.BillInfoVO;
import cn.com.polysoft.utils.BaseAction;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* 账单
* @author weijixiang
* @Description
* @date 2019/7/31.
*/
@RestController
@RequestMapping("/template/bill")
public class BillController extends BaseAction {
private static final Logger logger = LoggerFactory.getLogger(BillController.class);
@Autowired
private BillBaseInfoService baseInfoService;
@Autowired
private HttpServletRequest request;
@Resource
private HttpServletResponse response;
/**
* 保存账单
* @param billDTO
* @return
*/
@RequestMapping(value = "save",method = RequestMethod.POST)
public Map<String,Object> saveBill(@RequestBody BillDTO billDTO){
try{
return baseInfoService.saveBill(billDTO);
} catch (Exception e){
e.printStackTrace();
return toResponsFail("系统保存失败");
}
}
/**
* 数据检索-查询数据列表
* @param page
* @param limit
* @param brokerName
* @param separateOutName
* @param status
* @param startTime
* @param endTime
* @param keywords
* @return
*/
@RequestMapping(value = "list",method = RequestMethod.GET)
public Map<String,Object> getBillListByCondition(@RequestParam("page") Integer page,
@RequestParam("limit") Integer limit,
@RequestParam("brokerName") String brokerName,
@RequestParam("separateOutName") String separateOutName,
@RequestParam("status") String status,
@RequestParam("startTime") String startTime,
@RequestParam("endTime") String endTime,
@RequestParam("keywords") String keywords,
@RequestParam("brokerCode") String brokerCode,
@RequestParam("separateOut") String separateOut,
@RequestParam("serialNumber") String serialNumber,
@RequestParam("contractCode") String contractCode,
@RequestParam("contractName") String contractName,
@RequestParam("comCode")String comCode){
if(StringUtils.isEmpty(page)){
return toResponsFail("没有页码");
}
if(StringUtils.isEmpty(limit)){
return toResponsFail("没有页码大小");
}
PageHelper.startPage(page,limit);
BillBaseInfoDTO billBaseInfoDTO = new BillBaseInfoDTO();
if(!StringUtils.isEmpty(brokerName)){
billBaseInfoDTO.setBrokerName("%" + brokerName +"%");
}
if(!StringUtils.isEmpty(separateOutName)){
billBaseInfoDTO.setSeparateOutName("%" + separateOutName +"%");
}
billBaseInfoDTO.setStatus(status);
billBaseInfoDTO.setStartTime(startTime);
billBaseInfoDTO.setEndTime(endTime);
if(!StringUtils.isEmpty(keywords)){
billBaseInfoDTO.setKeywords("%"+ keywords +"%");
}
if(!StringUtils.isEmpty(brokerCode)){
billBaseInfoDTO.setBrokerCode("%"+ brokerCode +"%");
}
if(!StringUtils.isEmpty(separateOut)){
billBaseInfoDTO.setSeparateOut("%"+ separateOut +"%");
}
if(!StringUtils.isEmpty(serialNumber)){
billBaseInfoDTO.setSerialNumber("%" + serialNumber + "%");
}
if(!StringUtils.isEmpty(contractCode)){
billBaseInfoDTO.setContractCode("%" + contractCode +"%");
}
if(!StringUtils.isEmpty(contractName)){
billBaseInfoDTO.setContractName("%" + contractName +"%");
}
billBaseInfoDTO.setComCode(comCode);
return toResponsSuccess(BeanUtil.toPagedResult(baseInfoService.getBillListByCondition(billBaseInfoDTO)));
}
/**
* 修改账单信息
* @param billDTO
* @return
*/
@RequestMapping(value = "/modify",method = RequestMethod.PUT)
public Map<String,Object> updateBillInfo(@RequestBody BillDTO billDTO){
if(StringUtils.isEmpty(billDTO.getId())){
return toResponsFail("没有账单ID");
}
try{
// 对提交数据进行账单期校验
InwardtreatyInfoDto queryInfo = baseInfoService.periodCheck(billDTO);
if (queryInfo!=null && !StringUtils.isEmpty(queryInfo.getTimeClues())) {
return toResponsFail(queryInfo.getTimeClues());
}
baseInfoService.modifyBill(billDTO);
return toResponsSuccess(true);
} catch (Exception e){
e.printStackTrace();
return toResponsFail("系统修改失败");
}
}
/**
* 根据账单id,获取账单信息
* @param billId
* @return
*/
@RequestMapping(value = "/info/{billId}",method = RequestMethod.GET)
public Map<String,Object> getBillInfo(@PathVariable("billId") String billId){
if(StringUtils.isEmpty(billId)){
return toResponsFail("没有账单ID");
}
return toResponsSuccess(baseInfoService.getByBillId(billId));
}
/**
* 导出账单信息
* @param brokerName
* @param separateOutName
* @param status
* @param startTime
* @param endTime
* @param keywords
*/
@RequestMapping(value = "/export",method = RequestMethod.GET)
public void exportBillInfoByCondition(@RequestParam("brokerName") String brokerName,
@RequestParam("separateOutName") String separateOutName,
@RequestParam("status") String status,
@RequestParam("startTime") String startTime,
@RequestParam("endTime") String endTime,
@RequestParam("keywords") String keywords,
@RequestParam("brokerCode") String brokerCode,
@RequestParam("separateOut") String separateOut,
@RequestParam("serialNumber") String serialNumber,
@RequestParam("contractCode") String contractCode,
@RequestParam("contractName") String contractName,
@RequestParam("comCode")String comCode){
BillBaseInfoDTO billBaseInfoDTO = new BillBaseInfoDTO();
if(!StringUtils.isEmpty(brokerName)){
billBaseInfoDTO.setBrokerName("%" + brokerName +"%");
}
if(!StringUtils.isEmpty(separateOutName)){
billBaseInfoDTO.setSeparateOutName("%" + separateOutName +"%");
}
billBaseInfoDTO.setStatus(status);
billBaseInfoDTO.setStartTime(startTime);
billBaseInfoDTO.setEndTime(endTime);
if(!StringUtils.isEmpty(keywords)){
billBaseInfoDTO.setKeywords("%"+ keywords +"%");
}
if(!StringUtils.isEmpty(brokerCode)){
billBaseInfoDTO.setBrokerCode("%"+ brokerCode +"%");
}
if(!StringUtils.isEmpty(separateOut)){
billBaseInfoDTO.setSeparateOut("%"+ separateOut +"%");
}
if(!StringUtils.isEmpty(serialNumber)){
billBaseInfoDTO.setSerialNumber("%" + serialNumber + "%");
}
if(!StringUtils.isEmpty(contractCode)){
billBaseInfoDTO.setContractCode("%" + contractCode +"%");
}
if(!StringUtils.isEmpty(contractName)){
billBaseInfoDTO.setContractName("%" + contractName +"%");
}
billBaseInfoDTO.setComCode(comCode);
baseInfoService.exportBillInfoByCondition(billBaseInfoDTO,request,response);
}
/**
* 导出账单信息
* @param billId
*/
@RequestMapping(value = "/exportBillData",method = RequestMethod.GET)
public void exportBillData(@RequestParam("billId") String billId){
BillInfoVO vo = baseInfoService.getByBillId(billId);
baseInfoService.exportBillData(vo,request,response);
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.polysoft.template.controller;
import cn.com.polysoft.template.dto.CompanyDTO;
import cn.com.polysoft.template.service.CompanyService;
import cn.com.polysoft.template.utils.BeanUtil;
import cn.com.polysoft.template.vo.CompanyVO;
import cn.com.polysoft.utils.BaseAction;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* 经纪公司
* @author weijixiang
* @Description
* @date 2019/7/30.
*/
@RestController
@RequestMapping("/template/company")
public class CompanyController extends BaseAction {
@Autowired
private CompanyService companyService;
/**
* 经纪公司选择列表
* @param page
* @param limit
* @param companyName
* @param companyCode
* @return
*/
@RequestMapping(value = "list",method = RequestMethod.GET)
public Map<String,Object> listByCondition(@RequestParam("page") Integer page,
@RequestParam("limit") Integer limit,
@RequestParam("companyName") String companyName,
@RequestParam("companyCode") String companyCode,
@RequestParam("type") String type) {
if(StringUtils.isEmpty(page)){
return toResponsFail("没有页码");
}
if(StringUtils.isEmpty(limit)){
return toResponsFail("没有页码大小");
}
CompanyDTO companyDTO = new CompanyDTO();
if(!StringUtils.isEmpty(companyName)){
companyDTO.setCompanyName("%"+ companyName +"%");
}
if(!StringUtils.isEmpty(companyCode)){
companyDTO.setCompanyCode("%"+ companyCode +"%");
}
companyDTO.setType(type);
PageHelper.startPage(page,limit);
List<CompanyVO> list = companyService.listByCondition(companyDTO);
return toResponsSuccess(BeanUtil.toPagedResult(list));
}
/**
* 查询是否为境外经纪人接口
* @param brokerCode 经纪人编码
* @return
*/
@GetMapping("getAttribute")
public Map<String,Object> getAttribute(@RequestParam("brokerCode") String brokerCode){
return companyService.getAttribute(brokerCode);
}
}
This diff is collapsed. Click to expand it.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!