feat: 提交项目代码

This commit is contained in:
super_liu
2021-05-31 14:56:05 +08:00
parent d50bb875cb
commit 3ed9ca235a
234 changed files with 27792 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
nbbuild/
dist/
nbdist/
.nb-gradle/
target
*.iml
*.ipr
*.iws
.idea
.classpath
.project
.settings
.DS_Store
*.bpmn/
*logs/
.metadata
+17
View File
@@ -0,0 +1,17 @@
# Getting Started
### Reference Documentation
For further reference, please consider the following sections:
* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)
* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.3.2.RELEASE/maven-plugin/reference/html/)
* [Create an OCI image](https://docs.spring.io/spring-boot/docs/2.3.2.RELEASE/maven-plugin/reference/html/#build-image)
* [Java Mail Sender](https://docs.spring.io/spring-boot/docs/2.3.2.RELEASE/reference/htmlsingle/#boot-features-email)
* [MyBatis Framework](https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/)
### Guides
The following guides illustrate how to use some features concretely:
* [MyBatis Quick Start](https://github.com/mybatis/spring-boot-starter/wiki/Quick-Start)
* [Accessing data with MySQL](https://spring.io/guides/gs/accessing-data-mysql/)
+58
View File
@@ -0,0 +1,58 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.adc</groupId>
<artifactId>foton-slrs-system-rest</artifactId>
<version>3.0.0</version>
</parent>
<groupId>com.adc</groupId>
<artifactId>adc-da-base</artifactId>
<version>3.0.0</version>
<name>adc-da-base</name>
<description>laws system rest base</description>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
</dependency>
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerVersion>${java.version}</compilerVersion>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,6 @@
package com.adc.da.base.entity;
public class BaseEntity {
public BaseEntity() {
}
}
@@ -0,0 +1,72 @@
package com.adc.da.base.entity;
import java.util.List;
public abstract class TreeEntity<T extends TreeEntity> extends BaseEntity {
protected String id;
protected String name;
protected String parentId;
protected String parentIds;
protected T parent;
protected List<T> childList;
protected Integer delFlag;
public TreeEntity() {
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getParentId() {
return this.parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getParentIds() {
return this.parentIds;
}
public void setParentIds(String parentIds) {
this.parentIds = parentIds;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public List<T> getChildList() {
return this.childList;
}
public void setChildList(List<T> childList) {
this.childList = childList;
}
public T getParent() {
return this.parent;
}
public void setParent(T parent) {
this.parent = parent;
}
public Integer getDelFlag() {
return this.delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
}
@@ -0,0 +1,91 @@
package com.adc.da.base.page;
public class BasePage {
private Integer page = 1;
private Integer pageSize = 20;
private Integer startIndex;
private Integer endIndex;
private String orderBy;
private String order;
private String q;
private Pager pager = new Pager();
public BasePage() {
}
public Pager getPager() {
this.pager.setPageId(this.getPage());
this.pager.setPageSize(this.getPageSize());
String orderField = "";
if (this.orderBy != null && this.orderBy.trim().length() > 0) {
orderField = this.orderBy;
}
if (orderField.trim().length() > 0 && this.order != null && this.order.trim().length() > 0) {
orderField = orderField + " " + this.order;
}
this.pager.setOrderField(orderField);
return this.pager;
}
public void setPager(Pager pager) {
this.pager = pager;
}
public Integer getPage() {
return this.page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPageSize() {
return this.pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public String getOrderBy() {
return this.orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public String getOrder() {
return this.order;
}
public void setOrder(String order) {
this.order = order;
}
public String getQ() {
return this.q;
}
public void setQ(String q) {
this.q = q;
}
public Integer getStartIndex() {
return this.startIndex;
}
public void setStartIndex(Integer startIndex) {
this.startIndex = (this.page - 1) * this.pageSize + 1;
}
public Integer getEndIndex() {
return this.endIndex;
}
public void setEndIndex(Integer endIndex) {
this.endIndex = this.page * this.pageSize;
}
}
@@ -0,0 +1,169 @@
package com.adc.da.base.page;
public class Pager {
private int pageId = 1;
private int rowCount = 0;
private int pageSize = 10;
private int pageCount = 0;
private int pageOffset = 0;
private int pageTail = 0;
private String orderField;
private boolean orderDirection = true;
private boolean pageEnabled = true;
private int length = 6;
private int startIndex = 0;
private int endIndex = 0;
private int[] indexs;
public Pager() {
}
public int getLength() {
return this.length;
}
public void setLength(int length) {
this.length = length;
}
public int[] getIndexs() {
int len = this.getEndIndex() - this.getStartIndex() + 1;
this.indexs = new int[len];
for(int i = 0; i < len; ++i) {
this.indexs[i] = this.getStartIndex() + i;
}
return this.indexs;
}
public void setIndexs(int[] indexs) {
this.indexs = indexs;
}
public int getStartIndex() {
this.startIndex = (this.pageId - 1) * this.pageSize + 1;
return this.startIndex;
}
public void setStartIndex(int startIndex) {
System.out.println("startIndx:" + this.pageId + ":" + this.pageSize);
this.startIndex = (this.pageId - 1) * this.pageSize + 1;
}
public int getEndIndex() {
this.endIndex = this.pageId * this.pageSize;
return this.endIndex;
}
public void setEndIndex(int endIndex) {
this.endIndex = this.pageId * this.pageSize;
}
protected void doPage() {
this.pageCount = this.rowCount / this.pageSize + 1;
if (this.rowCount % this.pageSize == 0 && this.pageCount > 1) {
--this.pageCount;
}
this.pageOffset = (this.pageId - 1) * this.pageSize;
this.pageTail = this.pageOffset + this.pageSize;
if (this.pageOffset + this.pageSize > this.rowCount) {
this.pageTail = this.rowCount;
}
}
public String getOrderCondition() {
String condition = "";
if (this.orderField != null && this.orderField.length() != 0) {
condition = " order by " + this.orderField + (this.orderDirection ? " " : " desc ");
}
return condition;
}
public String getMysqlQueryCondition() {
String condition = "";
if (this.pageEnabled) {
}
return condition;
}
public void setOrderDirection(boolean orderDirection) {
this.orderDirection = orderDirection;
}
public boolean isOrderDirection() {
return this.orderDirection;
}
public void setOrderField(String orderField) {
this.orderField = orderField;
}
public String getOrderField() {
return this.orderField;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getPageCount() {
return this.pageCount;
}
public void setPageId(int pageId) {
this.pageId = pageId;
}
public int getPageId() {
return this.pageId;
}
public void setPageOffset(int pageOffset) {
this.pageOffset = pageOffset;
}
public int getPageOffset() {
return this.pageOffset;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageSize() {
return this.pageSize;
}
public void setPageTail(int pageTail) {
this.pageTail = pageTail;
}
public int getPageTail() {
return this.pageTail;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
this.doPage();
}
public int getRowCount() {
return this.rowCount;
}
public boolean isPageEnabled() {
return this.pageEnabled;
}
public void setPageEnabled(boolean pageEnabled) {
this.pageEnabled = pageEnabled;
}
}
@@ -0,0 +1,81 @@
package com.adc.da.base.web;
import com.adc.da.base.page.Pager;
import com.adc.da.http.PageInfo;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaseController<T> {
private static final String DATA = "data";
private static final String TOTAL = "total";
protected BaseController() {
}
public PageInfo<T> getPageInfo(Pager pager, List<T> rows) {
PageInfo<T> pageInfo = new PageInfo();
pageInfo.setList(rows);
pageInfo.setCount((long)pager.getRowCount());
pageInfo.setPageSize(pager.getPageSize());
pageInfo.setPageCount((long)pager.getPageCount());
pageInfo.setPageNo(pager.getPageId());
return pageInfo;
}
public static Map<String, Object> getGridData(int total, List<?> rows) {
Map<String, Object> response = new HashMap();
response.put("total", total);
response.put("data", rows);
return response;
}
public static Map<String, Object> getData(Object data) {
Map<String, Object> response = new HashMap();
response.put("data", data);
return response;
}
public static void download(HttpServletResponse response, File file) throws IOException {
download(response, file, file.getName());
}
public static void download(HttpServletResponse response, File file, String fileName) throws IOException {
FileInputStream in = new FileInputStream(file);
Throwable var4 = null;
try {
download(response, (InputStream)in, fileName);
} catch (Throwable var13) {
var4 = var13;
throw var13;
} finally {
if (in != null) {
if (var4 != null) {
try {
in.close();
} catch (Throwable var12) {
var4.addSuppressed(var12);
}
} else {
in.close();
}
}
}
}
public static void download(HttpServletResponse response, InputStream in, String fileName) throws IOException {
response.setContentType("application/x-msdownload;");
response.addHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setCharacterEncoding("UTF-8");
}
}
@@ -0,0 +1,25 @@
package com.adc.da.exception;
public class AdcDaBaseException extends RuntimeException {
private String errorCode;
public AdcDaBaseException() {
}
public AdcDaBaseException(String message) {
this("-1", message);
}
public AdcDaBaseException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return this.errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
@@ -0,0 +1,14 @@
package com.adc.da.file.store;
import java.io.IOException;
import java.io.InputStream;
public interface IFileStore {
String storeFile(InputStream var1, String var2, String var3) throws IOException;
InputStream loadFile(String var1);
byte[] loadFileBytes(String var1);
}
@@ -0,0 +1,34 @@
package com.adc.da.filter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.util.Arrays;
import java.util.Calendar;
public class AddExpiresHeaderResponse extends HttpServletResponseWrapper {
private static final String[] CACHEABLE_CONTENT_TYPES = new String[]{"text/css", "text/javascript", "application/javascript", "image/png", "image/jpeg", "image/gif", "image/jpg"};
private long maxAge = 0L;
public AddExpiresHeaderResponse(HttpServletResponse response, long maxAge) {
super(response);
this.maxAge = maxAge;
}
public void setContentType(String contentType) {
if (contentType != null && Arrays.binarySearch(CACHEABLE_CONTENT_TYPES, contentType) > -1) {
Calendar inTwoMonths = Calendar.getInstance();
inTwoMonths.add(2, 2);
super.setDateHeader("Expires", inTwoMonths.getTimeInMillis());
super.setHeader("Cache-Control", "max-age=" + this.maxAge);
} else {
super.setHeader("Expires", "-1");
super.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
}
super.setContentType(contentType);
}
static {
Arrays.sort(CACHEABLE_CONTENT_TYPES);
}
}
@@ -0,0 +1,78 @@
package com.adc.da.filter;
import com.adc.da.util.FileUtil;
import com.adc.da.util.RequestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class CsrfFilter implements Filter {
private static final Log logger = LogFactory.getLog(CsrfFilter.class);
private List<String> whiteUrls;
private int whitelistSize = 0;
public CsrfFilter() {
}
public void init(FilterConfig filterConfig) {
String path = CsrfFilter.class.getResource("/").getFile();
this.whiteUrls = FileUtil.readAsStringList(path + "white/csrfWhite.txt");
this.whitelistSize = null == this.whiteUrls ? 0 : this.whiteUrls.size();
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
String url = req.getRequestURL().toString();
String referurl = req.getHeader("Referer");
if (this.isWhiteReq(referurl)) {
chain.doFilter(request, response);
} else {
req.getRequestDispatcher("/").forward(req, res);
String log = "";
String date = (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date());
String clientIp = RequestUtils.getClientIp(req);
log = "跨站请求---->>>" + clientIp + "||" + date + "||" + referurl + "||" + url;
logger.warn(log);
}
} catch (Exception var11) {
logger.error("doFilter Exception:", var11);
}
}
private boolean isWhiteReq(String referUrl) {
if (referUrl != null && !"".equals(referUrl) && this.whitelistSize != 0) {
String refHost = "";
referUrl = referUrl.toLowerCase();
if (referUrl.startsWith("http://")) {
refHost = referUrl.substring(7);
} else if (referUrl.startsWith("https://")) {
refHost = referUrl.substring(8);
}
Iterator iterator = this.whiteUrls.iterator();
String urlTemp;
do {
if (!iterator.hasNext()) {
return false;
}
urlTemp = (String)iterator.next();
} while(refHost.indexOf(urlTemp.toLowerCase()) <= -1);
return true;
} else {
return true;
}
}
public void destroy() {
}
}
@@ -0,0 +1,40 @@
package com.adc.da.filter;
import com.adc.da.util.IpUtil;
import eu.bitwalker.useragentutils.UserAgent;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class FakeJSessionIdFilter implements Filter {
public FakeJSessionIdFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
String ip = (String)request.getSession().getAttribute("ip");
String browser = (String)request.getSession().getAttribute("browser");
UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
String newBrowser = userAgent.getBrowser().toString();
String newIp = IpUtil.getIpAddr(request);
if ("0:0:0:0:0:0:0:1".equals(newIp)) {
newIp = "127.0.0.1";
}
request.getSession().setAttribute("ip", newIp);
request.getSession().setAttribute("browser", newBrowser);
if (ip == null || browser == null || newBrowser.equals(browser) && newIp.equals(ip)) {
filterChain.doFilter(req, resp);
} else {
request.getSession().invalidate();
}
}
public void init(FilterConfig arg0) throws ServletException {
}
}
@@ -0,0 +1,33 @@
package com.adc.da.filter;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HttpCacheFilter implements Filter {
private long maxAge = 86400L;
public HttpCacheFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
chain.doFilter(request, new AddExpiresHeaderResponse(response, this.maxAge));
}
public void init(FilterConfig config) throws ServletException {
String maxAgeStr = config.getInitParameter("maxAge");
if (StringUtils.isNotEmpty(maxAgeStr)) {
this.maxAge = Long.valueOf(maxAgeStr);
}
}
}
@@ -0,0 +1,102 @@
package com.adc.da.filter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
public class RequestInfoFilter implements Filter {
private static final Log logger = LogFactory.getLog(RequestInfoFilter.class);
private static final List<String> ignoreList = new ArrayList();
public RequestInfoFilter() {
}
public void destroy() {
}
public void init(FilterConfig filterConfig) throws ServletException {
ignoreList.add("js");
ignoreList.add("css");
ignoreList.add("png");
ignoreList.add("ico");
ignoreList.add("gif");
ignoreList.add("jpg");
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
try {
long startTime = System.currentTimeMillis();
String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
if (!isIgnore(uri)) {
logger.info("==================== RequestInfoFilter Start ====================");
logger.info(request.getMethod() + " : " + uri);
logger.info("session存活时间:" + request.getSession().getMaxInactiveInterval());
this.logHeaders(request);
this.logParams(request);
logger.info(request.getHeader("Authorization"));
chain.doFilter(request, response);
long endTime = System.currentTimeMillis();
logger.info(request.getMethod() + " 耗时:" + (endTime - startTime) + " ms");
logger.info("==================== RequestInfoFilter End ====================");
} else {
chain.doFilter(request, response);
}
} catch (Exception var11) {
logger.error("doFilter error", var11);
}
}
private void logHeaders(HttpServletRequest request) {
Map<String, String> headerMap = new HashMap();
Enumeration headers = request.getHeaderNames();
while(headers.hasMoreElements()) {
String headName = (String)headers.nextElement();
if (headName != null && !"".equals(headName)) {
headerMap.put(headName, request.getHeader(headName));
}
}
headerMap.put("RemoteHost", request.getRemoteHost() + ":" + request.getRemotePort());
logger.info(headerMap);
}
private void logParams(HttpServletRequest request) {
Map<String, String> maps = new HashMap();
Enumeration keys = request.getParameterNames();
while(keys.hasMoreElements()) {
String key = (String)keys.nextElement();
if (StringUtils.isNotEmpty(key)) {
String values = request.getParameter(key);
maps.put(key, values);
}
}
logger.info(maps.toString());
}
private static final boolean isIgnore(String url) {
boolean ignore = false;
int index = url.lastIndexOf(46);
if (index > 0) {
String subFix = url.substring(index + 1, url.length());
if (ignoreList.contains(subFix)) {
ignore = true;
}
}
return ignore;
}
}
@@ -0,0 +1,29 @@
package com.adc.da.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class WebFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(WebFilter.class);
public WebFilter() {
// 不做操作
}
public void init(FilterConfig config) throws ServletException {
// 不做操作
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest)request);
chain.doFilter(xssRequest, response);
}
public void destroy() {
// 不做操作
}
}
@@ -0,0 +1,124 @@
package com.adc.da.filter;
import com.adc.da.xss.SQLFilter;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
private static final Logger logger = LoggerFactory.getLogger(XssHttpServletRequestWrapper.class);
HttpServletRequest orgRequest;
private static final SQLFilter sqlFilter = new SQLFilter();
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
this.orgRequest = request;
}
public ServletInputStream getInputStream() throws IOException {
String type = super.getHeader("Content-Type");
if (StringUtils.indexOfIgnoreCase(type, "application/json") < 0) {
return super.getInputStream();
} else {
String json = IOUtils.toString(super.getInputStream(), "utf-8");
if (StringUtils.isBlank(json)) {
return super.getInputStream();
} else {
json = this.xssSqlEncode(json);
final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
return new ServletInputStream() {
public boolean isFinished() {
return true;
}
public boolean isReady() {
return true;
}
public void setReadListener(ReadListener readListener) {
// 不做操作
}
public int read() throws IOException {
return bis.read();
}
};
}
}
}
public String getParameter(String name) {
String value = super.getParameter(this.xssSqlEncode(name));
if (StringUtils.isNotBlank(value)) {
value = this.xssSqlEncode(value);
}
return value;
}
public String[] getParameterValues(String name) {
String[] parameters = super.getParameterValues(name);
if (parameters != null && parameters.length != 0) {
for(int i = 0; i < parameters.length; ++i) {
parameters[i] = this.xssSqlEncode(parameters[i]);
}
return parameters;
} else {
return null;
}
}
public Map<String, String[]> getParameterMap() {
Map<String, String[]> map = new LinkedHashMap();
Map<String, String[]> parameters = super.getParameterMap();
Iterator i$ = parameters.keySet().iterator();
while(i$.hasNext()) {
String key = (String)i$.next();
String[] values = (String[])parameters.get(key);
for(int i = 0; i < values.length; ++i) {
values[i] = this.xssSqlEncode(values[i]);
}
map.put(key, values);
}
return map;
}
public String getHeader(String name) {
String value = super.getHeader(this.xssSqlEncode(name));
if (StringUtils.isNotBlank(value)) {
value = this.xssSqlEncode(value);
}
return value;
}
private String xssSqlEncode(String input) {
String htmlOutput = XssShieldUtil.stripXss(input);
// SQLFilter var10000 = sqlFilter;
return SQLFilter.sqlInject(htmlOutput);
}
public HttpServletRequest getOrgRequest() {
return this.orgRequest;
}
public static HttpServletRequest getOrgRequest(HttpServletRequest request) {
return request instanceof XssHttpServletRequestWrapper ? ((XssHttpServletRequestWrapper)request).getOrgRequest() : request;
}
}
@@ -0,0 +1,96 @@
package com.adc.da.filter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class XssShieldUtil {
private static final Logger logger = LoggerFactory.getLogger(XssShieldUtil.class);
private static List<Pattern> patterns = null;
private XssShieldUtil(){
super();
}
private static List<Object[]> getXssPatternList()
{
List<Object[]> ret = new ArrayList();
ret.add(new Object[] { "<(no)?script[^>]*>.*?</(no)?script>", Integer.valueOf(2) });
ret.add(new Object[] { "eval\\((.*?)\\)", Integer.valueOf(42) });
ret.add(new Object[] { "expression\\((.*?)\\)", Integer.valueOf(42) });
ret.add(new Object[] { "(javascript:|vbscript:|view-source:)*", Integer.valueOf(2) });
// ret.add(new Object[] { "<(\"[^\"]*\"|'[^']*'|[^'\">])*>", Integer.valueOf(42) });
ret.add(new Object[] { "(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*", Integer.valueOf(42) });
ret.add(new Object[] { "<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+", Integer.valueOf(42) });
return ret;
}
private static List<Pattern> getPatterns()
{
if (patterns == null)
{
List<Pattern> list = new ArrayList();
String regex = null;
Integer flag = null;
int arrLength = 0;
int i;
Iterator localIterator = getXssPatternList().iterator();
while (localIterator.hasNext()){
Object[] arr = (Object[])localIterator.next();
if(arr.length==0){
continue;
}
regex = (String)arr[0];
flag = (Integer)arr[1];
list.add(Pattern.compile(regex, flag.intValue()));
}
/* for (Iterator localIterator = getXssPatternList().iterator(); localIterator.hasNext();i < arrLength) {
Object[] arr = (Object[])localIterator.next();
arrLength = arr.length;
i = 0;
continue;
regex = (String)arr[0];
flag = (Integer)arr[1];
list.add(Pattern.compile(regex, flag.intValue()));
i++;
}*/
patterns = list;
}
return patterns;
}
public static String stripXss(String value)
{
if (StringUtils.isNotBlank(value))
{
Matcher matcher = null;
for (Pattern pattern : getPatterns())
{
matcher = pattern.matcher(value);
if (matcher.find()) {
value = matcher.replaceAll("");
}
}
// value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
String[] pattern = { "%", " select ", " insert ", " delete ", " from ",
"count\\(", "drop table", " update ", " truncate ", "asc\\(",
"mid\\(", "char\\(", "xp_cmdshell", " exec ", " master ",
"netlocalgroup administrators", "net user", " or ", " and " };
for (int i = 0; i < pattern.length; i++) {
value = value.replaceAll(pattern[i],"");
}
}
return value;
}
}
@@ -0,0 +1,31 @@
package com.adc.da.xss;
import com.adc.da.exception.AdcDaBaseException;
import org.apache.commons.lang3.StringUtils;
public class SQLFilter {
public static String sqlInject(String str) {
if (StringUtils.isBlank(str)) {
return null;
} else {
String checkStr= str;
checkStr = StringUtils.replace(checkStr, "\\", "");
checkStr = checkStr.toLowerCase();
String[] keywords = new String[]{"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"};
String[] arr$ = keywords;
int len$ = keywords.length;
for(int i$ = 0; i$ < len$; ++i$) {
String keyword = arr$[i$];
if (checkStr.indexOf(keyword) != -1) {
throw new AdcDaBaseException("包含非法字符");
}
}
return str;
}
}
}
+33
View File
@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
+118
View File
@@ -0,0 +1,118 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
+310
View File
@@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
+182
View File
@@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
+50
View File
@@ -0,0 +1,50 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.adc</groupId>
<artifactId>foton-slrs-system-rest</artifactId>
<version>3.0.0</version>
</parent>
<groupId>com.adc</groupId>
<artifactId>adc-da-jwtLogin</artifactId>
<version>3.1.0</version>
<name>adc-da-jwtLogin</name>
<description>laws system rest JwtLogin</description>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.adc</groupId>
<artifactId>adc-da-sys</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerVersion>${java.version}</compilerVersion>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,213 @@
package com.adc.da.login.rest;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import com.adc.da.login.util.JWTUtil;
import com.adc.da.login.util.UserUtils;
import com.adc.da.login.vo.LoginVO;
import com.adc.da.sys.entity.MenuEO;
import com.adc.da.sys.entity.UserEO;
import com.adc.da.sys.service.IUserEOService;
import com.adc.da.util.Encodes;
import com.adc.da.util.PasswordUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
@Validated
@Controller
@RequestMapping(value = "/auth")
@Api(description = "登录接口")
@Slf4j
public class LoginRestController {
@Autowired
private IUserEOService userService;
/**
* 读取配置文件判断是否需要开启Base64加密,默认值为false
*/
@Value("${isPassEncrypted:false}")
private boolean isPassEncrypted;
/**
* 无缓存,用于校验
*/
private static final String NO_CACHE = "no-cache";
/**
* 登录失败Map字段
*/
private static final String LOGIN_FAIL_MAP = "loginFailMap";
/**
* 验证码
*/
private static final Object VERIFY_CODE = "VerifyCode";
/**
* 10分钟内最大错误次数
*/
@Value("${maxLoginErrorCount:3}")
private int maxLoginErrorCount;
/**
* 读取验证码模式配置,
* 1为不开启,2为开启,3为三次输错用户名或密码才开启,
* 默认为1
* <p>
* 若配置文件缺少该参数,将设置为1
*/
@Value("${verifyCodeMode:1}")
private int verifyCodeMode;
@ApiOperation(value = "登录")
@PostMapping(value = "/login")
@ResponseBody
public ResponseMessage<String> loginWithVerifyCode(HttpServletResponse response, @RequestBody LoginVO loginVO) {
String username = loginVO.getUsername();
String password = loginVO.getPassword();
String key = loginVO.getKey();
if (StringUtils.isBlank(username)) {
return Result.error("r0014", "登录名不能为空");
}
if (StringUtils.isBlank(password)) {
return Result.error("r0016", "密码不能为空");
}
if (StringUtils.isBlank(key)) {
return Result.error("key不能为空");
}
UserEO userEO = userService.getUserByLoginNameNotDeleted(username);
if (null == userEO) {
log.info("用户[{}]身份验证失败", username);
return Result.error("r0011", "您输入的帐号或密码有误");
}
if (PasswordUtils.validatePassword(password, userEO.getPassword())) {
String token = JWTUtil.sign(username, userEO.getPassword(), userEO.getUsid());
response.setHeader("Authorization", token);
response.addHeader("Access-Control-Allow-Headers", "Authorization");
return Result.success(token);
} else {
log.info("用户[{}]密码验证失败", username);
return Result.error("r0011", "您输入的帐号或密码有误");
}
}
@ApiOperation(value = "登录")
@GetMapping(value = "/login")
@ResponseBody
public ResponseMessage<String> loginRest(HttpServletRequest request, HttpServletResponse response,
@RequestParam @NotNull(message = "请输入用户名") String username,
@RequestParam @NotNull(message = "请输入密码") String password,
@RequestParam(value = "isRememberMe", defaultValue = "false") Boolean isRememberMe, String verifyCode) {
UserEO userEO = userService.getUserByLoginNameNotDeleted(username);
if (null == userEO) {
log.info("用户[{}]身份验证失败", username);
return Result.error("r0011", "您输入的帐号或密码有误");
}
if(userEO.getDisableFlag()==1){
log.info("用户[{}]身份验证失败", username);
return Result.error("r0011", "您输入的帐号已禁用");
}
if (PasswordUtils.validatePassword(password, userEO.getPassword())) {
String token = JWTUtil.sign(username, userEO.getUsid(),userEO.getPassword());
response.setHeader("Authorization", token);
response.addHeader("Access-Control-Allow-Headers", "Authorization");
return Result.success(token);
} else {
log.info("用户[{}]密码验证失败", username);
return Result.error("r0011", "您输入的帐号或密码有误");
}
}
/**
* 退出登录,客户端把Token丢弃就可以
*/
@ApiOperation(value = "退出登录")
@GetMapping("/logout")
@ResponseBody
public ResponseMessage logout(HttpServletResponse response,String ticket) {
UserUtils.logout();
return Result.success();
}
@ApiOperation(value = "未授权访问")
@RequestMapping(path = "/401")
@ResponseBody
public ResponseMessage unauthorized() {
return Result.error("401", "Unauthorized");
}
/**
* 登录成功之后获取当前登录用户信息的接口
*/
@ApiOperation(value = "获取登录用户信息")
@GetMapping("/userInfo")
@ResponseBody
public ResponseMessage<UserEO> userInfo(HttpServletResponse response) throws NumberFormatException {
UserEO user = UserUtils.getUser();
if (user != null) {
return Result.success(user);
}
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return Result.error();
}
/**
* 获取用户菜单,已用菜单管理实现
*/
@ApiOperation(value = "获取登录用户菜单权限")
@GetMapping("/userMenu")
@ResponseBody
public ResponseMessage<List<MenuEO>> userMenu(){
return Result.success(UserUtils.getMenuList());
}
/**
* 修改当前登录用户密码
*/
@ApiOperation(value = "修改密码")
@PutMapping("/updatePassword")
@ResponseBody
public ResponseMessage updatePassword(@NotNull(message = "请输入旧密码") @RequestParam String oldPassword,
@NotNull(message = "请输入新密码") @RequestParam String newPassword) {
// 前台如果base64传输密文,则需要解码
if (isPassEncrypted) {
oldPassword = new String(Encodes.decodeBase64(oldPassword), StandardCharsets.UTF_8);
newPassword = new String(Encodes.decodeBase64(newPassword), StandardCharsets.UTF_8);
}
if (!newPassword.matches("^(?![0-9]*$)[a-zA-Z0-9]{6,10}$")) {
return Result.error("r0018", "新密码必须6-10位且不能纯数字");
}
userService.updatePassword(UserUtils.getUserId(), oldPassword, newPassword);
return Result.success();
}
}
@@ -0,0 +1,158 @@
package com.adc.da.login.security;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* JWT过滤器,针对请求进行拦截过滤
*/
@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {
//10分钟后刷新token
private static final int tokenRefreshInterval = 60 * 10;
/**
* 这里我们详细说明下为什么最终返回的都是true,即允许访问
*例如我们提供一个地址 GET /article
*登入用户和游客看到的内容是不同的
*如果在这里返回了false,请求会被直接拦截,用户看不到任何东西
*所以我们在这里返回trueController中可以通过 subject.isAuthenticated() 来判断用户是否登入
*如果有些资源只有登入用户才能访问,我们只需要在方法上面加上 @RequiresAuthentication 注解即可
*但是这样做有一个缺点,就是不能够对GET,POST等请求进行分别过滤鉴权(因为我们重写了官方的方法),但实际上对应用影响不大
*/
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
if (isLoginAttempt(request, response)) {
try {
return executeLogin(request, response);
} catch (Exception e) {
responseError(request, response);
return false;
}
}else{
return false;
}
}
/**
* 检测header里面是否包含Authorization字段
* @param request
* @param response
* @return
*/
@Override
protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
HttpServletRequest req = (HttpServletRequest) request;
String authorization = req.getHeader("Authorization");
log.debug("判断用户是否想要登录:{}",authorization);
return authorization != null;
}
/**
* 认证失败后调用的方法
* @param request
* @param response
* @return
* @throws Exception
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
this.responseError(request,response);
return false;
}
@Override
protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception{
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String authorization = httpServletRequest.getHeader("Authorization");
log.debug("用户开始认证x{}",authorization);
JWTToken token = new JWTToken(authorization);
// 提交给realm进行登入,如果错误他会抛出异常并被捕获
getSubject(request, response).login(token);
// 如果没有抛出异常则代表登入成功,返回true
return true;
}
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
if(token instanceof JWTToken){
JWTToken jwtToken= (JWTToken) token;
//TODO 此处需要设置token自动续期功能
}
return true;
}
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
httpServletResponse.addHeader("Access-Control-Allow-Headers", "Authorization");
// 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态
if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
httpServletResponse.setStatus(HttpStatus.OK.value());
return false;
}
return super.preHandle(request, response);
}
/**
* 将非法请求跳转到 /401
*/
private void responseError(ServletRequest req, ServletResponse resp) {
try {
HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
if(httpServletResponse.isCommitted()){
return;
}
//此处需要返回统一的错误对象 以便应对统一的异常处理
JSONObject result=new JSONObject();
result.put("respCode","A404");
result.put("ok",false);
result.put("message","认证失败");
result.put("data",null);
httpServletResponse.setHeader("Content-Type", "application/json");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
// response.setHeader("Content-type", "application/json;charset=UTF-8");
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.setCharacterEncoding("UTF-8");
PrintWriter printWriter = httpServletResponse.getWriter();
printWriter.append(result.toString(SerializerFeature.WriteMapNullValue));
printWriter.flush();
// httpServletResponse.sendRedirect("/401");
} catch (IOException e) {
log.error(e.getMessage());
}
}
private boolean shouldTokenRefresh(JWTToken jwtToken) {
// LocalDateTime issueTime = LocalDateTime.ofInstant(issueAt.toInstant(), ZoneId.systemDefault());
// return LocalDateTime.now().minusSeconds(tokenRefreshInterval).isAfter(issueTime);
return true;
}
}
@@ -0,0 +1,145 @@
package com.adc.da.login.security;
import com.adc.da.login.util.JWTUtil;
import com.adc.da.login.util.UserUtils;
import com.adc.da.sys.entity.UserEO;
import com.adc.da.sys.service.IUserEOService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.*;
//@Service
public class JWTRealm extends AuthorizingRealm {
private static final Logger logger = LoggerFactory.getLogger(JWTRealm.class);
private IUserEOService userEOService;
/**
* JWT签名密钥
*/
public static final String SECRET = "AyX3TWpHIkPfE9rqaDiYV416d0nguURLQ8vhNzBlK7MGcOJjmoZ2w5stSeCFxb16";
@Autowired
public void setUserEOService(IUserEOService userEOService) {
this.userEOService = userEOService;
}
/**
* 必须重写此方法,不然Shiro会报错
*/
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JWTToken;
}
/**
* 此方法调用hasRole,hasPermission的时候才会进行回调.
* <p>
* 权限信息.(授权):
* 1、如果用户正常退出,缓存自动清空;
* 2、如果用户非正常退出,缓存自动清空;
* 3、如果我们修改了用户的权限,而用户不退出系统,修改的权限无法立即生效。
* (需要手动编程进行实现;放在service进行调用)
* 在权限修改后调用realm中的方法,realm已经由spring管理,所以从spring中获取realm实例,调用clearCached方法;
* :Authorization 是授权访问控制,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等。
*
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = JWTUtil.getUsername(principalCollection.toString());
if (username == null) {
return null;
}
UserEO user = userEOService.getUserByLoginNameNotDeleted(username);
if (user != null) {
try {
return UserUtils.getAuthInfo();
} catch (NumberFormatException e) {
logger.error("AuthorizationInfo NumberFormatException", e);
} catch (Exception e) {
logger.error("AuthorizationInfo Exception", e);
}
}
return null;
}
/**
* 认证信息(身份验证)
* Authentication 是用来验证用户身份
*
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String token = (String) authenticationToken.getCredentials();
// 解密获得username,用于和数据库进行对比
String username = JWTUtil.getUsername(token);
if (username == null) {
throw new AuthenticationException("token 无效!");
}
UserEO user = userEOService.getUserByLoginNameNotDeleted(username);
if (user == null) {
throw new AuthenticationException("用户"+username+"不存在") ;
}
if (!JWTUtil.verify(token, username,user.getUsid(),user.getPassword())) {
throw new AuthenticationException("账户密码错误!");
}
return new SimpleAuthenticationInfo(token, token, "jwtRealm");
}
/**
* 授权用户信息
*/
public static class Principal implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String loginName;
private transient Map<String, Object> cacheMap;
public Principal(UserEO user) {
this.id = user.getUsid() == null ? "" : String.valueOf(user.getUsid());
this.loginName = user.getAccount();
}
public String getId() {
return id;
}
public String getLoginName() {
return loginName;
}
public Map<String, Object> getCacheMap() {
if (cacheMap == null) {
cacheMap = new HashMap<>();
}
return cacheMap;
}
}
}
@@ -0,0 +1,32 @@
package com.adc.da.login.security;
import org.apache.shiro.authc.AuthenticationToken;
/**
* JWT认证token实体对象
*/
public class JWTToken implements AuthenticationToken {
private static final long serialVersionUID = 613047528940906064L;
// 秘钥
private String token;
public JWTToken(String token) {
this.token = token;
}
@Override
public Object getPrincipal() {
return getToken();
}
@Override
public Object getCredentials() {
return getToken();
}
public String getToken() {
return token;
}
}
@@ -0,0 +1,4 @@
package com.adc.da.login;
public class test {
}
@@ -0,0 +1,84 @@
package com.adc.da.login.util;
import com.adc.da.util.SpringContextHolder;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
* Cache工具类
*/
public class CacheUtils {
private CacheUtils() {
super();
}
private static CacheManager cacheManager = (CacheManager) SpringContextHolder.getBean("ehCacheManagerFactoryBean");
private static final String SYS_CACHE = "sysCache";
private static final String ERROR_CACHE = "errorCache";
public static Object get(String key) {
return get(SYS_CACHE, key);
}
public static void put(String key, Object value) {
put(SYS_CACHE, key, value);
}
public static void remove(String key) {
remove(SYS_CACHE, key);
}
//配合main模块下resource/cache/ehcache-local.xml
//<cache name="errorCache" maxElementsInMemory="100" timeToIdleSeconds="180" timeToLiveSeconds="300" eternal="false" overflowToDisk="true"/>
public static Object getErrorCache(String key) {
return get(ERROR_CACHE, key);
}
public static void putErrorCache(String key, Object value) {
put(ERROR_CACHE, key, value);
}
public static void removeErrorCache(String key) {
remove(ERROR_CACHE, key);
}
public static Object get(String cacheName, String key) {
Element element = getCache(cacheName).get(key);
return element == null ? null : element.getObjectValue();
}
public static void put(String cacheName, String key, Object value) {
Element element = new Element(key, value);
getCache(cacheName).put(element);
}
public static void remove(String cacheName, String key) {
getCache(cacheName).remove(key);
}
/**
* 获得一个Cache,没有则创建一个。
* @param cacheName
* @return
*/
private static Cache getCache(String cacheName) {
Cache cache = cacheManager.getCache(cacheName);
if (cache == null) {
cacheManager.addCache(cacheName);
cache = cacheManager.getCache(cacheName);
cache.getCacheConfiguration().setEternal(true);
}
return cache;
}
public static CacheManager getCacheManager() {
return cacheManager;
}
}
@@ -0,0 +1,79 @@
package com.adc.da.login.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class JWTUtil {
// 设置过期时间,默认为2小时
private static long EXPIRE_TIME = 120;
@Value("${EXPIRE_TIME}")
public void setEnv(long expireTime) {
setExpireTime(expireTime);
}
public static synchronized void setExpireTime(long expireTime) {
EXPIRE_TIME = expireTime;
}
public static boolean verify(String token, String username,String userId, String secret) {
try {
Algorithm algorithm = Algorithm.HMAC512(secret);
JWTVerifier verifier = JWT.require(algorithm)
.withClaim("username", username).withClaim("userid", userId)
.build();
verifier.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
/**
* @Title: getUsername
* @Description: 获取token中的信息无需secret解密也能获得
* @Author 刘仁
* @DateTime 2019年4月1日 下午4:42:39
* @param token
* @return
*/
public static String getUsername(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("username").asString();
} catch (JWTDecodeException e) {
return null;
}
}
public static String getUserId(String token){
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("userid").asString();
} catch (JWTDecodeException e) {
return null;
}
}
public static String sign(String username,String userId, String secret) {
Date date = Date
.from(LocalDateTime.now().plusMinutes(EXPIRE_TIME).atZone(ZoneId.systemDefault()).toInstant());
Algorithm algorithm = Algorithm.HMAC512(secret);
String sign = JWT.create()
.withClaim("username", username).withClaim("userid", userId)
.withExpiresAt(date)
.sign(algorithm);
// 附带username信息
return sign;
}
}
@@ -0,0 +1,188 @@
package com.adc.da.login.util;
import com.adc.da.login.security.JWTRealm;
import com.adc.da.login.security.JWTRealm.Principal;
import com.adc.da.sys.entity.MenuEO;
import com.adc.da.sys.entity.UserEO;
import com.adc.da.sys.service.IMenuEOService;
import com.adc.da.sys.service.IUserEOService;
import com.adc.da.util.SpringContextHolder;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
public class UserUtils {
private UserUtils() {
super();
}
private static Logger logger = LoggerFactory.getLogger(UserUtils.class);
/**
* 当前登陆用户
*/
public static final String CURRENT_USER = "currentUser";
/**
* 菜单信息
*/
public static final String CACHE_MENU_LIST = "menuList";
/**
* @see IUserEOService
*/
private static IUserEOService userService = SpringContextHolder.getBean(IUserEOService.class);
/**
* @see IMenuEOService
*/
private static IMenuEOService menuService = SpringContextHolder.getBean(IMenuEOService.class);
/**
* 退出
*/
public static void logout() {
try {
SecurityUtils.getSubject().logout();
} catch (UnavailableSecurityManagerException e) {
logger.error(e.getMessage(),e);
} catch (InvalidSessionException e) {
logger.error(e.getMessage(),e);
}
}
/**
* 获取当前登录用户名
*/
public static String getUserName() {
JWTRealm.Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
if (principal != null) {
return principal.getLoginName();
}
return null;
}
/**
* 获取当前登陆用户ID
* @throws Exception
*/
public static String getUserId() {
UserEO userEO = getUser();
if (userEO != null) {
return userEO.getUsid();
}
return null;
}
/**
* 获取当前登录用户信息
*/
public static UserEO getUser() {
UserEO user = (UserEO) CacheUtils.getCache(CURRENT_USER);
if (user == null) {
String userName = getUserName();
if (StringUtils.isNotEmpty(userName)) {
UserEO userInDb = userService.getUserByLoginNameNotDeleted(userName);
user = ObjectUtils.clone(userInDb);
user.setPassword(null);
CacheUtils.putCache(CURRENT_USER, user);
}
}
return user;
}
/**
* 获取当前登录用户菜单列表
*/
public static List<MenuEO> getMenuList() {
List<MenuEO> menuList = (List<MenuEO>) CacheUtils.getCache(CACHE_MENU_LIST);
if (menuList == null) {
UserEO user = getUser();
if (user != null) {
if (isAdmin(user)) {
menuList = menuService.findAll();
} else {
menuList = menuService.listMenuEOByUserId(String.valueOf(user.getUsid()));
}
CacheUtils.putCache(CACHE_MENU_LIST, menuList);
}
}
return menuList;
}
/**
* 判断用户是否是超级管理员
*
* @param userVo 用户信息
* @return 返回判断
*/
public static boolean isAdmin(UserEO userVo) {
return userVo != null && userVo.getUsid().equals("1");
}
/**
* 获取用户菜单权限信息
*/
public static SimpleAuthorizationInfo getAuthInfo() {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
List<MenuEO> list = UserUtils.getMenuList();
for (MenuEO menu : list) {
if (StringUtils.isNotBlank(menu.getPermission())) {
// 添加基于Permission的权限信息
for (String permission : StringUtils.split(menu.getPermission(), ",")) {
info.addStringPermission(permission);
}
}
}
return info;
}
public static void flush() {
CacheUtils.removeCache(CURRENT_USER);
}
private static final class CacheUtils {
public static Object getCache(String key) {
return getCache(key, null);
}
public static Object getCache(String key, Object defaultValue) {
Object obj = getCacheMap().get(key);
return obj == null ? defaultValue : obj;
}
public static void putCache(String key, Object value) {
getCacheMap().put(key, value);
}
public static void removeCache(String key) {
getCacheMap().remove(key);
}
public static Map<String, Object> getCacheMap() {
Map<String, Object> map = Maps.newHashMap();
try {
Subject subject = SecurityUtils.getSubject();
JWTRealm.Principal principal = (JWTRealm.Principal) subject.getPrincipal();
return principal != null ? principal.getCacheMap() : map;
} catch (UnavailableSecurityManagerException e) {
logger.error(e.getMessage(),e);
} catch (InvalidSessionException e) {
logger.error(e.getMessage(),e);
}
return map;
}
}
}
@@ -0,0 +1,64 @@
package com.adc.da.login.vo;
import com.adc.da.base.entity.BaseEntity;
/**
* <b>功能:</b>LoginVO<br>
* <b>作者:</b>Wei Jinjin<br>
* <b>日期:</b> 2019-10-09 <br>
* <b>版权所有:<b>版权归天津卡达克数据技术中心所有。<br>
*/
public class LoginVO extends BaseEntity {
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 验证码
*/
private String verifyCode;
/**
* 服务端存储验证码的key
*/
private String key;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getVerifyCode() {
return verifyCode;
}
public void setVerifyCode(String verifyCode) {
this.verifyCode = verifyCode;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
+33
View File
@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
+118
View File
@@ -0,0 +1,118 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
+310
View File
@@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
+182
View File
@@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
+63
View File
@@ -0,0 +1,63 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.adc</groupId>
<artifactId>foton-slrs-system-rest</artifactId>
<version>3.0.0</version>
</parent>
<groupId>com.adc</groupId>
<artifactId>adc-da-main</artifactId>
<name>adc-da-main</name>
<description>laws system rest main</description>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.adc</groupId>
<artifactId>adc-da-sys</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.adc</groupId>
<artifactId>adc-da-base</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.adc</groupId>
<artifactId>adc-da-jwtLogin</artifactId>
<version>3.1.0</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.adc</groupId>-->
<!-- <artifactId>adc-da-gen</artifactId>-->
<!-- <version>2.3.2-SNAPSHOT</version>-->
<!-- </dependency>-->
</dependencies>
<!-- Profiles for different environment -->
<profiles>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,16 @@
package com.adc.da;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class AdcDaApplication {
public static void main(String[] args) {
SpringApplication.run(AdcDaApplication.class, args);
}
}
@@ -0,0 +1,16 @@
package com.adc.da;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* Springboot打war包的启动口
*/
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
// 注意这里要指向原先用main方法执行的Application启动类
return builder.sources(AdcDaApplication.class);
}
}
@@ -0,0 +1,38 @@
package com.adc.da.main.advice;
import com.adc.da.exception.AdcDaBaseException;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.ResponseMessageCodeEnum;
import com.adc.da.http.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Slf4j
@ControllerAdvice
@Order(value=4)
public class AdcDaBaseExceptionAdvice {
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(AdcDaBaseException.class)
@ResponseBody
public ResponseMessage handlerAdcDaBaseException(AdcDaBaseException exception) {
log.warn(exception.getMessage(), exception);
return Result.error(exception.getErrorCode(), exception.getMessage());
}
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseMessage handlerAdcDaBaseException(Exception exception) {
log.error(exception.getMessage(), exception);
// TODO 在数据库中记录程序异常,这个地方的异常是未处理的异常,需要管理员查看并进行处理以防重复出现
return Result.error(ResponseMessageCodeEnum.ERROR.getCode(), "程序异常,请重试。如果重复出现请联系管理员处理!");
}
}
@@ -0,0 +1,41 @@
package com.adc.da.main.advice;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Slf4j
@ControllerAdvice
@Order(value=2)
public class ShiroExceptionAdvice {
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler({AuthenticationException.class, UnknownAccountException.class,
UnauthenticatedException.class, IncorrectCredentialsException.class})
@ResponseBody
public ResponseMessage unauthorized(Exception exception) {
log.warn(exception.getMessage(), exception);
log.info("catch UnknownAccountException");
return Result.error("A404", "无权访问");
}
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(UnauthorizedException.class)
@ResponseBody
public ResponseMessage unauthorized1(UnauthorizedException exception) {
log.warn(exception.getMessage(), exception);
return Result.error("A404","无权访问");
}
}
@@ -0,0 +1,44 @@
package com.adc.da.main.config;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* shiro 自定义URL规则设置
*/
public class DefinitionUrlConfig {
/**
* 匿名用户,无需登录
*/
private static final String ANON = "anon";
// 拦截器
//rest:比如/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[usermethod] ,其中method为postgetdelete等。
//port:比如/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal//serverName8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString是你访问的url里的?后面的参数。
//perms:比如/admins/user/**=perms[useradd*],perms参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,比如/admins/user/**=perms["useradd*,usermodify*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。
//roles:比如/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,比如/admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。//要实现or的效果看http://zgzty.blog.163.com/blog/static/83831226201302983358670/
//anon:比如/admins/**=anon 没有参数,表示可以匿名使用。
//authc:比如/admins/user/**=authc表示需要认证才能使用,没有参数
//authcBasic:比如/admins/user/**=authcBasic没有参数表示httpBasic认证
//ssl:比如/admins/user/**=ssl没有参数,表示安全的url请求,协议为https
//user:比如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查
public static Map<String,String> definitionUrlOptions(){
Map<String, String> filterRuleMap = new LinkedHashMap<>();
//TODO 此处设置URL过滤规则 默认是全部请求进行拦截,此处设置为不拦截的URL地址
filterRuleMap.put("/api/auth/login",ANON);//登录接口
// swagger接口文档
filterRuleMap.put("/v2/api-docs", "anon");
filterRuleMap.put("/webjars/**", "anon");
filterRuleMap.put("/swagger-resources/**", "anon");
filterRuleMap.put("/swagger-ui.html", "anon");
filterRuleMap.put("/doc.html", "anon");
return filterRuleMap;
}
}
@@ -0,0 +1,22 @@
package com.adc.da.main.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Mybatis Plus 配置
*/
@EnableTransactionManagement
@Configuration
@MapperScan("com.adc.da.**.dao")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
@@ -0,0 +1,50 @@
package com.adc.da.main.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
/**
* restTemplate设置
*/
@Configuration
public class RestTemplateConfig {
private static final Logger logger = LoggerFactory.getLogger(RestTemplateConfig.class);
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
RestTemplate restTemplate = new RestTemplate(factory);
// 使用 utf-8 编码集的 conver 替换默认的 conver(默认的 string conver 的编码集为"ISO-8859-1"
List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
while (iterator.hasNext()) {
HttpMessageConverter<?> converter = iterator.next();
if (converter instanceof StringHttpMessageConverter) {
iterator.remove();
}
}
messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(50000);//单位为ms
factory.setConnectTimeout(50000);//单位为ms
return factory;
}
}
@@ -0,0 +1,151 @@
package com.adc.da.main.config;
import com.adc.da.login.security.JWTFilter;
import com.adc.da.login.security.JWTRealm;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;
@Configuration
@Order(value=1)
public class ShiroConfig {
private static final String JWT_FILTER_NAME = "jwt";
private static final String URL_SUFFIX="/api";
/**
* 自定义realm,实现登录授权流程
* @return
*/
@Bean(name="jwtRealm")
public JWTRealm jwtRealm() {
return new JWTRealm();
}
/**
* 配置securityManager 管理subject(默认),并把自定义realm交由manager
*/
@Bean
public DefaultSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 设置realm.
securityManager.setRealm(jwtRealm());
//注入缓存管理器
securityManager.setCacheManager(ehCacheManager());
/*
* 关闭shiro自带的session,详情见文档
* http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29
*/
DefaultSubjectDAO defaultSubjectDAO = new DefaultSubjectDAO();
DefaultSessionStorageEvaluator storageEvaluator = new DefaultSessionStorageEvaluator();
storageEvaluator.setSessionStorageEnabled(false);
defaultSubjectDAO.setSessionStorageEvaluator(storageEvaluator);
securityManager.setSubjectDAO(defaultSubjectDAO);
return securityManager;
}
/**
* 拦截链
*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultSecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setFilters(filterMap());
shiroFilterFactoryBean.setFilterChainDefinitionMap(definitionMap());
return shiroFilterFactoryBean;
}
/**
* 自定义拦截器,处理所有请求
*/
private Map<String, Filter> filterMap() {
Map<String, Filter> filterMap = new HashMap<>();
filterMap.put(JWT_FILTER_NAME, new JWTFilter());
return filterMap;
}
/**
* url拦截规则
*/
private Map<String, String> definitionMap() {
// 拦截器
//rest:比如/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[usermethod] ,其中method为postgetdelete等。
//port:比如/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal//serverName8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString是你访问的url里的?后面的参数。
//perms:比如/admins/user/**=perms[useradd*],perms参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,比如/admins/user/**=perms["useradd*,usermodify*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。
//roles:比如/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,比如/admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。//要实现or的效果看http://zgzty.blog.163.com/blog/static/83831226201302983358670/
//anon:比如/admins/**=anon 没有参数,表示可以匿名使用。
//authc:比如/admins/user/**=authc表示需要认证才能使用,没有参数
//authcBasic:比如/admins/user/**=authcBasic没有参数表示httpBasic认证
//ssl:比如/admins/user/**=ssl没有参数,表示安全的url请求,协议为https
//user:比如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查
Map<String, String> definitionMap = DefinitionUrlConfig.definitionUrlOptions();
definitionMap.put(URL_SUFFIX+"/**", JWT_FILTER_NAME);
return definitionMap;
}
/* *//**
* 开启注解
*//*
@Bean
@DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
// 强制使用cglib代理,防止和aop冲突
defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
return defaultAdvisorAutoProxyCreator;
}
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}*/
/**
* 开启shiro aop注解支持. 使用代理方式; 所以需要开启代码支持;
*
* @param securityManager 安全管理器
* @return 授权Advisor
*/
@Bean("authorizationAttributeSourceAdvisor")
public AuthorizationAttributeSourceAdvisor advisor(DefaultSecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
/**
* shiro缓存管理器;
* 需要注入对应的其它的实体类中:
* 1、安全管理器:securityManager
* 可见securityManager是整个shiro的核心;
*
* @return
*/
@Bean
public EhCacheManager ehCacheManager() {
EhCacheManager cacheManager = new EhCacheManager();
cacheManager.setCacheManagerConfigFile("classpath:cache/ehcache.xml");
return cacheManager;
}
}
@@ -0,0 +1,92 @@
package com.adc.da.main.config;
import com.adc.da.login.security.JWTRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.ClassPathResource;
//@Configuration
public class ShiroConfiguration {
@Bean(name = "ehCacheManagerFactoryBean")
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
ClassPathResource classPathResource = new ClassPathResource("cache/ehcache-local.xml");
ehCacheManagerFactoryBean.setConfigLocation(classPathResource);
return ehCacheManagerFactoryBean;
}
@Bean(name = "shiroCacheManager")
@DependsOn({ "ehCacheManagerFactoryBean" })
public EhCacheManager shiroCacheManager() {
EhCacheManager ehCacheManager = new EhCacheManager();
ehCacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject());
return ehCacheManager;
}
@Bean
@DependsOn({ "lifecycleBeanPostProcessor" })
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
proxyCreator.setProxyTargetClass(true);
return proxyCreator;
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean(name = "securityManager")
public SecurityManager securityManager() {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(jwtRealm());
// 关闭shiro自带的session
DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
defaultWebSecurityManager.setSubjectDAO(subjectDAO);
// 自定义缓存管理器
defaultWebSecurityManager.setCacheManager(shiroCacheManager());
SecurityUtils.setSecurityManager(defaultWebSecurityManager);
return defaultWebSecurityManager;
}
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");// 散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(2);// 散列的次数,比如散列两次,相当于
// md5(md5(""));
return hashedCredentialsMatcher;
}
@Bean
public JWTRealm jwtRealm() {
JWTRealm jwtRealm = new JWTRealm();
return jwtRealm;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager());
return advisor;
}
}
@@ -0,0 +1,67 @@
package com.adc.da.main.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/**
* swagger UI 配置we年
*/
@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {
@Bean
public Docket createRestApiByDefault() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
tokenPar.name("Authorization")
.description("令牌")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(true)
.build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.adc.da"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars).groupName("默认");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("FOTON-SLRS-SYSTEM-REST APIs")
.description("标准法规1.0")
.termsOfServiceUrl("http://localhost:8888/")
.contact("developer@mail.com")
.version("1.0.0")
.build();
}
}
@@ -0,0 +1,105 @@
package com.adc.da.main.config;
import com.adc.da.filter.*;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* Web配置,用于注入过滤器,拦截器等
*/
@Configuration
@Order(value =3)
public class WebConfig {
/**
* xss过滤器(高标准)
*/
@Bean
public FilterRegistrationBean xssFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
// registration.setFilter(new XssFilter());
registration.setFilter(new WebFilter());
registration.addUrlPatterns("/*");
registration.setName("xssFilter");
registration.setOrder(10);
return registration;
}
/**
* xss过滤器(低标准)
*/
// @Bean
// public FilterRegistrationBean xssShieldFilter() {
// FilterRegistrationBean registration = new FilterRegistrationBean();
// registration.setFilter(new XssShieldFilter());
// registration.addUrlPatterns("/*");
// registration.setName("xssShieldFilter");
// registration.setOrder(10);
// return registration;
// }
@Bean
public FilterRegistrationBean csrfFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new CsrfFilter());
registration.addUrlPatterns("/*");
registration.setName("csrfFilter");
registration.setOrder(9);
return registration;
}
@Bean
public FilterRegistrationBean requestInfoFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new RequestInfoFilter());
registration.addUrlPatterns("/*");
registration.setName("RequestInfoFilter");
registration.setOrder(8);
return registration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public FilterRegistrationBean httpCacheFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new HttpCacheFilter());
registration.addUrlPatterns("/*");
registration.setName("httpCacheFilter");
registration.addInitParameter("maxAge", String.valueOf(60 * 60 * 24 * 7));
registration.setOrder(6);
return registration;
}
/**
* 防伪造jsessionid
*/
@Bean
public FilterRegistrationBean fakeJSessionIdFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new FakeJSessionIdFilter());
registration.addUrlPatterns("/*");
registration.setName("fakeJSessionIdFilter");
registration.setOrder(5);
return registration;
}
}
@@ -0,0 +1,25 @@
package com.adc.da.main.filter;
import cn.hutool.json.JSONUtil;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class AuthFormAuthenticationFilter extends FormAuthenticationFilter {
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setStatus(200);
httpServletResponse.setContentType("application/json;charset=utf-8");
PrintWriter out = httpServletResponse.getWriter();
ResponseMessage responseMessage = Result.error("A404", "无权访问");
out.print(JSONUtil.toJsonStr(responseMessage));
return false;
}
}
@@ -0,0 +1,147 @@
package com.adc.da.main.generate;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CodeGen {
private static final String PACKAGE_PATH="/adc-da-sys/src/main";
private static final String AUTHOR="91isoft";
private static final String DB_IP="192.168.10.140:1521:orcl";
private static final String DB_USER="GSAR_TEST";
private static final String DB_PWD="1q2w3e4r";
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + "");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + PACKAGE_PATH+"/java");
gc.setAuthor(AUTHOR);
gc.setOpen(false);
gc.setSwagger2(true); //实体属性 Swagger2 注解
gc.setMapperName("%sDao");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:oracle:thin:@"+DB_IP);
// dsc.setSchemaName("public");
dsc.setDriverName("oracle.jdbc.OracleDriver");
dsc.setUsername(DB_USER);
dsc.setPassword(DB_PWD);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setMapper("dao");
pc.setParent("com.adc.da");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath +PACKAGE_PATH+ "/resources/mybatis/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
templateConfig.setController("templates/controller.java");
templateConfig.setMapper("templates/mapper.java");
templateConfig.setEntity("templates/entity.java");
templateConfig.setService("templates/service.java");
templateConfig.setServiceImpl("templates/serviceImpl.java");
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.adc.da.base.entity.BaseEntity");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
strategy.setSuperControllerClass("com.adc.da.base.web.BaseController");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
@@ -0,0 +1,15 @@
package com.adc.da.main.generate;
//import com.codemagic.DbCodeGenerateFactory;
public class CodeUtil {
public CodeUtil() {}
public static void main(String[] args) {
String entityPackage="sys";
// DbCodeGenerateFactory.codeGenerate("ECP_CHANGE_HIS_PLAN", entityPackage);
}
}
@@ -0,0 +1,44 @@
# dev config
#=============================================
# 数据库配置
#=============================================
spring.datasource.driverClassName = oracle.jdbc.OracleDriver
spring.datasource.url = jdbc:oracle:thin:@//192.168.10.140:1521/orcl
spring.datasource.username = LAWSDB
spring.datasource.password = 1q2w3e4r
#==============================================
# 应用设置
spring.application.name=gsar
application.code=20200101
application.center=1
#==============================================
#==============================================
# 邮箱配置
#==============================================
mail.state=false
spring.mail.host=outlook.geely.com
spring.mail.protocol=smtp
spring.mail.username=e-shiwei@geely.com
spring.mail.password=YtfaaJauPjq21
spring.mail.properties.smtp.auth=true
spring.mail.properties.smtp.starttls.enable=false
spring.mail.properties.smtp.starttls.required=false
spring.mail.properties.mail.smtp.ssl.enable=false
spring.mail.port=587
# ==============================================
# rabbitMQ
# ==============================================
spring.rabbitmq.host=rabbitmq-cluster-01.vs.test.geely.svc
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=uat_pcms
spring.rabbitmq.username=uat_pcms
spring.rabbitmq.password=VxsBLL5bJruwzXfS
# spring.rabbitmq.publisher-confirms=true
# ==============================================
# 文档存储路径指向
# ==============================================
file.path=/usr/laws/file/
@@ -0,0 +1,38 @@
#prod config
#=============================================
# 数据库配置
#=============================================
spring.datasource.driverClassName = oracle.jdbc.OracleDriver
spring.datasource.url = jdbc:oracle:thin:@//10.190.228.33:1521/geely
spring.datasource.username = scyzx_uat
spring.datasource.password = b#Lf5z0^QrF4J3Km
#==============================================
# 邮箱配置
#==============================================
mail.state=false
spring.mail.host=outlook.geely.com
spring.mail.protocol=smtp
spring.mail.username=e-shiwei@geely.com
spring.mail.password=YtfaaJauPjq21
spring.mail.properties.smtp.auth=true
spring.mail.properties.smtp.starttls.enable=false
spring.mail.properties.smtp.starttls.required=false
spring.mail.properties.mail.smtp.ssl.enable=false
spring.mail.port=587
# ==============================================
# rabbitMQ
# ==============================================
spring.rabbitmq.host=rabbitmq-cluster-01.vs.test.geely.svc
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=uat_pcms
spring.rabbitmq.username=uat_pcms
spring.rabbitmq.password=VxsBLL5bJruwzXfS
# spring.rabbitmq.publisher-confirms=true
# ==============================================
# 文档存储路径指向
# ==============================================
file.path=/usr/laws/file/
@@ -0,0 +1,38 @@
# test config
#=============================================
# 数据库配置
#=============================================
spring.datasource.driverClassName = oracle.jdbc.OracleDriver
spring.datasource.url = jdbc:oracle:thin:@//10.190.228.33:1521/geely
spring.datasource.username = scyzx_uat
spring.datasource.password = b#Lf5z0^QrF4J3Km
#==============================================
# 邮箱配置
#==============================================
mail.state=false
spring.mail.host=outlook.geely.com
spring.mail.protocol=smtp
spring.mail.username=e-shiwei@geely.com
spring.mail.password=YtfaaJauPjq21
spring.mail.properties.smtp.auth=true
spring.mail.properties.smtp.starttls.enable=false
spring.mail.properties.smtp.starttls.required=false
spring.mail.properties.mail.smtp.ssl.enable=false
spring.mail.port=587
# ==============================================
# rabbitMQ
# ==============================================
spring.rabbitmq.host=rabbitmq-cluster-01.vs.test.geely.svc
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=uat_pcms
spring.rabbitmq.username=uat_pcms
spring.rabbitmq.password=VxsBLL5bJruwzXfS
# spring.rabbitmq.publisher-confirms=true
# ==============================================
# 文档存储路径指向
# ==============================================
file.path=/usr/laws/file/
@@ -0,0 +1,101 @@
##############################################
# 项目启动模式
##############################################
spring.profiles.active=dev
##############################################
#公共配置信息
##############################################
server.compression.enabled=true
server.compression.mime-types=application/json,application/xml,text/html,text/plain,text/css,application/x-javascript
# 端口号设置
server.port=9999
#主服务session超时
server.servlet.session.timeout =600
# http-only
server.session.cookie.http-only=true
spring.mvc.async.request-timeout=20000
# file模块上传文件大小限制
spring.http.multipart.max-request-size=100MB
spring.http.multipart.max-file-size=100MB
#显示sql
logging.level.com.adc=DEBUG
logging.level.org.springframework=info
# 请求前缀
restPath=/api
#server.servlet.context-path=/api
# ===============================
# = DATA SOURCE
# ===============================
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.druid.initial-size= 5
spring.datasource.druid.min-idle= 5
spring.datasource.druid.max-active= 50
# 配置获取连接等待超时的时间
spring.datasource.druid.max-wait= 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.time-between-eviction-runs-millis= 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.min-evictable-idle-time-millis= 300000
spring.datasource.druid.validation-query= SELECT 1 FROM DUAL
# 空闲时间监测连接是否优秀奥
spring.datasource.druid.test-while-idle= true
# 数据库连接心跳监测
spring.datasource.druid.keep-alive= true
# 获取链接前检查链接是否有效
spring.datasource.druid.test-on-borrow= true
# 返回连接池时检查链接是否可用
spring.datasource.druid.test-on-return= false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.druid.pool-prepared-statements= true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size= 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.druid.filters=stat,wall
#合并多个DruidDataSource的监控数据
spring.datasource.druid.use-global-data-source-stat=true
# druid web管理页面开启
spring.datasource.druid.stat-view-servlet.enabled=true
# druid web管理页面白名单
#spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
# druid web管理页面账号
spring.datasource.druid.stat-view-servlet.login-username=druid
# druid web管理页面密码
spring.datasource.druid.stat-view-servlet.login-password=laws1q2w3e4r
# druid web管理页面URL访问前缀地址
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
# ===============================
# =======================================
# Mybatis Plus config
# =======================================
mybatis-plus.config-location=classpath:mybatis/mybatis-config.xml
mybatis-plus.mapper-locations=classpath*:mybatis/mapper/**/*.xml
# ========================================
# activiti 配置信息
# ========================================
#spring.activiti.database-schema=ACT
spring.activiti.database-schema-update=false
spring.activiti.check-process-definitions=false
spring.activiti.job-executor-activate=false
spring.activiti.process-definition-location-prefix=classpath:/mybatis/mapper/activiti/
# =========================================
# login value
# =========================================
maxLoginErrorCount=3
verifyCodeMode=1
# =========================================
# 上传文件配置
# =========================================
#上传文件白名单-以,分隔
upload.file.white.lists = doc,docx,xls,xlsx,pdf,PDF,png,jpg
@@ -0,0 +1,9 @@
${AnsiColor.RED} _ _
__ _ __| | ___ __| | __ _
/ _` |/ _` |/ __|____ / _` |/ _` |
| (_| | (_| | (_|_____| (_| | (_| |
\__,_|\__,_|\___| \__,_|\__,_|
${AnsiColor.YELLOW}------------------------------------------------
${AnsiColor.YELLOW} :: ${AnsiColor.YELLOW}@数据资源中心
${AnsiColor.YELLOW}------------------------------------------------${AnsiColor.WHITE}
@@ -0,0 +1,202 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--*****************************property start*****************************-->
<!-- 设置变量。定义变量后,可以使“${}”来使用变量。 -->
<!-- 项目名称 -->
<property name="PROJECT_NAME" value="adc-da" />
<!-- 定义日志文件的存储地址,勿在 LogBack的配置中使用相对路径 -->
<property name="LOG_HOME" value="/tmp/applog/pcms-rest" />
<!-- <property name="LOG_HOME" value="../logs/pcms-rest" />-->
<!-- 定义系统日志文件的存储地址,勿在 LogBack的配置中使用相对路径 -->
<property name="LOG_HOME_SYSTEM" value="system" />
<!-- 定义Druid日志文件的存储地址,勿在 LogBack的配置中使用相对路径 -->
<property name="LOG_HOME_DRUID" value="druid" />
<property name="LOG_HOME_OPERATION" value="operation"/>
<!--*****************************property end*****************************-->
<!--*****************************appender start*****************************-->
<!-- 负责写日志的组件。有两个必要属性name和class。name指定appender名称,class指定appender的全限定名。 -->
<!-- 控制台输出 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!-- 对日志进行格式化。 -->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 系统日志输出:记录所有日志 -->
<!-- RollingFileAppender:滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件。 -->
<appender name="SYSTEM_ALL_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器,打印指定级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的日志级别 -->
<level>INFO</level>
<!-- 满足指定级别的日志操作 -->
<onMatch>ACCEPT</onMatch>
<!-- 不满足指定级别的日志操作 -->
<onMismatch>ACCEPT</onMismatch>
</filter>
<!-- rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。 -->
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/${LOG_HOME_SYSTEM}/${PROJECT_NAME}.system_all.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>7</MaxHistory>
<!--日志文件最大的大小-->
<MaxFileSize>100MB</MaxFileSize>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 系统错误日志输出 -->
<appender name="SYSTEM_ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器,只打印ERROR级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/${LOG_HOME_SYSTEM}/${PROJECT_NAME}.system_error.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>30</MaxHistory>
<!--日志文件最大的大小-->
<MaxFileSize>100MB</MaxFileSize>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- Druid日志输出,用于记录执行INFO级别的慢SQL -->
<appender name="DRUID_SLOWSQL_INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- LevelFilter: 级别过滤器,根据日志级别进行过滤 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/${LOG_HOME_DRUID}/${PROJECT_NAME}.druid_info.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>15</MaxHistory>
<!--日志文件最大的大小-->
<MaxFileSize>50MB</MaxFileSize>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- Druid打印的日志文件,用于记录执行WARN级别的SQL -->
<appender name="DRUID_SLOWSQL_WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/${LOG_HOME_DRUID}/${PROJECT_NAME}.druid_warn.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>30</MaxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>50MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%-5level] %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="OPERATION_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器,只打印ERROR级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/${LOG_HOME_OPERATION}/${PROJECT_NAME}.operation.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>120</MaxHistory>
<!--日志文件最大的大小-->
<MaxFileSize>300MB</MaxFileSize>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!--*****************************appender end*****************************-->
<!--*****************************logger start*****************************-->
<!-- logger用来设置某一个包或者具体的某一个类的日志打印级别、以及指定<appender> -->
<!-- <logger>仅有一个name属性,一个可选的level和一个可选的additivity属性。 -->
<!-- name:用来指定受此logger约束的某一个包或者具体的某一个类。 -->
<!-- level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,还有一个特殊值INHERITED或者同义词NULL,代表强制执行上级的级别。如果未设置此属性,那么当前logger将会继承上级的级别。 -->
<!-- additivity:是否向上级logger传递打印信息。默认是true。 -->
<logger name="org.activiti" level="ERROR" >
<appender-ref ref="SYSTEM_ALL_FILE"/>
<appender-ref ref="SYSTEM_ERROR_FILE"/>
</logger>
<!--<logger name="org.activiti.engine.impl.persistence.entity" level="DEBUG" >-->
<!--<appender-ref ref="CONSOLE" />-->
<!--<appender-ref ref="SYSTEM_ALL_FILE"/>-->
<!--</logger>-->
<logger name="com.alibaba.druid" level="INFO" additivity="true">
<appender-ref ref="DRUID_SLOWSQL_INFO_FILE"/>
</logger>
<logger name="com.alibaba.druid" level="warn">
<appender-ref ref="DRUID_SLOWSQL_WARN_FILE"/>
</logger>
<!-- 设置对应配置信息 -->
<logger name="com.adc.da.log.service.impl.OperationLogServiceImpl" additivity="true" level="INFO">
<appender-ref ref="OPERATION_LOG"/>
</logger>
<!--*****************************logger end*****************************-->
<!-- 开发环境下的日志配置 -->
<springProfile name="dev">
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="SYSTEM_ALL_FILE"/>
<appender-ref ref="SYSTEM_ERROR_FILE"/>
</root>
</springProfile>
<!-- 生产环境下的日志配置 -->
<springProfile name="prod">
<root level="INFO">
<appender-ref ref="SYSTEM_ALL_FILE"/>
<appender-ref ref="SYSTEM_ERROR_FILE"/>
</root>
</springProfile>
</configuration>
Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局参数 -->
<settings>
<setting name="callSettersOnNulls" value="true" />
</settings>
<!-- 配置别名用 -->
<typeAliases>
</typeAliases>
</configuration>
@@ -0,0 +1,152 @@
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>
/**
* <p>
* ${table.comment!}
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
@Accessors(chain = true)
</#if>
<#if table.convert>
@TableName("${table.name}")
</#if>
<#if swagger2>
@ApiModel(value="${entity}对象", description="${table.comment!}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if>
<#if entitySerialVersionUID>
private static final long serialVersionUID = 1L;
</#if>
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.comment!?length gt 0>
<#if swagger2>
@ApiModelProperty(value = "${field.comment}")
<#else>
/**
* ${field.comment}
*/
</#if>
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
@TableId(value = "${field.name}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.name}", type = IdType.${idType})
<#elseif field.convert>
@TableId("${field.name}")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- ----- 存在字段填充设置 ----->
<#if field.convert>
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
<#else>
@TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
@TableField("${field.name}")
</#if>
<#-- 乐观锁注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 逻辑删除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循环遍历 ---------->
<#if !entityLombokModel>
<#list table.fields as field>
<#if field.propertyType == "boolean">
<#assign getprefix="is"/>
<#else>
<#assign getprefix="get"/>
</#if>
public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}
<#if entityBuilderModel>
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
<#else>
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
</#if>
this.${field.propertyName} = ${field.propertyName};
<#if entityBuilderModel>
return this;
</#if>
}
</#list>
</#if>
<#if entityColumnConstant>
<#list table.fields as field>
public static final String ${field.name?upper_case} = "${field.name}";
</#list>
</#if>
<#if activeRecord>
@Override
protected Serializable pkVal() {
<#if keyPropertyName??>
return this.${keyPropertyName};
<#else>
return null;
</#if>
}
</#if>
<#if !entityLombokModel>
@Override
public String toString() {
return "${entity}{" +
<#list table.fields as field>
<#if field_index==0>
"${field.propertyName}=" + ${field.propertyName} +
<#else>
", ${field.propertyName}=" + ${field.propertyName} +
</#if>
</#list>
"}";
}
</#if>
}
@@ -0,0 +1,20 @@
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
/**
* <p>
* ${table.comment!} Mapper 接口
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
</#if>
@@ -0,0 +1,20 @@
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/**
* <p>
* ${table.comment!} 服务类
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
</#if>
@@ -0,0 +1,41 @@
package ${package.Controller};
import org.springframework.web.bind.annotation.RequestMapping;
import ${package.Entity}.${entity};
import io.swagger.annotations.Api;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
/**
* <p>
* ${table.comment!} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@Api(description = "|${entity}|")
@RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass}<${entity}> {
<#else>
public class ${table.controllerName} extends ${superControllerClass}<${entity}>{
</#if>
}
</#if>
@@ -0,0 +1,152 @@
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>
/**
* <p>
* ${table.comment!}
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
@Accessors(chain = true)
</#if>
<#if table.convert>
@TableName("${table.name}")
</#if>
<#if swagger2>
@ApiModel(value="${entity}对象", description="${table.comment!}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if>
<#if entitySerialVersionUID>
private static final long serialVersionUID = 1L;
</#if>
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.comment!?length gt 0>
<#if swagger2>
@ApiModelProperty(value = "${field.comment}")
<#else>
/**
* ${field.comment}
*/
</#if>
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
@TableId(value = "${field.name}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.name}", type = IdType.${idType})
<#elseif field.convert>
@TableId("${field.name}")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- ----- 存在字段填充设置 ----->
<#if field.convert>
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
<#else>
@TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
@TableField("${field.name}")
</#if>
<#-- 乐观锁注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 逻辑删除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循环遍历 ---------->
<#if !entityLombokModel>
<#list table.fields as field>
<#if field.propertyType == "boolean">
<#assign getprefix="is"/>
<#else>
<#assign getprefix="get"/>
</#if>
public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}
<#if entityBuilderModel>
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
<#else>
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
</#if>
this.${field.propertyName} = ${field.propertyName};
<#if entityBuilderModel>
return this;
</#if>
}
</#list>
</#if>
<#if entityColumnConstant>
<#list table.fields as field>
public static final String ${field.name?upper_case} = "${field.name}";
</#list>
</#if>
<#if activeRecord>
@Override
protected Serializable pkVal() {
<#if keyPropertyName??>
return this.${keyPropertyName};
<#else>
return null;
</#if>
}
</#if>
<#if !entityLombokModel>
@Override
public String toString() {
return "${entity}{" +
<#list table.fields as field>
<#if field_index==0>
"${field.propertyName}=" + ${field.propertyName} +
<#else>
", ${field.propertyName}=" + ${field.propertyName} +
</#if>
</#list>
"}";
}
</#if>
}
@@ -0,0 +1,20 @@
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
/**
* <p>
* ${table.comment!} Mapper 接口
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
</#if>
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}">
<#if enableCache>
<!-- 开启二级缓存 -->
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
</#if>
<#if baseResultMap>
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
<#list table.fields as field>
<#if field.keyFlag><#--生成主键排在第一位-->
<id column="${field.name}" property="${field.propertyName}" />
</#if>
</#list>
<#list table.commonFields as field><#--生成公共字段 -->
<result column="${field.name}" property="${field.propertyName}" />
</#list>
<#list table.fields as field>
<#if !field.keyFlag><#--生成普通字段 -->
<result column="${field.name}" property="${field.propertyName}" />
</#if>
</#list>
</resultMap>
</#if>
<#if baseColumnList>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
<#list table.commonFields as field>
${field.name},
</#list>
${table.fieldNames}
</sql>
</#if>
</mapper>
@@ -0,0 +1,20 @@
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/**
* <p>
* ${table.comment!} 服务类
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
</#if>
@@ -0,0 +1,26 @@
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
/**
* <p>
* ${table.comment!} 服务实现类
* </p>
*
* @author ${author}
* @since ${date}
*/
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
}
</#if>
@@ -0,0 +1,97 @@
/* ,使 */
{
/* */
"imageActionName": "/api/ueditor/uploadImageData", /* action */
"imageFieldName": "upfile", /* */
"imageMaxSize": 2048000, /* B */
"imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* */
"imageCompressEnable": true, /* ,true */
"imageCompressBorder": 1600, /* */
"imageInsertAlign": "none", /* */
"imageUrlPrefix": "", /* 访 */
"localSavePathPrefix":"upload/images/inform",
"imagePathFormat": "", /* , */
/* {filename} , */
/* {rand:6} , */
/* {time} */
/* {yyyy} */
/* {yy} */
/* {mm} */
/* {dd} */
/* {hh} */
/* {ii} */
/* {ss} */
/* \ : * ? " < > | */
/* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */
/* 涂鸦图片上传配置项 */
"scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */
"scrawlFieldName": "upfile", /* 提交的图片表单名称 */
"scrawlPathFormat": "", /* 上传保存路径,可以自定义保存路径和文件名格式 */
"scrawlMaxSize": 2048000, /* 上传大小限制,单位B */
"scrawlUrlPrefix": "", /* 图片访问路径前缀 */
"scrawlInsertAlign": "none",
/* 截图工具上传 */
"snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */
"snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
"snapscreenUrlPrefix": "", /* 图片访问路径前缀 */
"snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */
/* 抓取远程图片配置 */
"catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
"catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */
"catcherFieldName": "source", /* 提交的图片列表表单名称 */
"catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
"catcherUrlPrefix": "", /* 图片访问路径前缀 */
"catcherMaxSize": 2048000, /* 上传大小限制,单位B */
"catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */
/*抓取远程图片是否开启,默认true*/
"catchRemoteImageEnable": false,
/* 上传视频配置 */
"videoActionName": "uploadvideo", /* 执行上传视频的action名称 */
"videoFieldName": "upfile", /* 提交的视频表单名称 */
"videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
"videoUrlPrefix": "", /* 视频访问路径前缀 */
"videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */
"videoAllowFiles": [
".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */
/* 上传文件配置 */
"fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */
"fileFieldName": "upfile", /* 提交的文件表单名称 */
"filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
"fileUrlPrefix": "", /* 文件访问路径前缀 */
"fileMaxSize": 51200000, /* 上传大小限制,单位B,默认50MB */
"fileAllowFiles": [
".png", ".jpg", ".jpeg", ".gif", ".bmp",
".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
], /* 上传文件格式显示 */
/* 列出指定目录下的图片 */
"imageManagerActionName": "listimage", /* 执行图片管理的action名称 */
"imageManagerListPath": "/ueditor/jsp/upload/image/", /* 指定要列出图片的目录 */
"imageManagerListSize": 20, /* 每次列出文件数量 */
"imageManagerUrlPrefix": "", /* 图片访问路径前缀 */
"imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */
"imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */
/* 列出指定目录下的文件 */
"fileManagerActionName": "listfile", /* 执行文件管理的action名称 */
"fileManagerListPath": "/ueditor/jsp/upload/file/", /* 指定要列出文件的目录 */
"fileManagerUrlPrefix": "", /* 文件访问路径前缀 */
"fileManagerListSize": 20, /* 每次列出文件数量 */
"fileManagerAllowFiles": [
".png", ".jpg", ".jpeg", ".gif", ".bmp",
".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
] /* */
}
@@ -0,0 +1,12 @@
pdf
doc
docx
xlsx
xls
zip
rar
jpg
jpge
png
gif
ppt
@@ -0,0 +1 @@
/upload/
+33
View File
@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
+118
View File
@@ -0,0 +1,118 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
+310
View File
@@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
+182
View File
@@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
+54
View File
@@ -0,0 +1,54 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.adc</groupId>
<artifactId>foton-slrs-system-rest</artifactId>
<version>3.0.0</version>
</parent>
<groupId>com.adc</groupId>
<artifactId>adc-da-sys</artifactId>
<version>3.0.0</version>
<name>adc-da-sys</name>
<description>laws system rest system config</description>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.8.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.adc</groupId>
<artifactId>adc-da-base</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerVersion>${java.version}</compilerVersion>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,578 @@
package com.adc.da.att.controller;
import com.adc.da.att.entity.AttFileEO;
import com.adc.da.att.service.IAttFileEOService;
import com.adc.da.att.vo.AttFileVo;
import com.adc.da.file.store.IFileStore;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import com.adc.da.util.MD5Util;
import com.adc.da.util.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@RestController
@RequestMapping("/${restPath}/att/attFile")
@Api(description = "|AttFileEO|文件上传")
public class AttFileEOController {
private static final Logger logger = LoggerFactory.getLogger(AttFileEOController.class);
@Autowired
private IAttFileEOService attFileEOService;
@Autowired
private IFileStore iFileStore;
@Value("${file.path}")
private String filePath;//文件存储路径
// @Autowired
// private RoleEOService roleEOService;
//
// @Autowired
// private UserEOService userEOService;
@Value("${upload.file.white.lists}")
private String uploadFileWhiteLists; //上传文件白名单
@ApiOperation(value="|File|上传文件")
@PostMapping(value="/upload",consumes="multipart/*",headers="content-type=multipart/form-data" )
@CrossOrigin(origins = "*", maxAge = 3600)
// @RequiresPermissions("att:attFile:uploadFile")
public ResponseMessage<AttFileVo> uploadFile(@RequestParam("file") @ApiParam(value="上传文件",required=true) MultipartFile file) throws Exception{
if(StringUtils.isNotEmpty(uploadFileWhiteLists)){
String[] fileLists = uploadFileWhiteLists.split(",");
List<String> arrList = Arrays.asList(fileLists);
String getFileName = file.getOriginalFilename();
Pattern pReg = Pattern.compile("\\/|\\/|\\||:|\\?|\\%|\\*|\"|<|>|\\p{Cntrl}");
// getFileName = getFileName.replaceAll(, "_");
Matcher matcher = pReg.matcher(getFileName);
if (matcher.find()) {
return Result.error("文件上传失败,该文件名可能导致文件类型改变,请修改后重试");
}
//截取文件后缀
int pos = getFileName.lastIndexOf(".");
String str = getFileName.substring(pos+1).toLowerCase();
if (arrList.contains(str)) {
AttFileVo fileInfo = attFileEOService.saveFileInfo(file);
if (fileInfo != null && fileInfo.getId() != null) {
String oriFileName = fileInfo.getOldFileName();
if (StringUtils.isNotEmpty(oriFileName)) {
String standNumber = "";
oriFileName = oriFileName.replaceAll("."+fileInfo.getFileSuffix(),"");
Pattern ptest = Pattern.compile("[A-Z]{1,}/{0,1}[A-Z]{1,}\\s{0,1}[0-9]\\d*\\.?\\d*");
Pattern ptest2 = Pattern.compile("[A-Z]{1,}/{0,1}[A-Z]{1,}\\s{0,1}[0-9]\\d*\\.?\\d*-[0-9]{1,4}");
Matcher matcher1 = ptest.matcher(oriFileName);
Matcher matcher2 = ptest2.matcher(oriFileName);
if (matcher2.find()) {
standNumber = matcher2.group();
} else if (matcher1.find()) {
standNumber = matcher1.group();
}
fileInfo.setStandNum(standNumber);
String standName = oriFileName.replace(standNumber,"");
fileInfo.setStandName(standName);
}
return Result.success("true", "上传成功", fileInfo);
} else {
return Result.error("文件上传失败");
}
} else {
return Result.error("文件上传失败,不允许上传该类型文件");
}
} else {
return Result.error("文件上传失败,不允许上传该类型文件");
}
}
@ApiOperation(value="|File|上传文件")
@PostMapping(value="/uploadFiles",consumes="multipart/*",headers="content-type=multipart/form-data" )
@CrossOrigin(origins = "*", maxAge = 3600)
public ResponseMessage<List<AttFileVo>> uploadFile(@RequestParam("files") @ApiParam(value="上传文件",required=true) MultipartFile[] files) throws Exception{
List<AttFileVo> fileInfoList= attFileEOService.saveFilesInfo(files);
return Result.success(fileInfoList);
}
/**
* @Author yangxuenan
* @Description 下载文件
* Date 2018/10/10 18:36
* @Param [response, fileId]
* @return void
**/
@ApiOperation(value = "|File|下载文件")
@GetMapping("/downloadFile")
// @RequiresPermissions("sys:file:download")
public void downloadFile(String fileId, HttpServletResponse response, HttpServletRequest request) throws Exception {
AttFileEO attFileEO = attFileEOService.getFileInfo(fileId);
InputStream is = null;
OutputStream os = null;
response.reset();
try {
String fileOldName = fileNameEncoding(attFileEO.getOldFileName(),request);
response.setHeader("Content-Disposition", "attachment; filename=\""+ fileOldName +"\"");
response.setContentType("application/octet-stream");
is = iFileStore.loadFile(attFileEO.getFilePath()+attFileEO.getFileName());
os = response.getOutputStream();
IOUtils.copy(is, os);
os.flush();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
}
@ApiOperation(value = "|File|手机下载文件")
@GetMapping("/downloadFileByPhone")
// @RequiresPermissions("sys:file:download")
public ResponseMessage downloadFileByPhone(@RequestParam("fileId")@NotNull String fileId,@RequestParam("sign")@NotNull String sign, HttpServletResponse response, HttpServletRequest request) throws Exception {
logger.info("手机下载文件调取到了----------------------"+fileId);
String key = "dufy20170329java";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH");
String time = df.format(new Date());
String signConvert = fileId + time + key;
String signEncrypt = MD5Util.string2MD5(signConvert);
if(StringUtils.isEmpty(sign)){
logger.info("非法请求");
return Result.error("非法请求");
}else {
if(!signEncrypt.equals(sign)){
logger.info("非法请求");
return Result.error("非法请求");
}
}
logger.info("手机下载验证已过----------------------"+sign);
AttFileEO attFileEO = attFileEOService.getFileInfo(fileId);
String filePathResult = "";
try {
if (attFileEO != null) {
File oldFile = new File(filePath + attFileEO.getFilePath()+attFileEO.getFileName());
String fileOldName = attFileEO.getOldFileName();
String timeStr = String.valueOf(System.currentTimeMillis());
String fileOutputPath = filePath + "/" + "phoneLoadFiles/" + timeStr;
File dir = new File(fileOutputPath);
if (!dir.exists()) {
dir.mkdirs();
}
String newFilePath = fileOutputPath + "/" + fileOldName;
File newFile = new File(newFilePath);
if (!newFile.exists()) {
Files.copy(oldFile.toPath(), newFile.toPath());
}
filePathResult = "uploadPath/phoneLoadFiles/" + timeStr + "/" + fileOldName;
return Result.success(filePathResult);
} else {
return Result.error("获取文件信息失败");
}
} catch (IOException e){
logger.error(e.getMessage(), e);
}
return Result.error("获取文件信息失败");
/*InputStream is = null;
OutputStream os = null;
response.reset();
try {
String fileOldName = fileNameEncoding(attFileEO.getOldFileName(),request);
response.setHeader("Content-Disposition", "attachment; filename=\""+ fileOldName +"\"");
response.setContentType("application/octet-stream");
logger.info("请求头设置完毕");
is = iFileStore.loadFile(attFileEO.getFilePath()+attFileEO.getFileName());
logger.info("序列化流完毕");
os = response.getOutputStream();
IOUtils.copy(is, os);
logger.info("文件复制完毕");
os.flush();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}*/
}
@ApiOperation(value = "|File|下载文件")
@GetMapping("/downloadFileForSar")
// @RequiresPermissions("sys:file:downloadFileForSar")
public void downloadFileForSar(String fileId, HttpServletResponse response, HttpServletRequest request) throws Exception {
AttFileEO attFileEO = attFileEOService.getFileInfo(fileId);
InputStream is = null;
OutputStream os = null;
response.reset();
try {
String fileOldName = fileNameEncoding(attFileEO.getOldFileName(),request);
response.setHeader("Content-Disposition", "attachment;filename=\""+fileOldName+"\"");
response.setContentType("application/octet-stream");
is = iFileStore.loadFile(attFileEO.getFilePath()+attFileEO.getFileName());
os = response.getOutputStream();
IOUtils.copy(is, os);
os.flush();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
}
@ApiOperation(value = "|File|下载文件加水印")
@GetMapping("/downloadFileForSarWaterMark")
// @RequiresPermissions("sys:file:downloadFileForSar")
public void downloadFileForSarWaterMark(String fileId, HttpServletResponse response, HttpServletRequest request) throws Exception {
AttFileEO attFileEO = attFileEOService.getFileInfo(fileId);
InputStream is = null;
OutputStream os = null;
response.reset();
try {
String fileOldName = fileNameEncoding(attFileEO.getOldFileName(),request);
//生成一份水印文件
String oldFilePath = filePath + attFileEO.getFilePath()+attFileEO.getFileName();
String newFilePath = filePath + attFileEO.getFilePath()+"waterPath/";
File dir = new File(newFilePath);
if (!dir.exists()) {
dir.mkdirs();
}
String waterFilePath = newFilePath + attFileEO.getOldFileName();
// 添加水印
String waterContent = "";
// String userId = LoginUserUtil.getUserId();
// String userMsg = "";
// UserEO userEO = userEOService.selectByPrimaryKey(userId);
// if (userEO != null) {
// userMsg = userEO.getUname() + ",";
// if (StringUtils.isNotEmpty(userEO.getWorkNum())) {
// userMsg += userEO.getWorkNum() + ",";
// }
// }
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");//设置日期格式
String date = df.format(new Date());
// waterContent = userMsg + date;
//2020年9月5日 去掉水印处理
// WaterMarkUtil.waterMark(oldFilePath,waterFilePath,waterContent);
response.setHeader("Content-Disposition", "attachment;filename=\""+fileOldName+"\"");
response.setContentType("application/octet-stream");
is = iFileStore.loadFile(attFileEO.getFilePath()+"waterPath/"+attFileEO.getOldFileName());
os = response.getOutputStream();
IOUtils.copy(is, os);
os.flush();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
}
/**
* @Author yangxuenan
* @Description 根据不同浏览器定义下载文件编码
* Date 2018/10/11 10:40
* @Param [fileName, request]
* @return java.lang.String
**/
public String fileNameEncoding(String fileName, HttpServletRequest request) throws IOException {
String agent = request.getHeader("User-Agent");
if (agent.contains("Firefox")) {
/*BASE64Encoder base64Encoder = new BASE64Encoder();
fileName = "=?utf-8?B?"
+ base64Encoder.encode(fileName.getBytes("utf-8")) + "?=";*/
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
} else {
fileName = URLEncoder.encode(fileName, "utf-8");
//谷歌中空格变为+问题
fileName = fileName.replaceAll("\\+","%20");
}
return fileName;
}
/**
* @Author yangxuenan
* @Description 查询文件信息
* Date 2018/10/10 18:41
* @Param [fileId]
* @return com.adc.da.util.http.ResponseMessage<com.adc.da.att.entity.AttFileEO>
**/
@ApiOperation(value = "|File|查询文件信息")
@GetMapping("/getAttFileInfo")
public ResponseMessage<AttFileEO> getAttFileInfo(String fileId){
AttFileEO attFileEO = attFileEOService.getFileInfo(fileId);
return Result.success(attFileEO);
}
/**
* @Author yangxuenan
* @Description 查询多个文件信息
* Date 2018/10/24 9:47
* @Param [fileIds]
* @return com.adc.da.util.http.ResponseMessage<com.adc.da.att.entity.AttFileEO>
**/
@ApiOperation(value = "|File|查询多个文件信息")
@GetMapping("/getMultiFileInfos")
// @RequiresPermissions("att:attFile:getMultiFileInfos")
public ResponseMessage<List<AttFileEO>> getMultiFileInfos(String fileIds){
List<AttFileEO> fileObj = attFileEOService.getMultiFileInfos(fileIds);
return Result.success(fileObj);
}
@ApiOperation(value = "|File|下载文件")
@GetMapping("/uploadModalFile")
// @RequiresPermissions("att:attFile:uploadModalFile")
public void uploadModalFile(String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
InputStream is = null;
OutputStream os = null;
response.reset();
try {
String fileOldName = fileNameEncoding(fileName,request);
response.setHeader("Content-Disposition", "attachment; filename=" + fileOldName);
response.setContentType("application/octet-stream");
is = iFileStore.loadFile("/modal/"+fileName);
os = response.getOutputStream();
IOUtils.copy(is, os);
os.flush();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
}
@ApiOperation(value = "|File|获取文件流")
@GetMapping("/getFileInfo")
// @RequiresPermissions("sys:file:getFileInfo")
public void getPdfFileSteam(String fileId,HttpServletRequest request,HttpServletResponse response) {
AttFileEO attFileEO = attFileEOService.getFileInfo(fileId);
InputStream is = null;
OutputStream os = null;
response.reset();
try {
String fileOldName = fileNameEncoding(attFileEO.getOldFileName(), request);
response.setHeader("Content-Disposition", "attachment; filename=" + fileOldName);
response.setContentType("application/octet-stream");
String readFilePath = filePath + "/" + attFileEO.getFilePath() + attFileEO.getFileName();
File readFile = new File(readFilePath);
if (readFile.exists()) {
byte[] data = null;
try (FileInputStream input = new FileInputStream(readFile)){
data = new byte[10000];
int readIndex=0;
while((readIndex=input.read(data)) > 0){
response.getOutputStream().write(data,0,readIndex);
}
}
} else {
return;
}
/* is = iFileStore.loadFile(attFileEO.getFilePath()+attFileEO.getFileName());
os = response.getOutputStream();
IOUtils.copy(is, os);
os.flush();*/
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
@ApiOperation(value = "|File|获取转换后的pdf文件流")
@GetMapping("/getPdfFileInfo")
// @RequiresPermissions("sys:file:getFileInfo")
public ResponseMessage getPdfFileInfo(String fileId,HttpServletRequest request,HttpServletResponse response) {
AttFileEO attFileEO = attFileEOService.getFileInfo(fileId);
InputStream is = null;
OutputStream os = null;
response.reset();
String encreptFileStr = "";
try {
String fileOldName = fileNameEncoding(attFileEO.getOldFileName(), request);
response.setHeader("Content-Disposition", "attachment; filename=" + fileOldName);
response.setContentType("application/octet-stream");
String readFilePath = filePath + "/" + attFileEO.getFilePath() + attFileEO.getFileName();
File readFile = new File(readFilePath);
String codeStr = "";
BASE64Encoder encoder = new BASE64Encoder();
if (readFile.exists()) {
byte[] data = null;
try (FileInputStream input = new FileInputStream(readFile)){
data = new byte[(int) readFile.length()];
input.read(data);
input.close();
} catch (IOException e) {
logger.info(e.getMessage(),e);
}
//base64编码
codeStr = encoder.encode(data);
codeStr = codeStr.replaceAll("\r|\n", "");
//加密处理,前30后50拼上随机生成字符串
encreptFileStr = UUIDUtils.randomUUID(30) + codeStr + UUIDUtils.randomUUID(50);
}
/* is = iFileStore.loadFile(attFileEO.getFilePath()+attFileEO.getFileName());
os = response.getOutputStream();
IOUtils.copy(is, os);
os.flush();*/
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
if(StringUtils.isNotEmpty(encreptFileStr)){
return Result.success("0","",encreptFileStr);
} else {
return Result.error("获取文件信息失败");
}
}
@ApiOperation(value = "|File|分段获取转换后的pdf文件流")
@GetMapping("/getSyncPdfFileInfo")
public void getSyncPdfFileInfo(String fileId,HttpServletRequest request,HttpServletResponse response) {
AttFileEO attFileEO = attFileEOService.getFileInfo(fileId);
InputStream is = null;
OutputStream os = null;
response.reset();
try {
String fileOldName = fileNameEncoding(attFileEO.getOldFileName(), request);
response.setHeader("Content-Disposition", "attachment; filename=" + fileOldName);
String readFilePath = filePath + "/" + attFileEO.getFilePath() + attFileEO.getFileName();
File readFile = new File(readFilePath);
if (readFile.exists()) {
downloadExistsFile(request,response,readFile);
} else {
return;
}
/* is = iFileStore.loadFile(attFileEO.getFilePath()+attFileEO.getFileName());
os = response.getOutputStream();
IOUtils.copy(is, os);
os.flush();*/
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
private void downloadExistsFile(HttpServletRequest request, HttpServletResponse response, File proposeFile) throws IOException,FileNotFoundException {
logger.debug("下载文件路径:" + proposeFile.getPath());
long fSize = proposeFile.length();
// 下载
response.setContentType("application/x-download");
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Length", String.valueOf(fSize));
long pos = 0;
if (null != request.getHeader("Range")) {
// 断点续传
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
try {
// pos = Long.parseLong(request.getHeader("Range").replaceAll(
// "bytes=", "").replaceAll("-", ""));
pos = Long.parseLong((request.getHeader("Range").replaceAll("bytes=", "").split("-")[0]));
} catch (NumberFormatException e) {
logger.error(request.getHeader("Range") + " is not Number!");
pos = 0;
}
}
ServletOutputStream out = response.getOutputStream();
BufferedOutputStream bufferOut = new BufferedOutputStream(out);
InputStream inputStream = new FileInputStream(proposeFile);
String contentRange = new StringBuffer("bytes ").append(
new Long(pos).toString()).append("-").append(
new Long(fSize - 1).toString()).append("/").append(
new Long(fSize).toString()).toString();
response.setHeader("Content-Range", contentRange);
logger.debug("Content-Range", contentRange);
inputStream.skip(pos);
byte[] buffer = new byte[64 * 1024];
int length = 0;
while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
bufferOut.write(buffer, 0, length);
}
bufferOut.flush();
bufferOut.close();
out.close();
inputStream.close();
}
@ApiOperation(value = "|File|获取转换后图片流")
@GetMapping("/getFileImgInfo")
// @RequiresPermissions("sys:file:getFileInfo")
public ResponseMessage<Map<String,String>> getFileImgInfo(String fileId,int pageNo,HttpServletRequest request,HttpServletResponse response) {
Map<String,String> resultMap = new HashMap<>();
AttFileEO attFileEO = attFileEOService.getFileInfo(fileId);
InputStream is = null;
OutputStream os = null;
response.reset();
String encreptFileStr = "";
try {
String fileOldName = fileNameEncoding(attFileEO.getOldFileName(), request);
response.setHeader("Content-Disposition", "attachment; filename=" + fileOldName);
response.setContentType("application/octet-stream");
String fileName = attFileEO.getFileName().substring(0, attFileEO.getFileName().indexOf("."));
String readFilePath = filePath + attFileEO.getFilePath() + fileName + "img/" + pageNo + ".png";
String fileDic = filePath + attFileEO.getFilePath() + fileName + "img";
File readFile = new File(readFilePath);
String codeStr = "";
BASE64Encoder encoder = new BASE64Encoder();
if (readFile.exists()) {
byte[] data = null;
try (FileInputStream input = new FileInputStream(readFile)){
data = new byte[(int) readFile.length()];
input.read(data);
input.close();
} catch (IOException e) {
logger.info(e.getMessage(),e);
}
//base64编码
codeStr = encoder.encode(data);
codeStr = codeStr.replaceAll("\r|\n", "");
//加密处理,前30后50拼上随机生成字符串
encreptFileStr = UUIDUtils.randomUUID(30) + codeStr + UUIDUtils.randomUUID(50);
resultMap.put("data",encreptFileStr);
//获取文件夹下图片数量
int imgCount = 0;
File readFileDic = new File(fileDic);
if (readFileDic.isDirectory()) {
File[] files = readFileDic.listFiles();
if (files != null && files.length>0) {
imgCount = files.length;
}
}
resultMap.put("count",String.valueOf(imgCount));
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
if(StringUtils.isNotEmpty(encreptFileStr)){
return Result.success("0","获取成功",resultMap);
} else {
return Result.error("获取文件信息失败");
}
}
}
@@ -0,0 +1,101 @@
package com.adc.da.att.controller;
import com.adc.da.att.entity.UeditorImage;
import com.adc.da.att.service.IAttFileEOService;
import com.adc.da.att.vo.AttFileVo;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.List;
/*import com.adc.da.att.common.ueditor.ActionEnter;*/
/**
* 用于处理关于ueditor插件相关的请求
* @author zhangyanduan
* @date 2018年9月25日
*
*/
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/${restPath}/ueditor")
public class UeditorController {
@Value("classpath:ueditor/config.json")
private Resource ueditorConfig;
@Autowired
private IAttFileEOService attFileEOService;
@RequestMapping(value = "/getConfig")
@ResponseBody
public String getUeditorConfig(HttpServletRequest request) throws Exception{
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
log.info(path);
log.info(basePath);
String ueditorData = IOUtils.toString(ueditorConfig.getInputStream(), Charset.forName("UTF-8"));
return ueditorData;
}
@RequestMapping("/uploadImageData")
@ResponseBody
public String uploadImageData(HttpServletRequest request) {
UeditorImage msg = uploadFile(request);
return JSONObject.toJSONString(msg);
}
private UeditorImage uploadFile(HttpServletRequest request) {
UeditorImage image = new UeditorImage();
try{
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("upfile");
String referer = request.getHeader("referer");
if(files!=null && !files.isEmpty()){
MultipartFile uploadFile=files.get(0);
AttFileVo attFileVo= attFileEOService.saveFileInfo(uploadFile);
String picUrlPath ="";
if(StringUtils.isNotEmpty(referer)){
picUrlPath=referer+"uploadPath"+ attFileVo.getFilePath()+attFileVo.getFileName();
}else{
picUrlPath="uploadPath"+attFileVo.getFilePath()+attFileVo.getFileName();
}
log.info("Ueditor 上传图片返回路径:"+picUrlPath);
image.setState("SUCCESS");
image.setUrl(picUrlPath);
image.setTitle(attFileVo.getOldFileName());
// image.setState(attFileVo.getOldFileName());
image.setOriginal(attFileVo.getOldFileName());
}else{
image.setState("FAIL");
}
}catch (Exception e){
image.setState("FAIL");
log.error(e.getMessage());
}
/* image.setUrl(serverPath + path);
image.setState("SUCCESS");
image.setOriginal(fileName);
image.setTitle(fileName);*/
return image;
}
}
@@ -0,0 +1,25 @@
package com.adc.da.att.dao;
import com.adc.da.att.entity.AttFileEO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
/**
*
* <br>
* <b>功能:</b>ATT_FILE AttFileEODao<br>
* <b>作者:</b>code generator<br>
* <b>日期:</b> 2018-09-07 <br>
* <b>版权所有:<b>版权归北京卡达克数据技术中心所有。<br>
*/
public interface AttFileEODao extends BaseMapper<AttFileEO> {
public void creatTableInfo(@Param("tableName") String tableName);
public int existTable(@Param("tableName") String tableName);
public AttFileEO selectFileInfoById(AttFileEO attFileEO);
public int insertData(AttFileEO attFileEO);
}
@@ -0,0 +1,217 @@
package com.adc.da.att.entity;
import com.adc.da.base.entity.BaseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.Date;
/**
* <b>功能:</b>ATT_FILE AttFileEOEntity<br>
* <b>作者:</b>code generator<br>
* <b>日期:</b> 2018-09-07 <br>
* <b>版权所有:<b>版权归北京卡达克数据技术中心所有。<br>
*/
public class AttFileEO extends BaseEntity implements Serializable{
private static final long serialVersionUID = 1284335706608668758L;
private static final Logger logger = LoggerFactory.getLogger(AttFileEO.class);
private String id;
private String fileName;
private String oldFileName;
private String fileSuffix;
private String filePath;
private Integer validFlag;
@org.springframework.format.annotation.DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date creationTime;
@org.springframework.format.annotation.DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date modifyTime;
private String tableName;
private String resId;
/**
* java字段名转换为原始数据库列名。<b>如果不存在则返回null</b><br>
* <p>字段列表:</p>
* <li>id -> id</li>
* <li>fileName -> file_name</li>
* <li>oldFileName -> old_file_name</li>
* <li>fileSuffix -> file_suffix</li>
* <li>filePath -> file_path</li>
* <li>validFlag -> valid_flag</li>
* <li>creationTime -> creation_time</li>
* <li>modifyTime -> modify_time</li>
*/
public static String fieldToColumn(String fieldName) {
if (fieldName == null){
return null;
}
switch (fieldName) {
case "id": return "id";
case "fileName": return "file_name";
case "oldFileName": return "old_file_name";
case "fileSuffix": return "file_suffix";
case "filePath": return "file_path";
case "validFlag": return "valid_flag";
case "creationTime": return "creation_time";
case "modifyTime": return "modify_time";
default: return null;
}
}
/**
* 原始数据库列名转换为java字段名。<b>如果不存在则返回null</b><br>
* <p>字段列表:</p>
* <li>id -> id</li>
* <li>file_name -> fileName</li>
* <li>old_file_name -> oldFileName</li>
* <li>file_suffix -> fileSuffix</li>
* <li>file_path -> filePath</li>
* <li>valid_flag -> validFlag</li>
* <li>creation_time -> creationTime</li>
* <li>modify_time -> modifyTime</li>
*/
public static String columnToField(String columnName) {
if (columnName == null){
return null;
}
switch (columnName) {
case "id": return "id";
case "file_name": return "fileName";
case "old_file_name": return "oldFileName";
case "file_suffix": return "fileSuffix";
case "file_path": return "filePath";
case "valid_flag": return "validFlag";
case "creation_time": return "creationTime";
case "modify_time": return "modifyTime";
default: return null;
}
}
/** **/
public String getId() {
int tableNameIndex = this.id.lastIndexOf("_");
if(tableNameIndex!= -1){
String tableName = this.id.substring(0, tableNameIndex);
this.tableName=tableName;
}else{
logger.error("文件ID格式错误:"+this.id);
}
return this.id;
}
/** **/
public void setId(String id) {
if(tableName!=null && !tableName.isEmpty()){
this.id = tableName+"_"+id;
}
//此处注意保存时表结构是否存在
this.id=id;
}
/** **/
public String getFileName() {
return this.fileName;
}
/** **/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/** **/
public String getOldFileName() {
return this.oldFileName;
}
/** **/
public void setOldFileName(String oldFileName) {
this.oldFileName = oldFileName;
}
/** **/
public String getFileSuffix() {
return this.fileSuffix;
}
/** **/
public void setFileSuffix(String fileSuffix) {
this.fileSuffix = fileSuffix;
}
/** **/
public String getFilePath() {
return this.filePath;
}
/** **/
public void setFilePath(String filePath) {
this.filePath = filePath;
}
/** **/
public Integer getValidFlag() {
return this.validFlag;
}
/** **/
public void setValidFlag(Integer validFlag) {
this.validFlag = validFlag;
}
/** **/
public Date getCreationTime() {
return this.creationTime;
}
/** **/
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
/** **/
public Date getModifyTime() {
return this.modifyTime;
}
/** **/
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
public String getTableName() {
if(this.tableName !=null && !this.tableName.isEmpty()){
return this.tableName;
}else{
int tableNameIndex = this.id.lastIndexOf("_");
if(tableNameIndex !=-1){
String tableName = this.id.substring(0, tableNameIndex);
this.tableName=tableName;
}else{
logger.error("文件ID格式错误:"+this.id);
}
return this.tableName;
}
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getResId() {
return resId;
}
public void setResId(String resId) {
this.resId = resId;
}
}
@@ -0,0 +1,41 @@
package com.adc.da.att.entity;
public class UeditorImage {
private String state;
private String url;
private String title;
private String original;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOriginal() {
return original;
}
public void setOriginal(String original) {
this.original = original;
}
}
@@ -0,0 +1,215 @@
package com.adc.da.att.page;
import com.adc.da.base.page.BasePage;
/**
* <b>功能:</b>ATT_FILE AttFileEOPage<br>
* <b>作者:</b>code generator<br>
* <b>日期:</b> 2018-09-07 <br>
* <b>版权所有:<b>版权归北京卡达克数据技术中心所有。<br>
*/
public class AttFileEOPage extends BasePage {
private String id;
private String idOperator = "=";
private String fileName;
private String fileNameOperator = "=";
private String oldFileName;
private String oldFileNameOperator = "=";
private String fileSuffix;
private String fileSuffixOperator = "=";
private String filePath;
private String filePathOperator = "=";
private String validFlag;
private String validFlagOperator = "=";
private String creationTime;
private String creationTime1;
private String creationTime2;
private String creationTimeOperator = "=";
private String modifyTime;
private String modifyTime1;
private String modifyTime2;
private String modifyTimeOperator = "=";
private String tableName;
public String getId() {
int tableNameIndex = this.id.lastIndexOf("_");
String tableName = this.id.substring(0, tableNameIndex);
this.tableName=tableName;
return this.id;
}
public void setId(String id) {
this.id = id;
int tableNameIndex = id.lastIndexOf("_");
String tableName = id.substring(0, tableNameIndex);
this.tableName=tableName;
}
public String getIdOperator() {
return this.idOperator;
}
public void setIdOperator(String idOperator) {
this.idOperator = idOperator;
}
public String getFileName() {
return this.fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileNameOperator() {
return this.fileNameOperator;
}
public void setFileNameOperator(String fileNameOperator) {
this.fileNameOperator = fileNameOperator;
}
public String getOldFileName() {
return this.oldFileName;
}
public void setOldFileName(String oldFileName) {
this.oldFileName = oldFileName;
}
public String getOldFileNameOperator() {
return this.oldFileNameOperator;
}
public void setOldFileNameOperator(String oldFileNameOperator) {
this.oldFileNameOperator = oldFileNameOperator;
}
public String getFileSuffix() {
return this.fileSuffix;
}
public void setFileSuffix(String fileSuffix) {
this.fileSuffix = fileSuffix;
}
public String getFileSuffixOperator() {
return this.fileSuffixOperator;
}
public void setFileSuffixOperator(String fileSuffixOperator) {
this.fileSuffixOperator = fileSuffixOperator;
}
public String getFilePath() {
return this.filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFilePathOperator() {
return this.filePathOperator;
}
public void setFilePathOperator(String filePathOperator) {
this.filePathOperator = filePathOperator;
}
public String getValidFlag() {
return this.validFlag;
}
public void setValidFlag(String validFlag) {
this.validFlag = validFlag;
}
public String getValidFlagOperator() {
return this.validFlagOperator;
}
public void setValidFlagOperator(String validFlagOperator) {
this.validFlagOperator = validFlagOperator;
}
public String getCreationTime() {
return this.creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public String getCreationTime1() {
return this.creationTime1;
}
public void setCreationTime1(String creationTime1) {
this.creationTime1 = creationTime1;
}
public String getCreationTime2() {
return this.creationTime2;
}
public void setCreationTime2(String creationTime2) {
this.creationTime2 = creationTime2;
}
public String getCreationTimeOperator() {
return this.creationTimeOperator;
}
public void setCreationTimeOperator(String creationTimeOperator) {
this.creationTimeOperator = creationTimeOperator;
}
public String getModifyTime() {
return this.modifyTime;
}
public void setModifyTime(String modifyTime) {
this.modifyTime = modifyTime;
}
public String getModifyTime1() {
return this.modifyTime1;
}
public void setModifyTime1(String modifyTime1) {
this.modifyTime1 = modifyTime1;
}
public String getModifyTime2() {
return this.modifyTime2;
}
public void setModifyTime2(String modifyTime2) {
this.modifyTime2 = modifyTime2;
}
public String getModifyTimeOperator() {
return this.modifyTimeOperator;
}
public void setModifyTimeOperator(String modifyTimeOperator) {
this.modifyTimeOperator = modifyTimeOperator;
}
public String getTableName() {
int tableNameIndex = this.id.lastIndexOf("_");
String tableName = this.id.substring(0, tableNameIndex);
this.tableName=tableName;
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
}
@@ -0,0 +1,25 @@
package com.adc.da.att.service;
import com.adc.da.att.entity.AttFileEO;
import com.adc.da.att.vo.AttFileVo;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.List;
public interface IAttFileEOService extends IService<AttFileEO> {
public AttFileVo saveFileInfo(File file);
public AttFileVo saveFileInfo(MultipartFile file);
public List<AttFileVo> saveFilesInfo(MultipartFile[] files);
public AttFileEO getFileInfo(String attId);
public List<AttFileEO> getMultiFileInfos(String fileIds);
public String saveFileAttId(File file);
}
@@ -0,0 +1,361 @@
package com.adc.da.att.service.impl;
import com.adc.da.att.dao.AttFileEODao;
import com.adc.da.att.entity.AttFileEO;
import com.adc.da.att.service.IAttFileEOService;
import com.adc.da.att.vo.AttFileVo;
import com.adc.da.common.ValidFlagEnum;
import com.adc.da.util.FileUtil;
import com.adc.da.util.UUIDUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service("attFileEOService")
@Transactional(value = "transactionManager", readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
@Slf4j
public class AttFileEOServiceImpl extends ServiceImpl<AttFileEODao, AttFileEO> implements IAttFileEOService {
@Value("${file.path}")
private String filePath;//文件存储路径
/**
* 保存文件并返回文件ID
*
* @param file
*/
@Transactional(rollbackFor = Exception.class)
public AttFileVo saveFileInfo(File file) {
/**
* 1、首先生成文件保存的主键ID
* 2、根据文件ID生成随机路径
* 3、生成文件名
* 3、保存文件
* 4、获取文件相关信息
* 5、判断当前表是否有存在,如果存在则执行insert语句 如果不存在则创建表结构
* 5、保存入库并返回主键ID
*/
AttFileVo attFileVo = new AttFileVo();
String fileId = UUIDUtils.randomUUID20();
try {
String uuidPath = UUIDUtils.getUUIDPath(fileId);
String FileSavePath = filePath + uuidPath + "/";
File dir = new File(FileSavePath);
if (!dir.exists()) {
dir.mkdirs();
}
String fileName = file.getName();
String fileSuffix = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
String newFileName = fileId +"."+ fileSuffix;
File saveFile = new File(FileSavePath + newFileName);
FileUtils.copyFile(file,saveFile);
//开始存储文件信息
String tableName = UUIDUtils.getAttTable();
int existTable = this.baseMapper.existTable(tableName);
if (existTable == 0) {
this.baseMapper.creatTableInfo(tableName);
}
fileId = tableName + "_" + fileId;
AttFileEO attFileEO = new AttFileEO();
attFileEO.setTableName(tableName);
attFileEO.setId(fileId);
attFileEO.setOldFileName(fileName);
attFileEO.setFileSuffix(fileSuffix);
attFileEO.setFilePath(uuidPath);
attFileEO.setFileName(newFileName);
attFileEO.setValidFlag(ValidFlagEnum.VALID_TRUE.getValue());
attFileEO.setCreationTime(new Date());
attFileEO.setModifyTime(new Date());
this.baseMapper.insertData(attFileEO);
attFileVo.setId(fileId);
attFileVo.setFileName(newFileName);
attFileVo.setFilePath(uuidPath);
attFileVo.setFileSuffix(fileSuffix);
attFileVo.setOldFileName(fileName);
} catch (IOException e) {
log.error(e.getMessage(),e);
} catch (Exception e) {
log.error(e.getMessage(),e);
}
return attFileVo;
}
/**
* 保存文件并返回文件ID
*
* @param file
*/
@Transactional(rollbackFor = Exception.class)
public AttFileVo saveFileInfo(MultipartFile file) {
/**
* 1、首先生成文件保存的主键ID
* 2、根据文件ID生成随机路径
* 3、生成文件名
* 3、保存文件
* 4、获取文件相关信息
* 5、判断当前表是否有存在,如果存在则执行insert语句 如果不存在则创建表结构
* 5、保存入库并返回主键ID
*/
AttFileVo attFileVo = new AttFileVo();
String fileId = UUIDUtils.randomUUID20();
try {
String uuidPath = UUIDUtils.getUUIDPath(fileId);
String FileSavePath = filePath + uuidPath;
File dir = new File(FileSavePath);
if (!dir.exists()) {
dir.mkdirs();
}
//开始存储文件
String fileName = file.getOriginalFilename();
// 此处发现在IE 11中存在获取文件名时获取了文件路径,此处将文件路径去除
if(fileName.indexOf(":\\")>-1){
// 此时说明存在从根路径获取的内容 需要处理
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
}
String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
String newFileName = fileId + "." + fileSuffix;
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(FileSavePath + newFileName));
//开始存储文件信息
String tableName = UUIDUtils.getAttTable();
int existTable = this.baseMapper.existTable(tableName);
if (existTable == 0) {
this.baseMapper.creatTableInfo(tableName);
}
fileId = tableName + "_" + fileId;
AttFileEO attFileEO = new AttFileEO();
attFileEO.setTableName(tableName);
attFileEO.setId(fileId);
attFileEO.setOldFileName(fileName);
attFileEO.setFileSuffix(fileSuffix);
attFileEO.setFilePath(uuidPath);
attFileEO.setFileName(newFileName);
attFileEO.setValidFlag(ValidFlagEnum.VALID_TRUE.getValue());
attFileEO.setCreationTime(new Date());
attFileEO.setModifyTime(new Date());
this.baseMapper.insertData(attFileEO);
attFileVo.setId(fileId);
attFileVo.setFileName(newFileName);
attFileVo.setFilePath(uuidPath);
attFileVo.setFileSuffix(fileSuffix);
attFileVo.setOldFileName(fileName);
} catch (IOException e) {
log.error(e.getMessage(),e);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return attFileVo;
}
/***
* 保存文件列表
* @MethodName:saveFilesInfo
* @author: zhangyanduan
* @param:[files]
* @return:java.lang.String
* date: 2018/9/19 9:48
*/
@Transactional(rollbackFor = Exception.class)
public List<AttFileVo> saveFilesInfo(MultipartFile[] files) {
/**
* 1、首先生成文件保存的主键ID
* 2、根据文件ID生成随机路径
* 3、生成文件名
* 3、保存文件
* 4、获取文件相关信息
* 5、判断当前表是否有存在,如果存在则执行insert语句 如果不存在则创建表结构
* 5、保存入库并返回主键ID
*/
List<AttFileVo> fileInfoList = new ArrayList<AttFileVo>();
if (files != null && files.length > 0) {
for (int index = 0; index < files.length; index++) {
MultipartFile file = files[index];
AttFileVo attFileVo = new AttFileVo();
String fileId = UUIDUtils.randomUUID20();
try {
String uuidPath = UUIDUtils.getUUIDPath(fileId);
String FileSavePath = filePath + uuidPath;
File dir = new File(FileSavePath);
if (!dir.exists()) {
dir.mkdirs();
}
//开始存储文件
String fileName = file.getOriginalFilename();
if(fileName.indexOf(":\\")>-1){
// 此时说明存在从根路径获取的内容 需要处理
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
}
String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
String newFileName = fileId + "." + fileSuffix;
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(FileSavePath + newFileName));
//开始存储文件信息
String tableName = UUIDUtils.getAttTable();
int existTable = this.baseMapper.existTable(tableName);
if (existTable == 0) {
this.baseMapper.creatTableInfo(tableName);
}
fileId = tableName + "_" + fileId;
AttFileEO attFileEO = new AttFileEO();
attFileEO.setTableName(tableName);
attFileEO.setId(fileId);
attFileEO.setOldFileName(fileName);
attFileEO.setFileSuffix(fileSuffix);
attFileEO.setFilePath(uuidPath);
attFileEO.setFileName(newFileName);
attFileEO.setValidFlag(ValidFlagEnum.VALID_TRUE.getValue());
attFileEO.setCreationTime(new Date());
attFileEO.setModifyTime(new Date());
this.baseMapper.insertData(attFileEO);
attFileVo.setId(fileId);
attFileVo.setFileName(newFileName);
attFileVo.setFilePath(uuidPath);
attFileVo.setFileSuffix(fileSuffix);
attFileVo.setOldFileName(fileName);
fileInfoList.add(attFileVo);
} catch (IOException e) {
log.error(e.getMessage(),e);
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
}
return fileInfoList;
}
/**
* 根据文件ID获取文件信息
*
* @param attId
* @return
*/
public AttFileEO getFileInfo(String attId) {
/**
* 根据ID获取文件信息
*/
AttFileEO attFileEO = new AttFileEO();
AttFileEO attFileInfo=null;
try {
attFileEO.setId(attId);
attFileInfo = this.baseMapper.selectFileInfoById(attFileEO);
return attFileInfo;
} catch (Exception e) {
log.error(e.getMessage(),e);
}
return attFileEO;
}
/**
* @Author yangxuenan
* @Description 多文件查询
* Date 2018/10/24 11:08
* @Param [fileIds]
* @return java.util.List<com.adc.da.att.entity.AttFileEO>
**/
public List<AttFileEO> getMultiFileInfos(String fileIds) {
List<AttFileEO> fileObj = new ArrayList<>();
if(StringUtils.isNotEmpty(fileIds)){
String idList[] = fileIds.split(",");
for(int i=0;i<idList.length;i++){
AttFileEO attFileEO = new AttFileEO();
try {
if(StringUtils.isNotEmpty(idList[i])){
attFileEO.setId(idList[i]);
AttFileEO getFile = this.baseMapper.selectFileInfoById(attFileEO);
if(attFileEO != null){
fileObj.add(getFile);
}
}
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
}
return fileObj;
}
/**
* @Author yangxuenan
* @Description 获取attId
* Date 2018/10/30 21:05
* @Param [file]
* @return java.lang.String
**/
@Transactional(rollbackFor = Exception.class)
public String saveFileAttId(File file) {
/**
* 1、首先生成文件保存的主键ID
* 2、根据文件ID生成随机路径
* 3、生成文件名
* 3、保存文件
* 4、获取文件相关信息
* 5、判断当前表是否有存在,如果存在则执行insert语句 如果不存在则创建表结构
* 5、保存入库并返回主键ID
*/
String fileId = UUIDUtils.randomUUID20();
try {
String uuidPath = UUIDUtils.getUUIDPath(fileId);
String FileSavePath = filePath + uuidPath;
File dir = new File(FileSavePath);
if (!dir.exists()) {
dir.mkdirs();
}
String fileName = file.getName();
String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
String newFileName = fileId + fileSuffix;
File saveFile = new File(FileSavePath + newFileName);
// FileUtil.copyInputStreamToFile(file.get, saveFile);
FileUtils.moveFile(file,saveFile);
//开始存储文件信息
String tableName = UUIDUtils.getAttTable();
int existTable = this.baseMapper.existTable(tableName);
if (existTable == 0) {
this.baseMapper.creatTableInfo(tableName);
}
fileId = tableName + "_" + fileId;
AttFileEO attFileEO = new AttFileEO();
attFileEO.setTableName(tableName);
attFileEO.setId(fileId);
attFileEO.setOldFileName(fileName);
attFileEO.setFileSuffix(fileSuffix);
attFileEO.setFilePath(uuidPath);
attFileEO.setFileName(newFileName);
attFileEO.setValidFlag(ValidFlagEnum.VALID_TRUE.getValue());
attFileEO.setCreationTime(new Date());
attFileEO.setModifyTime(new Date());
this.baseMapper.insertData(attFileEO);
} catch (IOException e) {
log.error(e.getMessage(),e);
} catch (Exception e) {
log.error(e.getMessage(),e);
} finally {
FileUtil.deleteQuietly(file);
}
return fileId;
}
}
@@ -0,0 +1,90 @@
package com.adc.da.att.vo;
public class AttFileVo {
private String id;
private String fileName;
private String oldFileName;
private String fileSuffix;
private String filePath;
private String attId;
private String name;
//识别文件名中的标准号和名称
private String standNum;
private String standName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getOldFileName() {
return oldFileName;
}
public void setOldFileName(String oldFileName) {
this.oldFileName = oldFileName;
}
public String getFileSuffix() {
return fileSuffix;
}
public void setFileSuffix(String fileSuffix) {
this.fileSuffix = fileSuffix;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getName() {
this.name = this.oldFileName;
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getAttId() {
this.attId=this.id;
return this.attId;
}
public void setAttId(String attId) {
this.attId = attId;
}
public String getStandNum() {
return standNum;
}
public void setStandNum(String standNum) {
this.standNum = standNum;
}
public String getStandName() {
return standName;
}
public void setStandName(String standName) {
this.standName = standName;
}
}
@@ -0,0 +1,206 @@
package com.adc.da.person.controller;
import com.adc.da.base.web.BaseController;
import com.adc.da.http.PageInfo;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import com.adc.da.person.entity.PersonCollectEO;
import com.adc.da.person.page.PersonCollectEOPage;
import com.adc.da.person.service.IPersonCollectEOService;
import com.adc.da.util.LoginUserUtil;
import com.adc.da.util.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
@RestController
@RequestMapping("/${restPath}/person/personCollect")
@Api(description = "|PersonCollectEO|")
public class PersonCollectEOController extends BaseController<PersonCollectEO> {
private static final Logger logger = LoggerFactory.getLogger(PersonCollectEOController.class);
@Autowired
private IPersonCollectEOService personCollectEOService;
/*
* @Author liuyinnan
* @Description //判断是法规,标准,动态
* @Date 17:39 2018/9/28
* @Param [pageNo, pageSize, modeType]
* @return com.adc.da.util.http.ResponseMessage<com.adc.da.util.http.PageInfo<com.adc.da.person.entity.PersonCollectEO>>
**/
@ApiOperation(value = "|PersonCollectEO|分页查询")
@GetMapping("/page")
public ResponseMessage<PageInfo<PersonCollectEO>> page(Integer pageNo, Integer pageSize, String modeType, String collectTitle) throws Exception {
PersonCollectEOPage page = new PersonCollectEOPage();
if (StringUtils.isNotEmpty(modeType)) {
List<String> collectTypes = new ArrayList<>();
switch (modeType) {
case "STAND":
collectTypes.add("INLAND_STAND");
collectTypes.add("FOREIGN_STAND");
collectTypes.add("BUSINESS_STAND");
break;
case "LAWS":
collectTypes.add("INLAND_LAWS");
collectTypes.add("FOREIGN_LAWS");
break;
case "MSG":
collectTypes.add("INLAND_MSG");
collectTypes.add("FOREIGN_MSG");
collectTypes.add("RESOURCE_MSG");
break;
default:break;
}
page.setCollectTypeList(collectTypes);
}
if (pageNo != null) {
page.setPage(pageNo);
}else{
page.setPage(1);
}
if (pageSize != null) {
page.setPageSize(pageSize);
}else{
page.setPageSize(10);
}
if (StringUtils.isNotEmpty(collectTitle)) {
page.setCollectTitle(collectTitle);
}
page.setUserId(LoginUserUtil.getUserId());
List<PersonCollectEO> rows = personCollectEOService.queryByPersonCollectPage(page);
return Result.success(getPageInfo(page.getPager(), rows));
}
@ApiOperation(value = "|PersonCollectEO|查询")
@GetMapping("")
// @RequiresPermissions("person:personCollect:list")
public ResponseMessage<List<PersonCollectEO>> list(PersonCollectEOPage page) throws Exception {
return Result.success(personCollectEOService.queryByList(page));
}
@ApiOperation(value = "|PersonCollectEO|详情")
@GetMapping("/{id}")
// @RequiresPermissions("person:personCollect:get")
public ResponseMessage<PersonCollectEO> find(@PathVariable String id) throws Exception {
return Result.success(personCollectEOService.getById(id));
}
/**
* 刘寅楠
* @param personCollectEO
* @return com.adc.da.person.entity.PersonCollectEO
* @throws Exception
*/
@ApiOperation(value = "|PersonCollectEO|新增")
@PostMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
// @RequiresPermissions("person:personCollect:create")
public ResponseMessage<PersonCollectEO> create(@RequestBody PersonCollectEO personCollectEO) throws Exception {
String userId = LoginUserUtil.getUserId();
personCollectEO.setId(UUIDUtils.randomUUID20());
personCollectEO.setUserId(userId);
personCollectEO.setValidFlag(0);
personCollectEO.setCreationTime(new Date());
personCollectEO.setModifyTime(new Date());
personCollectEOService.save(personCollectEO);
return Result.success("0","收藏成功,请到'我的收藏'中查看相关信息。",personCollectEO);
}
@ApiOperation(value = "|PersonCollectEO|修改")
@PutMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
// @RequiresPermissions("person:personCollect:update")
public ResponseMessage<PersonCollectEO> update(@RequestBody PersonCollectEO personCollectEO) throws Exception {
personCollectEO.setModifyTime(new Date());
personCollectEOService.updateById(personCollectEO);
return Result.success(personCollectEO);
}
@ApiOperation(value = "|PersonCollectEO|删除")
@DeleteMapping("/{id}")
// @RequiresPermissions("person:personCollect:delete")
public ResponseMessage delete(@PathVariable String id) throws Exception {
personCollectEOService.removeById(id);
logger.info("delete from TS_PERSON_COLLECT where id = {}", id);
return Result.success();
}
/*
* @Author liuyinnan
* @Description //对收藏数据进行取消收藏
* @Date 17:31 2018/9/28
* @Param [personCollectEO]
* @return com.adc.da.util.http.ResponseMessage<java.lang.Integer>
**/
@ApiOperation(value = "取消收藏")
@PutMapping("/updateByUserId")
// @RequiresPermissions("person:personCollect:updateByUserId")
public ResponseMessage<PersonCollectEO> updateByUserId(PersonCollectEO personCollectEO) throws Exception {
personCollectEO.setValidFlag(1);
boolean result = personCollectEOService.updateById(personCollectEO);
if(result){
return Result.success("0","取消成功",personCollectEO);
} else {
return Result.error("0","取消失败",personCollectEO);
}
}
@ApiOperation(value = "|批量取消收藏")
@PostMapping("/cancelCollectByBatch")
public ResponseMessage cancelCollectByBatch(String ids) throws Exception {
try {
String arr[] = ids.split(",");
List<String> idList = Arrays.asList(arr);
int count = personCollectEOService.deleteByIdList(idList);
if (count > 0) {
return Result.success("200","取消收藏成功",true);
} else {
return Result.error("400","取消收藏失败");
}
}catch (Exception e){
logger.error(e.getMessage(),e);
return Result.error("400","取消收藏失败");
}
}
/*
* @Author liuyinnan
* @Description //通过检索模糊查询
* @Date 17:38 2018/9/28
* @Param [page]
* @return com.adc.da.util.http.ResponseMessage<com.adc.da.person.entity.PersonCollectEO>
**/
// @ApiOperation(value = "通过内容标题模糊查询")
// @GetMapping("/selectByCollectTitle")
//// @RequiresPermissions("person:personCollect:list")
// public ResponseMessage<List<PersonCollectEO>> selectByCollectTitle(PersonCollectEOPage page) throws Exception {
// page.setValidFlag("0");
// List<PersonCollectEO> personCollectEO=personCollectEOService.queryByList(page);
// return Result.success(personCollectEO);
// }
}
@@ -0,0 +1,216 @@
package com.adc.da.person.controller;
import com.adc.da.base.web.BaseController;
import com.adc.da.http.PageInfo;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import com.adc.da.person.entity.PersonConfEO;
import com.adc.da.person.page.PersonConfEOPage;
import com.adc.da.person.service.IPersonConfEOService;
import com.adc.da.util.LoginUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
@RestController
@RequestMapping("/${restPath}/person/personConf")
@Api(description = "|PersonConfEO|")
public class PersonConfEOController extends BaseController<PersonConfEO> {
private static final Logger logger = LoggerFactory.getLogger(PersonConfEOController.class);
@Autowired
private IPersonConfEOService personConfEOService;
@ApiOperation(value = "|PersonConfEO|分页查询")
@GetMapping("/page")
//@RequiresPermissions("person:personConf:page")
public ResponseMessage<PageInfo<PersonConfEO>> page(PersonConfEOPage page) throws Exception {
List<PersonConfEO> rows = personConfEOService.queryByPage(page);
return Result.success(getPageInfo(page.getPager(), rows));
}
@ApiOperation(value = "|PersonConfEO|查询")
@GetMapping("")
//@RequiresPermissions("person:personConf:list")
public ResponseMessage<List<PersonConfEO>> list(PersonConfEOPage page) throws Exception {
return Result.success(personConfEOService.queryByList(page));
}
@ApiOperation(value = "|PersonConfEO|详情")
@GetMapping("/{id}")
//@RequiresPermissions("person:personConf:get")
public ResponseMessage<PersonConfEO> find(@PathVariable String id) throws Exception {
return Result.success(personConfEOService.getById(id));
}
/**
* gaoyan 用户新增过程中,默认全部新增
* @param
* @param
* @return
*/
@ApiOperation(value = "|PersonConfEO|新增")
@PostMapping(value="addConfList")
// @RequiresPermissions("person:personConf:save")
public ResponseMessage<List<PersonConfEO>> addConfList(String userId) throws Exception {
List<PersonConfEO> list = personConfEOService.saveConfList(userId);
return Result.success(list);
}
/*
* @Author liuyinnan
* @Description //按一个对象更新个人板块
* @Date 8:38 2018/9/25
* @Param [personConfEO]
* @return com.adc.da.util.http.ResponseMessage<com.adc.da.person.entity.PersonConfEO>
**/
@ApiOperation(value = "|PersonConfEO|修改")
@PutMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
//@RequiresPermissions("person:personConf:update")
public ResponseMessage<PersonConfEO> update(@RequestBody PersonConfEO personConfEO) throws Exception {
personConfEOService.updateById(personConfEO);
personConfEO.setCreationTime(new Date());
personConfEO.setModifyTime(new Date());
boolean result=personConfEOService.updateById(personConfEO);
if(!result){
return Result.error("修改失败");
}
return Result.success(personConfEO);
}
// @ApiOperation(value = "根据前台传来的对象保存")
// @PostMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
// public ResponseMessage<PersonConfEO> insertByList(PersonConfEO personConfEO)throws Exception{
// personConfEOService.updateByPrimaryKeySelective(personConfEO);
// personConfEOService.insertByList(personConfEO);
// return Result.success(personConfEO);
// }
@ApiOperation(value = "根据前台传来的对象保存")
@PostMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
public ResponseMessage insertByList(@RequestBody List<PersonConfEO> personConfEOList) throws Exception {
if (personConfEOList != null && personConfEOList.size() > 0) {
// String[] personConfEO=personConfEO.split(",");
for (int i = 0; i < personConfEOList.size(); i++) {
PersonConfEO personConfEO = personConfEOList.get(i);
personConfEO.setUserId("1");
personConfEO.setDisplaySeq(i+1);
personConfEO.setCreationTime(new Date());
personConfEO.setModifyTime(new Date());
System.out.println(personConfEOList.get(i));
personConfEOService.updateById(personConfEOList.get(i));
personConfEOService.insert1(personConfEOList.get(i));
}
}else {
return Result.error("操作失败");
}
return Result.success("","操作成功",personConfEOList);
}
@ApiOperation(value = "|PersonConfEO|删除")
@DeleteMapping("/{id}")
//@RequiresPermissions("person:personConf:delete")
public ResponseMessage delete(@PathVariable String id) throws Exception {
personConfEOService.removeById(id);
logger.info("delete from TS_PERSON_CONF where id = {}", id);
return Result.success();
}
/*
* @Author liuyinnan
* @Description //排序查询
* @Date 16:13 2018/9/21
* @Param []
* @return com.adc.da.util.http.ResponseMessage<java.util.List<com.adc.da.person.entity.PersonConfEO>>
**/
// @ApiOperation(value = "排序查询")
// @GetMapping("/selectByDisplay")
// //@RequiresPermissions("person:personConf:list")
// public ResponseMessage<List<PersonConfEO>> updateById() throws Exception {
// List<PersonConfEO> personConfEO = personConfEOService.updateById();
// return Result.success(personConfEO);
// }
/*
* @Author liuyinnan
* @Description //批量删除
* @Date 16:12 2018/9/21
* @Param [ids]
* @return com.adc.da.util.http.ResponseMessage<java.util.List<com.adc.da.person.entity.PersonConfEO>>
**/
// @ApiOperation(value = "批量删除")
// @DeleteMapping("/{ids}")
// public ResponseMessage<List<PersonConfEO>> deleteByIdList(@PathVariable String ids) throws Exception {
// String[] idList = ids.split(",");
// if (idList != null && idList.length > 0) {
// for (String id : idList) {
// List<PersonConfEO> list = personConfEOService.deleteByIdList(id);
// }
// }
// return Result.success();
// }
/**
* gaoyan
* 查询左侧可显示的目录
* @param
* @return
* @throws Exception
*/
@ApiOperation(value = "|PersonConfEO|详情")
@GetMapping("/getPersonConf")
//@RequiresPermissions("person:personConf:get")
public ResponseMessage<List<HashMap>> getPersonConf() throws Exception {
List<HashMap> list = personConfEOService.selectByUserid(LoginUserUtil.getUserId());
return Result.success(list);
}
/**
* gaoyan
* 个人板块信息查询
* @param
* @return
* @throws Exception
*/
@ApiOperation(value = "|PersonConfEO|详情")
@GetMapping("/getPersonConfList")
//@RequiresPermissions("person:personConf:getPersonConfList")
public ResponseMessage<Map> getPersonConfList() throws Exception {
Map result = personConfEOService.selectPersonConfByUserid(LoginUserUtil.getUserId());
return Result.success(result);
}
/**
* gaoyan
* 个人登录后修改自己显示板块
* @param
* @return
* @throws Exception
*/
@ApiOperation(value = "|PersonConfEO|详情")
@PostMapping("/updatePersonConfList")
//@RequiresPermissions("person:personConf:updatePersonConfList")
public ResponseMessage<String[]> updatePersonConfList(String[] targetKeys) throws Exception {
personConfEOService.updatePersonConfList(targetKeys, LoginUserUtil.getUserId());
return Result.success("","保存成功",targetKeys);
}
}
@@ -0,0 +1,176 @@
package com.adc.da.person.controller;
import com.adc.da.base.web.BaseController;
import com.adc.da.http.PageInfo;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import com.adc.da.person.entity.PersonCookiesEO;
import com.adc.da.person.page.PersonCookiesEOPage;
import com.adc.da.person.service.IPersonCookiesEOService;
import com.adc.da.util.LoginUserUtil;
import com.adc.da.util.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/${restPath}/person/personCookies")
@Api(description = "|PersonCookiesEO|")
public class PersonCookiesEOController extends BaseController<PersonCookiesEO> {
private static final Logger logger = LoggerFactory.getLogger(PersonCookiesEOController.class);
@Autowired
private IPersonCookiesEOService personCookiesEOService;
@ApiOperation(value = "|PersonCookiesEO|分页查询")
@GetMapping("/page")
//@RequiresPermissions("person:personCookies:page")
public ResponseMessage<PageInfo<PersonCookiesEO>> page(PersonCookiesEOPage page) throws Exception {
page.setValidFlag("0");
String userId= LoginUserUtil.getUserId();
page.setUserId(userId);
List<PersonCookiesEO> rows = personCookiesEOService.queryByPage(page);
return Result.success(getPageInfo(page.getPager(), rows));
}
@ApiOperation(value = "|PersonCookiesEO|查询")
@GetMapping("")
//@RequiresPermissions("person:personCookies:list")
public ResponseMessage<List<PersonCookiesEO>> list(PersonCookiesEOPage page) throws Exception {
return Result.success(personCookiesEOService.queryByList(page));
}
@ApiOperation(value = "|PersonCookiesEO|详情")
@GetMapping("/{id}")
//@RequiresPermissions("person:personCookies:get")
public ResponseMessage<PersonCookiesEO> find(@PathVariable String id) throws Exception {
return Result.success(personCookiesEOService.getById(id));
}
/*@ApiOperation(value = "|PersonCookiesEO|新增")
@PostMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
//@RequiresPermissions("person:personCookies:save")
public ResponseMessage<PersonCookiesEO> create(@RequestBody PersonCookiesEO personCookiesEO) throws Exception {
personCookiesEOService.insertSelective(personCookiesEO);
return Result.success(personCookiesEO);
}*/
@ApiOperation(value = "|PersonCookiesEO|新增")
@PostMapping("/create")
//@RequiresPermissions("person:personCookies:save")
public ResponseMessage<PersonCookiesEO> create(@RequestBody PersonCookiesEO personCookiesEO) throws Exception {
personCookiesEO.setUserId(LoginUserUtil.getUserId());
personCookiesEO.setId(UUIDUtils.randomUUID20());
personCookiesEO.setCreationTime(new Date());
personCookiesEO.setModifyTime(new Date());
personCookiesEO.setValidFlag(0);
personCookiesEOService.saveBean(personCookiesEO);
return Result.success(personCookiesEO);
}
@ApiOperation(value = "|PersonCookiesEO|批量删除")
@PostMapping("/deleteByBacth")
public ResponseMessage deleteByBacth(String ids) throws Exception {
try {
String arr[] = ids.split(",");
List<String> idList = Arrays.asList(arr);
int count = personCookiesEOService.deleteByIdList(idList);
if (count > 0) {
return Result.success("200","删除成功",true);
} else {
return Result.error("400","删除失败");
}
}catch (Exception e){
logger.error(e.getMessage(),e);
return Result.error("400","删除失败");
}
}
/*
* @Author liuyinnan
* @Description //删除我的浏览所有记录
* @Date 9:51 2018/9/27
* @Param [ids]
* @return com.adc.da.util.http.ResponseMessage
**/
@ApiOperation(value = "|PersonCookiesEO|批量删除")
@PutMapping("/deleteBacth")
//@RequiresPermissions("person:personCookies:update")
public ResponseMessage update(PersonCookiesEO personCookiesEO) throws Exception {
personCookiesEO.setUserId(LoginUserUtil.getUserId());
personCookiesEOService.updateByAll(personCookiesEO);
return Result.success("true","清除成功",personCookiesEO);
}
@ApiOperation(value = "|PersonCookiesEO|删除")
@DeleteMapping("/{id}")
//@RequiresPermissions("person:personCookies:delete")
public ResponseMessage delete(@PathVariable String id) throws Exception {
personCookiesEOService.removeById(id);
logger.info("delete from TS_PERSON_COOKIES where id = {}", id);
return Result.success("true","删除成功",1);
}
/*
* @Author liuyinnan
* @Description //单句删除
* @Date 9:51 2018/9/27
* @Param [personCookiesEO]
* @return com.adc.da.util.http.ResponseMessage<com.adc.da.person.entity.PersonCookiesEO>
**/
@ApiOperation(value = "根据用户id删除浏览记录")
@PutMapping("/deleteBySimple")
//@RequiresPermissions("person:personCookies:updateByUserId")
public ResponseMessage<Integer> updateByUserId(PersonCookiesEO personCookiesEO) throws Exception {
int personCookiesEO1=personCookiesEOService.updateByUserId(personCookiesEO);
return Result.success("true","删除成功",1);
}
// @ApiOperation(value = "根据浏览类型查询")
// @GetMapping("/cookieType")
// @ResponseBody
// public ResponseMessage<List<PersonCookiesEO>> queryByCookieType(String cookieType) throws Exception{
// List<PersonCookiesEO> personCookiesEO=personCookiesEOService.queryByCookieType(cookieType);
// if(personCookiesEO==null){
// return Result.error("查询失败");
// }
// return Result.success(personCookiesEO);
// }
// @ApiOperation(value = "根据用户id查询")
// @GetMapping("/userId")
// public ResponseMessage<List<PersonCookiesEO>> queryByUserId(String ids) throws Exception {
// String[] idList = ids.split(",");
// if (idList != null && idList.length > 0) {
// for (String id : idList) {
// List<PersonConfEO> list = personConfEOService.deleteByIdList(id);
// }
// }
// return Result.success();
// }
@ApiOperation(value = "|PersonCookiesEO|计算浏览数")
@GetMapping("/countPageCookie")
public ResponseMessage<Integer> countPageCookie(PersonCookiesEO personCookiesEO){
int count = personCookiesEOService.countPageCookie(personCookiesEO);
return Result.success(count);
}
}
@@ -0,0 +1,220 @@
package com.adc.da.person.controller;
import com.adc.da.base.web.BaseController;
import com.adc.da.http.PageInfo;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import com.adc.da.person.entity.PersonMsgEO;
import com.adc.da.person.page.PersonMsgEOPage;
import com.adc.da.person.page.PersonShareEOPage;
import com.adc.da.person.service.IPersonMsgEOService;
import com.adc.da.person.service.IPersonShareEOService;
import com.adc.da.util.LoginUserUtil;
import com.adc.da.util.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
@RestController
@RequestMapping("/${restPath}/person/personMsg")
@Api(description = "|PersonMsgEO|")
public class PersonMsgEOController extends BaseController<PersonMsgEO>{
private static final Logger logger = LoggerFactory.getLogger(PersonMsgEOController.class);
@Autowired
private IPersonMsgEOService personMsgEOService;
@Autowired
private IPersonShareEOService personShareEOService;
@ApiOperation(value = "|PersonMsgEO|分页查询")
@GetMapping("/page")
//@RequiresPermissions("person:personMsg:page")
public ResponseMessage<PageInfo<PersonMsgEO>> page(PersonMsgEOPage page) throws Exception {
page.setValidFlag("0");
List<PersonMsgEO> rows = personMsgEOService.queryByPage(page);
return Result.success(getPageInfo(page.getPager(), rows));
}
@ApiOperation(value = "|PersonMsgEO|查询")
@GetMapping("")
//@RequiresPermissions("person:personMsg:list")
public ResponseMessage<List<PersonMsgEO>> list(PersonMsgEOPage page) throws Exception {
return Result.success(personMsgEOService.queryByList(page));
}
@ApiOperation(value = "|PersonMsgEO|详情")
@GetMapping("/{id}")
//@RequiresPermissions("person:personMsg:get")
public ResponseMessage<PersonMsgEO> find(@PathVariable String id) throws Exception {
return Result.success(personMsgEOService.getById(id));
}
@ApiOperation(value = "|PersonMsgEO|新增")
@PostMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
//@RequiresPermissions("person:personMsg:save")
public ResponseMessage<PersonMsgEO> create(@RequestBody PersonMsgEO personMsgEO) throws Exception {
personMsgEO.setUserId(LoginUserUtil.getUserId());
personMsgEO.setId(UUIDUtils.randomUUID20());
personMsgEO.setCreationTime(new Date());
personMsgEO.setModifyTime(new Date());
personMsgEO.setReadFlag(0);
personMsgEO.setValidFlag(0);
personMsgEOService.save(personMsgEO);
return Result.success(personMsgEO);
}
@ApiOperation(value = "|PersonMsgEO|修改")
@PutMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
//@RequiresPermissions("person:personMsg:update")
public ResponseMessage<PersonMsgEO> update(@RequestBody PersonMsgEO personMsgEO) throws Exception {
personMsgEOService.updateById(personMsgEO);
return Result.success(personMsgEO);
}
@ApiOperation(value = "|PersonMsgEO|删除")
@DeleteMapping("/{id}")
//@RequiresPermissions("person:personMsg:delete")
public ResponseMessage delete(@PathVariable String id) throws Exception {
personMsgEOService.removeById(id);
logger.info("delete from TS_PERSON_MSG where id = {}", id);
return Result.success();
}
/*
* @Author liuyinnan
* @Description 根据id查询详细信息
* @Date 14:10 2018/10/19
* @Param [id]
* @return com.adc.da.util.http.ResponseMessage<com.adc.da.person.entity.PersonMsgEO>
**/
@ApiOperation(value = "|PersonMsgEO|根据id查询详细信息")
@GetMapping("/selectByInfoId")
//@RequiresPermissions("person:personMsg:list")
public ResponseMessage<PersonMsgEO> selectByInfoId(String id) throws Exception {
PersonMsgEO personMsgEO = personMsgEOService.selectByInfoId(id);
// 查询详情表示查看过这条数据同时去修改是否已读
if( null !=personMsgEO.getReadFlag() && personMsgEO.getReadFlag() == 0) {
PersonMsgEO updatete = new PersonMsgEO();
updatete.setId(personMsgEO.getId());
updatete.setReadFlag(1);
updatete.setModifyTime(new Date());
personMsgEOService.updateById(updatete);
}
return Result.success(personMsgEO);
}
/*
* @Author liuyinnan
* @Description 查询当前登录人一共有多少条未读动态
* @Date 14:10 2018/10/19
* @Param [id]
* @return com.adc.da.util.http.ResponseMessage<com.adc.da.person.entity.PersonMsgEO>
**/
@ApiOperation(value = "|PersonMsgEO|查询当前登录人一共有多少条未读动态")
@GetMapping("/selectNotRed")
//@RequiresPermissions("person:personMsg:selectNotRed")
public ResponseMessage<Map<String,Integer>> selectNotRed() throws Exception {
Map<String,Integer> resultMap = new HashMap<String,Integer>();
PersonMsgEOPage page = new PersonMsgEOPage();
page.setValidFlag("0");
page.setReadFlag("0");
page.setUserId(LoginUserUtil.getUserId());
int msgCount = personMsgEOService.selectByNotRed(page);
resultMap.put("msgCount",msgCount);
PersonShareEOPage personShareEOPage = new PersonShareEOPage();
personShareEOPage.setReadFlag("0");
personShareEOPage.setValidFlag("0");
personShareEOPage.setRecipientId(LoginUserUtil.getUserId());
int shareCount = personShareEOService.queryByCount(personShareEOPage);
resultMap.put("shareCount",shareCount);
int allCount = msgCount+shareCount;
resultMap.put("allCount",allCount);
return Result.success(resultMap);
}
@ApiOperation(value = "批量删除")
@PostMapping("/deleteByIdList")
public ResponseMessage deleteByIdList(String ids){
try {
String arr[] = ids.split(",");
List<String> idList = Arrays.asList(arr);
personMsgEOService.deletePersonMsgByIdList(idList);
return Result.success("200","删除成功",true);
}catch (Exception e){
logger.error(e.getMessage(),e);
return Result.error("400","删除失败");
}
}
/*
* @Author yuzhong
* @Description 根据流程编号更改动态信息
* @Date 14:10 2018/10/19
* @Param [id]
* @return com.adc.da.util.http.ResponseMessage<com.adc.da.person.entity.PersonMsgEO>
**/
@ApiOperation(value = "根据流程编号更改动态信息")
@GetMapping("/updateMsgInfoByProcessNum")
//@RequiresPermissions("person:personMsg:selectNotRed")
public ResponseMessage<Map<String,Integer>> updateMsgInfoByProcessNum(String processNum) throws Exception {
Map<String,Integer> resultMap = new HashMap<String,Integer>();
//为了把动态的信息关闭掉
PersonMsgEOPage personMsgEOPage = new PersonMsgEOPage();
personMsgEOPage.setProcessnum(processNum);
personMsgEOPage.setValidFlag("0");
List<PersonMsgEO> personMsgEOList = personMsgEOService.queryByList(personMsgEOPage);
if(personMsgEOList!=null && !personMsgEOList.isEmpty()){
for(PersonMsgEO personMsgEO : personMsgEOList){
personMsgEO.setReadFlag(1);
personMsgEOService.updateById(personMsgEO);
}
}
PersonMsgEOPage page = new PersonMsgEOPage();
page.setValidFlag("0");
page.setReadFlag("0");
page.setUserId(LoginUserUtil.getUserId());
int msgCount = personMsgEOService.selectByNotRed(page);
resultMap.put("msgCount",msgCount);
PersonShareEOPage personShareEOPage = new PersonShareEOPage();
personShareEOPage.setReadFlag("0");
personShareEOPage.setValidFlag("0");
personShareEOPage.setRecipientId(LoginUserUtil.getUserId());
int shareCount = personShareEOService.queryByCount(personShareEOPage);
resultMap.put("shareCount",shareCount);
int allCount = msgCount+shareCount;
resultMap.put("allCount",allCount);
return Result.success(resultMap);
}
@ApiOperation(value = "批量标记已读")
@PostMapping("/markIsReadByBatch")
public ResponseMessage markIsReadByBatch(String ids){
try {
String arr[] = ids.split(",");
List<String> idList = Arrays.asList(arr);
int count = personMsgEOService.markIsReadByBatch(idList);
if (count > 0) {
return Result.success("200","标记成功",true);
} else {
return Result.error("400","标记失败");
}
}catch (Exception e){
logger.error(e.getMessage(),e);
return Result.error("400","标记失败");
}
}
}
@@ -0,0 +1,168 @@
package com.adc.da.person.controller;
import com.adc.da.base.web.BaseController;
import com.adc.da.http.PageInfo;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import com.adc.da.person.entity.PersonNoteEO;
import com.adc.da.person.page.PersonNoteEOPage;
import com.adc.da.person.service.IPersonNoteEOService;
import com.adc.da.util.LoginUserUtil;
import com.adc.da.util.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/${restPath}/person/personNote")
@Api(description = "|PersonNoteEO|")
public class PersonNoteEOController extends BaseController<PersonNoteEO> {
private static final Logger logger = LoggerFactory.getLogger(PersonNoteEOController.class);
@Autowired
private IPersonNoteEOService personNoteEOService;
@ApiOperation(value = "|PersonNoteEO|分页查询")
@GetMapping("/page")
//@RequiresPermissions("person:personNote:page")
public ResponseMessage<PageInfo<PersonNoteEO>> page(PersonNoteEOPage page) throws Exception {
List<PersonNoteEO> rows = personNoteEOService.queryByPage(page);
return Result.success(getPageInfo(page.getPager(), rows));
}
@ApiOperation(value = "|PersonNoteEO|查询")
@GetMapping("")
//@RequiresPermissions("person:personNote:list")
public ResponseMessage<List<PersonNoteEO>> list(PersonNoteEOPage page) throws Exception {
return Result.success(personNoteEOService.queryByList(page));
}
@ApiOperation(value = "|PersonNoteEO|详情")
@GetMapping("/{id}")
//@RequiresPermissions("person:personNote:get")
public ResponseMessage<PersonNoteEO> find(@PathVariable String id) throws Exception {
return Result.success(personNoteEOService.getById(id));
}
/*
* @Author liuyinnan
* @Description //保存笔记
* @Date 18:30 2018/9/28
* @Param [personNoteEO]
* @return com.adc.da.util.http.ResponseMessage<java.lang.Integer>
**/
@ApiOperation(value = "保存笔记")
@PostMapping("/save")
//@RequiresPermissions("person:personNote:save")
public ResponseMessage<PersonNoteEO> save(@RequestBody PersonNoteEO personNoteEO) throws Exception {
personNoteEO.setId(personNoteEO.getId());
personNoteEO.setUserId(personNoteEO.getUserId());
boolean result=personNoteEOService.save(personNoteEO);
if(!result){
return Result.error("保存失败");
}
return Result.success("true","修改成功",personNoteEO);
}
/* @ApiOperation(value = "|PersonNoteEO|修改")
@PutMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
@RequiresPermissions("person:personNote:update")
public ResponseMessage<PersonNoteEO> update(@RequestBody PersonNoteEO personNoteEO) throws Exception {
personNoteEOService.updateByPrimaryKeySelective(personNoteEO);
return Result.success(personNoteEO);
}*/
@ApiOperation(value = "|PersonNoteEO|删除")
@DeleteMapping("/{id}")
// @RequiresPermissions("person:personNote:delete")
public ResponseMessage delete(@PathVariable String id) throws Exception {
personNoteEOService.removeById(id);
logger.info("delete from TS_PERSON_NOTE where id = {}", id);
return Result.success();
}
/*
* @Author liuyinnan
* @Description //通过笔记的id和收藏id进行修改笔记内容
* @Date 8:49 2018/9/28
* @Param [personNoteEO]
* @return com.adc.da.util.http.ResponseMessage<java.lang.Integer>
**/
@ApiOperation(value = "修改笔记")
@PutMapping("/updateById")
//@RequiresPermissions("person:personNote:updateByCollectId")
public ResponseMessage<PersonNoteEO> updateByCollectId(PersonNoteEO personNoteEO) throws Exception {
personNoteEOService.updateByCollectId(personNoteEO);
return Result.success("true","修改成功",personNoteEO);
}
/*
* @Author liuyinnan
* @Description //通过传入的收藏表的id对笔记表进行查询
* @Date 8:44 2018/9/28
* @Param [collectId]
* @return com.adc.da.util.http.ResponseMessage<com.adc.da.person.entity.PersonNoteEO>
**/
@ApiOperation(value = "查询笔记")
@GetMapping("/collectId")
public ResponseMessage<List<PersonNoteEO>> queryByCollectId(PersonNoteEO personNoteEO) throws Exception {
//获取当前登录人
System.err.println("zzzzzzzz "+personNoteEO);
List<PersonNoteEO> personNoteEO1 = personNoteEOService.queryByCollectId(personNoteEO);
System.err.println("xxxxxxxx "+personNoteEO1);
return Result.success(personNoteEO1);
}
/*
* @Author liuyinnan
* @Description //根据用户id和笔记id删除
* @Date 8:38 2018/9/28
* @Param [personNoteEO]
* @return com.adc.da.util.http.ResponseMessage<java.lang.Integer>
**/
@ApiOperation(value = "删除笔记")
@PutMapping("/updatePersonNote")
//@RequiresPermissions("person:personNote:updatePersonNote")
public ResponseMessage<PersonNoteEO> updatePersonNote(PersonNoteEO personNoteEO) throws Exception {
personNoteEOService.updateById(personNoteEO);
return Result.success("true", "删除成功",personNoteEO);
}
/*
* @Author liuyinnan
* @Description //根据收藏的id插入笔记
* @Date 21:15 2018/9/27
* @Param [personNoteEO]
* @return com.adc.da.util.http.ResponseMessage<java.lang.Integer>
**/
@ApiOperation(value = "插入笔记")
@PostMapping("/insertByCollectId")
//@RequiresPermissions("person:personNote:insert")
public ResponseMessage<PersonNoteEO> insert(PersonNoteEO personNoteEO) throws Exception {
personNoteEO.setId(UUIDUtils.randomUUID20());
personNoteEO.setUserId(LoginUserUtil.getUserId());
personNoteEO.setCreartionTime(new Date());
personNoteEO.setModifyTime(new Date());
personNoteEO.setValidFlag(0);
boolean result=personNoteEOService.save(personNoteEO);
if(!result){
return Result.error("添加失败");
}
return Result.success("true", "新增成功",personNoteEO);
}
}
@@ -0,0 +1,143 @@
package com.adc.da.person.controller;
import com.adc.da.base.web.BaseController;
import com.adc.da.http.PageInfo;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import com.adc.da.person.entity.PersonSearchEO;
import com.adc.da.person.page.PersonSearchEOPage;
import com.adc.da.person.service.IPersonSearchEOService;
import com.adc.da.util.LoginUserUtil;
import com.adc.da.util.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
@RestController
@RequestMapping("/${restPath}/person/personSearch")
@Api(description = "|PersonSearchEO|")
public class PersonSearchEOController extends BaseController<PersonSearchEO>{
private static final Logger logger = LoggerFactory.getLogger(PersonSearchEOController.class);
@Autowired
private IPersonSearchEOService personSearchEOService;
@ApiOperation(value = "|PersonSearchEO|分页查询")
@GetMapping("/page")
//@RequiresPermissions("person:personSearch:page")
public ResponseMessage<PageInfo<PersonSearchEO>> page(PersonSearchEOPage page) throws Exception {
List<PersonSearchEO> rows = personSearchEOService.queryByPage(page);
return Result.success(getPageInfo(page.getPager(), rows));
}
@ApiOperation(value = "|PersonSearchEO|查询")
@GetMapping("")
//@RequiresPermissions("person:personSearch:list")
public ResponseMessage<List<PersonSearchEO>> list(PersonSearchEOPage page) throws Exception {
return Result.success(personSearchEOService.queryByList(page));
}
@ApiOperation(value = "|PersonSearchEO|详情")
@GetMapping("/{id}")
//@RequiresPermissions("person:personSearch:get")
public ResponseMessage<PersonSearchEO> find(@PathVariable String id) throws Exception {
return Result.success(personSearchEOService.getById(id));
}
@ApiOperation(value = "|PersonSearchEO|新增")
@PostMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
//@RequiresPermissions("person:personSearch:save")
public ResponseMessage<PersonSearchEO> create(@RequestBody PersonSearchEO personSearchEO) throws Exception {
personSearchEO.setId(UUIDUtils.randomUUID20());
personSearchEO.setCreationTime(new Date());
personSearchEO.setModifyTime(new Date());
personSearchEOService.save(personSearchEO);
return Result.success(personSearchEO);
}
@ApiOperation(value = "|PersonSearchEO|修改")
@PutMapping(consumes = APPLICATION_JSON_UTF8_VALUE)
//@RequiresPermissions("person:personSearch:update")
public ResponseMessage<PersonSearchEO> update(@RequestBody PersonSearchEO personSearchEO) throws Exception {
personSearchEOService.updateById(personSearchEO);
return Result.success(personSearchEO);
}
@ApiOperation(value = "|PersonSearchEO|删除")
@DeleteMapping("/{id}")
//@RequiresPermissions("person:personSearch:delete")
public ResponseMessage delete(@PathVariable String id) throws Exception {
personSearchEOService.removeById(id);
logger.info("delete from TS_PERSON_SEARCH where id = {}", id);
return Result.success();
}
/**
* gaoyan
* 查询各人检索记录
* @param page
* @return
* @throws Exception
*/
@ApiOperation(value = "|PersonSearchEO|查询")
@GetMapping("/selectPersonSearch")
//@RequiresPermissions("person:personSearch:list")
public ResponseMessage<List<PersonSearchEO>> selectPersonSearch(PersonSearchEOPage page) throws Exception {
page.setUserId(LoginUserUtil.getUserId());
page.setOrderBy("creation_time desc");
page.setValidFlag("0");
List<PersonSearchEO> result = personSearchEOService.queryByList(page);
int i = 5;
if(result.size()<5){
i = result.size();
}
List<PersonSearchEO> newresult = result.subList(0,i);
return Result.success(newresult);
}
/**
* gaoyan
* 删除或清空检索历史
* @param
* @return
* @throws Exception
*/
@ApiOperation(value = "|PersonSearchEO|查询")
@PostMapping("/deletePersonSearch")
//@RequiresPermissions("person:personSearch:list")
public ResponseMessage<List<String>> deletePersonSearch(String id,String type) throws Exception {
List<String> idlist = new ArrayList<>();
if(StringUtils.isNotEmpty(type) && type.equals("all")){
// 清空当前登录人所有浏览记录
PersonSearchEOPage personSearchEOPage = new PersonSearchEOPage();
personSearchEOPage.setUserId(LoginUserUtil.getUserId());
personSearchEOPage.setValidFlag("0");
List<PersonSearchEO> resulist = personSearchEOService.queryByList(personSearchEOPage);
for(int i=0;i<resulist.size();i++){
idlist.add(resulist.get(i).getId());
}
} else {
idlist.add(id);
}
PersonSearchEO personSearchEO = new PersonSearchEO();
for(int i=0;i<idlist.size();i++){
personSearchEO.setId(idlist.get(i));
personSearchEO.setValidFlag(1);
personSearchEO.setModifyTime(new Date());
personSearchEOService.updateById(personSearchEO);
}
return Result.success(idlist);
}
}
@@ -0,0 +1,205 @@
package com.adc.da.person.controller;
import com.adc.da.base.web.BaseController;
import com.adc.da.http.PageInfo;
import com.adc.da.http.ResponseMessage;
import com.adc.da.http.Result;
import com.adc.da.person.entity.PersonShareEO;
import com.adc.da.person.page.PersonShareEOPage;
import com.adc.da.person.service.IPersonShareEOService;
import com.adc.da.sys.entity.UserEO;
import com.adc.da.sys.service.IUserEOService;
import com.adc.da.util.LoginUserUtil;
import com.adc.da.util.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
* 分享消息推送
*/
@RestController
@RequestMapping("/${restPath}/person/personShare")
@Api(description = "|PersonShareEO|")
public class PersonShareEOController extends BaseController<PersonShareEO> {
private static final Logger logger = LoggerFactory.getLogger(PersonShareEOController.class);
@Autowired
private IPersonShareEOService personShareEOService;
@Autowired
private IUserEOService userEOService;
@ApiOperation(value = "|PersonShareEO|推送分页查询")
@GetMapping("/page")
//@RequiresPermissions("person:personShare:page")
public ResponseMessage<PageInfo<PersonShareEO>> page(PersonShareEOPage page) {
page.setValidFlag("0");
page.setRecipientId(LoginUserUtil.getUserId());
List<PersonShareEO> rows = personShareEOService.queryByPage(page);
//加载分享人名称到前台
if (rows != null && rows.size() > 0) {
for (PersonShareEO personShareEO : rows) {
String userid = personShareEO.getShareUserId();
UserEO user = userEOService.selectByPrimaryKey(userid);
personShareEO.setShareUserId(user != null ? user.getUname() : null);
}
}
return Result.success(getPageInfo(page.getPager(), rows));
}
@ApiOperation(value = "|PersonShareEO|转发分页查询")
@GetMapping("/forwardPage")
//@RequiresPermissions("person:personShare:page")
public ResponseMessage<PageInfo<PersonShareEO>> forwardPage(PersonShareEOPage page) throws Exception {
page.setFvalidFlag("0");
page.setShareUserId(LoginUserUtil.getUserId());
List<PersonShareEO> rows = personShareEOService.queryByPage(page);
//加载转发人名称到前台
if (rows != null && rows.size() > 0) {
for (PersonShareEO personShareEO : rows) {
String userid = personShareEO.getRecipientId();
UserEO user = userEOService.selectByPrimaryKey(userid);
personShareEO.setShareUserId(user != null ? user.getUname() : null);
}
}
return Result.success(getPageInfo(page.getPager(), rows));
}
@ApiOperation(value = "|PersonShareEO|查询")
@GetMapping("")
//@RequiresPermissions("person:personShare:list")
public ResponseMessage<List<PersonShareEO>> list(PersonShareEOPage page) throws Exception {
return Result.success(personShareEOService.queryByList(page));
}
@ApiOperation(value = "|PersonShareEO|详情")
@GetMapping("/{id}")
//@RequiresPermissions("person:personShare:get")
public ResponseMessage<PersonShareEO> find(@PathVariable String id) throws Exception {
return Result.success(personShareEOService.getById(id));
}
/**
* 功能描述: 消息推送新增
*
* @param: [personShareEO]
* @return: com.adc.da.util.http.ResponseMessage<com.adc.da.person.entity.PersonShareEO>
* @auther: SYT
* @date: 2018/10/15 14:00
*/
@ApiOperation(value = "|PersonShareEO|分享新增")
@PostMapping("/savePersonShare")
//@RequiresPermissions("person:personShare:create")
public ResponseMessage<PersonShareEO> create(PersonShareEO personShareEO) throws Exception {
String[] split = personShareEO.getRecipientId().split(",");
// 去掉重复选择的人
List<String> idList = Arrays.asList(split);
List<String> idListNew = new ArrayList<>();
for (String id : idList) {
if (!idListNew.contains(id)) {
idListNew.add(id);
}
}
for (String s : idListNew) {
//前台传递的值 resType recipientId RES_ID RES_TITLE
personShareEO.setRecipientId(s);
personShareEO.setId(UUIDUtils.randomUUID20());
personShareEO.setShareUserId(LoginUserUtil.getUserId());
personShareEO.setValidFlag(0);
personShareEO.setResUri("推送信息");
personShareEO.setReadFlag(0);
personShareEO.setModifyTime(new Date());
personShareEO.setCreationTime(new Date());
System.out.println(personShareEO);
personShareEOService.save(personShareEO);
}
return Result.success(personShareEO);
}
@ApiOperation(value = "|PersonShareEO|转发新增")
@PostMapping("/savePersonForward")
//@RequiresPermissions("person:personShare:create")
public ResponseMessage<PersonShareEO> forwardCreate(PersonShareEO personShareEO) throws Exception {
String[] split = personShareEO.getRecipientId().split(",");
// 去掉重复选择的人
List<String> idList = Arrays.asList(split);
List<String> idListNew = new ArrayList<>();
for (String id : idList) {
if (!idListNew.contains(id)) {
idListNew.add(id);
}
}
for (String s : idListNew) {
//前台传递的值 resType recipientId RES_ID RES_TITLE
personShareEO.setRecipientId(s);
personShareEO.setId(UUIDUtils.randomUUID20());
personShareEO.setShareUserId(LoginUserUtil.getUserId());
personShareEO.setFvalidFlag(0);
personShareEO.setResUri("转发消息");
personShareEO.setReadFlag(0);
personShareEO.setModifyTime(new Date());
personShareEO.setCreationTime(new Date());
System.out.println(personShareEO);
personShareEOService.save(personShareEO);
}
return Result.success(personShareEO);
}
@ApiOperation(value = "|PersonShareEO|修改")
@PostMapping("/updateReadFlag")
//@RequiresPermissions("person:personShare:update")
public ResponseMessage<PersonShareEO> updateReadFlag(@RequestBody PersonShareEO personShareEO) throws Exception {
personShareEO.setReadFlag(1);
personShareEOService.updateById(personShareEO);
return Result.success(personShareEO);
}
@ApiOperation(value = "|PersonShareEO|删除")
@DeleteMapping("/{id}")
//@RequiresPermissions("person:personShare:delete")
public ResponseMessage delete(@PathVariable String id) throws Exception {
personShareEOService.removeById(id);
logger.info("delete from TS_PERSON_SHARE where id = {}", id);
return Result.success();
}
@ApiOperation(value = "批量删除")
@PostMapping("/deleteByIdList")
public ResponseMessage deleteByIdList(String ids){
try {
String arr[] = ids.split(",");
List<String> idList = Arrays.asList(arr);
personShareEOService.deleteByIdList(idList);
return Result.success("200","删除成功",true);
}catch (Exception e){
logger.error(e.getMessage(),e);
return Result.error("400","删除失败");
}
}
@ApiOperation(value = "转发批量删除")
@PostMapping("/deleteByIdListForward")
public ResponseMessage deleteByIdListForward(String ids){
try {
String arr[] = ids.split(",");
List<String> idList = Arrays.asList(arr);
personShareEOService.deleteByIdListForward(idList);
return Result.success("200","删除成功",true);
}catch (Exception e){
logger.error(e.getMessage(),e);
return Result.error("400","删除失败");
}
}
}
@@ -0,0 +1,32 @@
package com.adc.da.person.dao;
import com.adc.da.base.page.BasePage;
import com.adc.da.person.entity.PersonCollectEO;
import com.adc.da.person.page.PersonCollectEOPage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
*
* <br>
* <b>功能:</b>TS_PERSON_COLLECT PersonCollectEODao<br>
* <b>作者:</b>code generator<br>
* <b>日期:</b> 2018-09-03 <br>
* <b>版权所有:<b>版权归北京卡达克数据技术中心所有。<br>
*/
public interface PersonCollectEODao extends BaseMapper<PersonCollectEO> {
List<PersonCollectEO> queryByList(BasePage page);
int queryByCount(BasePage var1);
List<PersonCollectEO> queryByPage(BasePage page);
public List<PersonCollectEO> queryByPersonCollectPage(PersonCollectEOPage page);
int queryByPersonCollectPageCount(PersonCollectEOPage page);
int deleteByIdList(@Param("idList") List<String> idList);
}

Some files were not shown because too many files have changed in this diff Show More