Commit a06ded9e by java-李谡

代码规范

parent 89564d2b
...@@ -26,7 +26,6 @@ import com.ejweb.core.security.DES3Utils; ...@@ -26,7 +26,6 @@ import com.ejweb.core.security.DES3Utils;
* @time 2016年11月2日 * @time 2016年11月2日
*/ */
public class SecurityPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer { public class SecurityPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
// private static final String key = "";
private static final String CONF_DESC_KEY = "782790337169117184"; private static final String CONF_DESC_KEY = "782790337169117184";
private Map<String, Boolean> keys = new HashMap<String, Boolean>(); private Map<String, Boolean> keys = new HashMap<String, Boolean>();
...@@ -34,20 +33,19 @@ public class SecurityPropertyPlaceholderConfigurer extends PropertyPlaceholderCo ...@@ -34,20 +33,19 @@ public class SecurityPropertyPlaceholderConfigurer extends PropertyPlaceholderCo
@Override @Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
throws BeansException { throws BeansException {
// TODO Auto-generated method stub
try { try {
if(getBoolean(props, "is.devmode", false) == false){// 非开发环境需要对配置文件加密 // 非开发环境需要对配置文件加密
// DESPlus des = new DESPlus(CONF_DESC_KEY);//定义密钥 if (getBoolean(props, "is.devmode", false) == false) {
Enumeration<?> enu = props.propertyNames(); Enumeration<?> enu = props.propertyNames();
while (enu.hasMoreElements()) { while (enu.hasMoreElements()) {
try { try {
String key = (String) enu.nextElement(); String key = (String) enu.nextElement();
if("is.devmode".equals(key) == false && keys.get(key) == null){// 还未处理 if ("is.devmode".equals(key) == false && keys.get(key) == null) {// 还未处理
keys.put(key, true); keys.put(key, true);
String val = (String) props.get(key); String val = (String) props.get(key);
String decrypted = DES3Utils.decrypt(val, CONF_DESC_KEY); String decrypted = DES3Utils.decrypt(val, CONF_DESC_KEY);
if(decrypted != null){ if (decrypted != null) {
props.put(key, decrypted); props.put(key, decrypted);
} }
...@@ -75,85 +73,4 @@ public class SecurityPropertyPlaceholderConfigurer extends PropertyPlaceholderCo ...@@ -75,85 +73,4 @@ public class SecurityPropertyPlaceholderConfigurer extends PropertyPlaceholderCo
} }
return want; return want;
} }
/**
* 解密
* @param encode
* @return
*/
// public static String decrypt(String encode) {
// if (StringUtils.isBlank(encode)) {
// return null;
// }
// try {
// DESPlus des = new DESPlus(CONF_DESC_KEY);
// return des.decrypt(encode);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return null;
// }
public static void main(String[] args) throws IOException {
// System.out.println(DES3Utils.encrypt("http://127.0.0.1:8080/", CONF_DESC_KEY));
// System.out.println(DES3Utils.decrypt("31a63fac8317458d81c034906825749f7c58c30a773c6927", CONF_DESC_KEY));
// InputStream in = new FileInputStream(new File("W:\\FOC智能管控系统\\线上配置\\20161221\\manage.conf\\3DES加密版本\\ejweb.properties"));
// InputStream in = new FileInputStream(new File("W:\\FOC智能管控系统\\线上配置\\20161221\\manage.conf\\ejweb.properties"));
// InputStream in = new FileInputStream(new File("W:\\FOC智能管控系统\\线上配置\\all_conf.20170423\\all_conf\\manage_conf\\ejweb.properties"));
// Properties props = new Properties();
// props.load(in);
// DES解密版本
// Enumeration<?> enu = props.propertyNames();
// while (enu.hasMoreElements()) {
// String key = (String) enu.nextElement();
// String val = (String) props.get(key);
// try {
// DESPlus des = new DESPlus(CONF_DESC_KEY);//定义密钥
//
// System.out.println("正常: "+key+"="+des.decrypt(val));
//
//// System.out.println("正常: "+key+"="+DES3Utils.encrypt(val, CONF_DESC_KEY));
// } catch (Exception e) {
// // TODO: handle exception
// System.out.println("异常: "+key+"="+val);
// }
// }
// 3DES加密
// Enumeration<?> enu = props.propertyNames();
// while (enu.hasMoreElements()) {
// String key = (String) enu.nextElement();
// String val = (String) props.get(key);
// try {
//
// System.out.println("正常: "+key+"="+val+"="+DES3Utils.encrypt(val, CONF_DESC_KEY));
// } catch (Exception e) {
// // TODO: handle exception
// System.out.println("异常: "+key+"="+val);
// }
// }
// Enumeration<?> enu = props.propertyNames();
// while (enu.hasMoreElements()) {
// String key = (String) enu.nextElement();
// String val = (String) props.get(key);
// try {
// String decrypted = DES3Utils.decrypt(val, CONF_DESC_KEY);
// if(decrypted == null){
// System.out.println("新增: "+key+"="+val);
// } else{
// System.out.println("NULL新增: "+key+"="+decrypted);
// }
//// System.out.println("正常: "+key+"="+DES3Utils.decrypt(val, CONF_DESC_KEY));
// } catch (Exception e) {
// // TODO: handle exception
// System.out.println("异常: "+key+"="+val);
// }
// }
// System.out.println(DES3Utils.encrypt("jdbc:mysql://10.70.78.27:3306/foc?useUnicode=true&characterEncoding=utf-8", CONF_DESC_KEY));
System.out.println(DES3Utils.decrypt("31a63fac8317458d81c034906825749f7c58c30a773c6927", CONF_DESC_KEY));
}
} }
...@@ -3,20 +3,19 @@ ...@@ -3,20 +3,19 @@
*/ */
package com.ejweb.core.filter; package com.ejweb.core.filter;
import java.text.SimpleDateFormat; import com.ejweb.core.service.BaseService;
import com.ejweb.core.utils.DateUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.NamedThreadLocal; import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import com.ejweb.core.service.BaseService; import javax.servlet.http.HttpServletRequest;
import com.ejweb.core.utils.DateUtils; import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
/** /**
* 日志拦截器 * 日志拦截器
*
* @author ThinkGem * @author ThinkGem
* @version 2014-8-19 * @version 2014-8-19
*/ */
...@@ -24,44 +23,45 @@ public class LogInterceptor extends BaseService implements HandlerInterceptor { ...@@ -24,44 +23,45 @@ public class LogInterceptor extends BaseService implements HandlerInterceptor {
private static final ThreadLocal<Long> startTimeThreadLocal = private static final ThreadLocal<Long> startTimeThreadLocal =
new NamedThreadLocal<Long>("ThreadLocal StartTime"); new NamedThreadLocal<Long>("ThreadLocal StartTime");
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception { Object handler) throws Exception {
if (logger.isDebugEnabled()){ if (logger.isDebugEnabled()) {
long beginTime = System.currentTimeMillis();//1、开始时间 //1、开始时间
startTimeThreadLocal.set(beginTime); //线程绑定变量(该数据只有当前请求的线程可见) long beginTime = System.currentTimeMillis();
//线程绑定变量(该数据只有当前请求的线程可见)
startTimeThreadLocal.set(beginTime);
logger.debug("开始计时: {} URI: {}", new SimpleDateFormat("hh:mm:ss.SSS") logger.debug("开始计时: {} URI: {}", new SimpleDateFormat("hh:mm:ss.SSS")
.format(beginTime), request.getRequestURI()); .format(beginTime), request.getRequestURI());
} }
return true; return true;
} }
@Override @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception { ModelAndView modelAndView) throws Exception {
if (modelAndView != null){ if (modelAndView != null) {
logger.info("ViewName: " + modelAndView.getViewName()); logger.info("ViewName: " + modelAndView.getViewName());
} }
} }
@Override @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception { Object handler, Exception ex) throws Exception {
// // 保存日志
// LogUtils.saveLog(request, handler, ex, null);
// 打印JVM信息。 // 打印JVM信息。
if (logger.isDebugEnabled()){ if (logger.isDebugEnabled()) {
long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量(开始时间) //得到线程绑定的局部变量(开始时间)
long endTime = System.currentTimeMillis(); //2、结束时间 long beginTime = startTimeThreadLocal.get();
//2、结束时间
long endTime = System.currentTimeMillis();
logger.debug("计时结束:{} 耗时:{} URI: {} 最大内存: {}m 已分配内存: {}m 已分配内存中的剩余空间: {}m 最大可用内存: {}m", logger.debug("计时结束:{} 耗时:{} URI: {} 最大内存: {}m 已分配内存: {}m 已分配内存中的剩余空间: {}m 最大可用内存: {}m",
new SimpleDateFormat("hh:mm:ss.SSS").format(endTime), DateUtils.formatDateTime(endTime - beginTime), new SimpleDateFormat("hh:mm:ss.SSS").format(endTime), DateUtils.formatDateTime(endTime - beginTime),
request.getRequestURI(), Runtime.getRuntime().maxMemory()/1024/1024, Runtime.getRuntime().totalMemory()/1024/1024, Runtime.getRuntime().freeMemory()/1024/1024, request.getRequestURI(), Runtime.getRuntime().maxMemory() / 1024 / 1024, Runtime.getRuntime().totalMemory() / 1024 / 1024, Runtime.getRuntime().freeMemory() / 1024 / 1024,
(Runtime.getRuntime().maxMemory()-Runtime.getRuntime().totalMemory()+Runtime.getRuntime().freeMemory())/1024/1024); (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()) / 1024 / 1024);
} }
} }
} }
...@@ -3,129 +3,129 @@ ...@@ -3,129 +3,129 @@
*/ */
package com.ejweb.core.persistence; package com.ejweb.core.persistence;
import java.util.ArrayList; import com.ejweb.core.conf.GConstants;
import java.util.List; import com.ejweb.core.utils.CookieUtils;
import java.util.regex.Pattern; import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils; import java.util.List;
import java.util.regex.Pattern;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ejweb.core.conf.GConstants;
import com.ejweb.core.utils.CookieUtils;
/** /**
* 分页类 * 分页类
* @author ThinkGem *
* @version 2013-7-2
* @param <T> * @param <T>
*/ */
public class Page<T> { public class Page<T> {
private int pageNo = 1; // 当前页码 private int pageNo = 1;
private int pageSize = GConstants.PAGE_SIZE;//Integer.valueOf(GConstants.getValue("page.pageSize")); // 页面大小,设置为“-1”表示不进行分页(分页无效) private int pageSize = GConstants.PAGE_SIZE;
private long count;
private long count;// 总记录数,设置为“-1”表示不查询总数
private int first;
private int first;// 首页索引 private int last;
private int last;// 尾页索引 private int prev;
private int prev;// 上一页索引 private int next;
private int next;// 下一页索引
private boolean firstPage;
private boolean firstPage;//是否是第一页 private boolean lastPage;
private boolean lastPage;//是否是最后一页
private int length = 8;
private int length = 8;// 显示页面长度 private int slider = 1;
private int slider = 1;// 前后显示页面长度
private List<T> list = new ArrayList<T>(); private List<T> list = new ArrayList<T>();
private String orderBy = ""; // 标准查询有效, 实例: updatedate desc, name asc
private String funcName = "page"; // 设置点击页码调用的js函数名称,默认为page,在一页有多个分页对象时使用。 private String orderBy = "";
private String funcParam = ""; // 函数的附加参数,第三个参数值。 private String funcName = "page";
private String message = ""; // 设置提示消息,显示在“共n条”之后 private String funcParam = "";
private String message = "";
public Page() { public Page() {
this.pageSize = -1; this.pageSize = -1;
} }
/** /**
* 构造方法 * 构造方法
* @param request 传递 repage 参数,来记住页码 *
* @param request 传递 repage 参数,来记住页码
* @param response 用于设置 Cookie,记住页码 * @param response 用于设置 Cookie,记住页码
*/ */
public Page(HttpServletRequest request, HttpServletResponse response){ public Page(HttpServletRequest request, HttpServletResponse response) {
this(request, response, -2); this(request, response, -2);
} }
/** /**
* 构造方法 * 构造方法
* @param request 传递 repage 参数,来记住页码 *
* @param response 用于设置 Cookie,记住页码 * @param request 传递 repage 参数,来记住页码
* @param response 用于设置 Cookie,记住页码
* @param defaultPageSize 默认分页大小,如果传递 -1 则为不分页,返回所有数据 * @param defaultPageSize 默认分页大小,如果传递 -1 则为不分页,返回所有数据
*/ */
public Page(HttpServletRequest request, HttpServletResponse response, int defaultPageSize){ public Page(HttpServletRequest request, HttpServletResponse response, int defaultPageSize) {
// 设置页码参数(传递repage参数,来记住页码) // 设置页码参数(传递repage参数,来记住页码)
String no = request.getParameter("pageNo"); String no = request.getParameter("pageNo");
if (StringUtils.isNumeric(no)){ if (StringUtils.isNumeric(no)) {
CookieUtils.setCookie(response, "pageNo", no); CookieUtils.setCookie(response, "pageNo", no);
this.setPageNo(Integer.parseInt(no)); this.setPageNo(Integer.parseInt(no));
}else if (request.getParameter("repage")!=null){ } else if (request.getParameter("repage") != null) {
no = CookieUtils.getCookie(request, "pageNo"); no = CookieUtils.getCookie(request, "pageNo");
if (StringUtils.isNumeric(no)){ if (StringUtils.isNumeric(no)) {
this.setPageNo(Integer.parseInt(no)); this.setPageNo(Integer.parseInt(no));
} }
} }
// 设置页面大小参数(传递repage参数,来记住页码大小) // 设置页面大小参数(传递repage参数,来记住页码大小)
String size = request.getParameter("pageSize"); String size = request.getParameter("pageSize");
if (StringUtils.isNumeric(size)){ if (StringUtils.isNumeric(size)) {
CookieUtils.setCookie(response, "pageSize", size); CookieUtils.setCookie(response, "pageSize", size);
this.setPageSize(Integer.parseInt(size)); this.setPageSize(Integer.parseInt(size));
}else if (request.getParameter("repage")!=null){ } else if (request.getParameter("repage") != null) {
no = CookieUtils.getCookie(request, "pageSize"); no = CookieUtils.getCookie(request, "pageSize");
if (StringUtils.isNumeric(size)){ if (StringUtils.isNumeric(size)) {
this.setPageSize(Integer.parseInt(size)); this.setPageSize(Integer.parseInt(size));
} }
}else if (defaultPageSize != -2){ } else if (defaultPageSize != -2) {
this.pageSize = defaultPageSize; this.pageSize = defaultPageSize;
} }
// 设置排序参数 // 设置排序参数
String orderBy = request.getParameter("orderBy"); String orderBy = request.getParameter("orderBy");
if (StringUtils.isNotBlank(orderBy)){ if (StringUtils.isNotBlank(orderBy)) {
this.setOrderBy(orderBy); this.setOrderBy(orderBy);
} }
} }
/** /**
* 构造方法 * 构造方法
* @param pageNo 当前页码 *
* @param pageNo 当前页码
* @param pageSize 分页大小 * @param pageSize 分页大小
*/ */
public Page(int pageNo, int pageSize) { public Page(int pageNo, int pageSize) {
this(pageNo, pageSize, 0); this(pageNo, pageSize, 0);
} }
/** /**
* 构造方法 * 构造方法
* @param pageNo 当前页码 *
* @param pageNo 当前页码
* @param pageSize 分页大小 * @param pageSize 分页大小
* @param count 数据条数 * @param count 数据条数
*/ */
public Page(int pageNo, int pageSize, long count) { public Page(int pageNo, int pageSize, long count) {
this(pageNo, pageSize, count, new ArrayList<T>()); this(pageNo, pageSize, count, new ArrayList<T>());
} }
/** /**
* 构造方法 * 构造方法
* @param pageNo 当前页码 *
* @param pageNo 当前页码
* @param pageSize 分页大小 * @param pageSize 分页大小
* @param count 数据条数 * @param count 数据条数
* @param list 本页数据对象列表 * @param list 本页数据对象列表
*/ */
public Page(int pageNo, int pageSize, long count, List<T> list) { public Page(int pageNo, int pageSize, long count, List<T> list) {
this.setCount(count); this.setCount(count);
...@@ -133,17 +133,17 @@ public class Page<T> { ...@@ -133,17 +133,17 @@ public class Page<T> {
this.pageSize = pageSize; this.pageSize = pageSize;
this.list = list; this.list = list;
} }
/** /**
* 初始化参数 * 初始化参数
*/ */
public void initialize(){ public void initialize() {
//1 //1
this.first = 1; this.first = 1;
this.last = (int)(count / (this.pageSize < 1 ? 20 : this.pageSize) + first - 1); this.last = (int) (count / (this.pageSize < 1 ? 20 : this.pageSize) + first - 1);
if (this.count % this.pageSize != 0 || this.last == 0) { if (this.count % this.pageSize != 0 || this.last == 0) {
this.last++; this.last++;
} }
...@@ -151,15 +151,15 @@ public class Page<T> { ...@@ -151,15 +151,15 @@ public class Page<T> {
if (this.last < this.first) { if (this.last < this.first) {
this.last = this.first; this.last = this.first;
} }
if (this.pageNo <= 1) { if (this.pageNo <= 1) {
this.pageNo = this.first; this.pageNo = this.first;
this.firstPage=true; this.firstPage = true;
} }
if (this.pageNo >= this.last) { if (this.pageNo >= this.last) {
this.pageNo = this.last; this.pageNo = this.last;
this.lastPage=true; this.lastPage = true;
} }
if (this.pageNo < this.last - 1) { if (this.pageNo < this.last - 1) {
...@@ -173,7 +173,7 @@ public class Page<T> { ...@@ -173,7 +173,7 @@ public class Page<T> {
} else { } else {
this.prev = this.first; this.prev = this.first;
} }
//2 //2
if (this.pageNo < this.first) {// 如果当前页小于首页 if (this.pageNo < this.first) {// 如果当前页小于首页
this.pageNo = this.first; this.pageNo = this.first;
...@@ -182,22 +182,22 @@ public class Page<T> { ...@@ -182,22 +182,22 @@ public class Page<T> {
if (this.pageNo > this.last) {// 如果当前页大于尾页 if (this.pageNo > this.last) {// 如果当前页大于尾页
this.pageNo = this.last; this.pageNo = this.last;
} }
} }
/** /**
* 默认输出当前分页标签 * 默认输出当前分页标签
* <div class="page">${page}</div> * <div class="page">${page}</div>
*/ */
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (pageNo == first) {// 如果是首页 if (pageNo == first) {// 如果是首页
sb.append("<li class=\"disabled\"><a href=\"javascript:\">&#171; 上一页</a></li>\n"); sb.append("<li class=\"disabled\"><a href=\"javascript:\">&#171; 上一页</a></li>\n");
} else { } else {
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+prev+","+pageSize+",'"+funcParam+"');\">&#171; 上一页</a></li>\n"); sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "(" + prev + "," + pageSize + ",'" + funcParam + "');\">&#171; 上一页</a></li>\n");
} }
int begin = pageNo - (length / 2); int begin = pageNo - (length / 2);
...@@ -219,7 +219,7 @@ public class Page<T> { ...@@ -219,7 +219,7 @@ public class Page<T> {
if (begin > first) { if (begin > first) {
int i = 0; int i = 0;
for (i = first; i < first + slider && i < begin; i++) { for (i = first; i < first + slider && i < begin; i++) {
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">" sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "(" + i + "," + pageSize + ",'" + funcParam + "');\">"
+ (i + 1 - first) + "</a></li>\n"); + (i + 1 - first) + "</a></li>\n");
} }
if (i < begin) { if (i < begin) {
...@@ -232,7 +232,7 @@ public class Page<T> { ...@@ -232,7 +232,7 @@ public class Page<T> {
sb.append("<li class=\"active\"><a href=\"javascript:\">" + (i + 1 - first) sb.append("<li class=\"active\"><a href=\"javascript:\">" + (i + 1 - first)
+ "</a></li>\n"); + "</a></li>\n");
} else { } else {
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">" sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "(" + i + "," + pageSize + ",'" + funcParam + "');\">"
+ (i + 1 - first) + "</a></li>\n"); + (i + 1 - first) + "</a></li>\n");
} }
} }
...@@ -243,52 +243,43 @@ public class Page<T> { ...@@ -243,52 +243,43 @@ public class Page<T> {
} }
for (int i = end + 1; i <= last; i++) { for (int i = end + 1; i <= last; i++) {
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">" sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "(" + i + "," + pageSize + ",'" + funcParam + "');\">"
+ (i + 1 - first) + "</a></li>\n"); + (i + 1 - first) + "</a></li>\n");
} }
if (pageNo == last) { if (pageNo == last) {
sb.append("<li class=\"disabled\"><a href=\"javascript:\">下一页 &#187;</a></li>\n"); sb.append("<li class=\"disabled\"><a href=\"javascript:\">下一页 &#187;</a></li>\n");
} else { } else {
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+next+","+pageSize+",'"+funcParam+"');\">" sb.append("<li><a href=\"javascript:\" onclick=\"" + funcName + "(" + next + "," + pageSize + ",'" + funcParam + "');\">"
+ "下一页 &#187;</a></li>\n"); + "下一页 &#187;</a></li>\n");
} }
sb.append("<li class=\"disabled controls\"><a href=\"javascript:\">当前 "); sb.append("<li class=\"disabled controls\"><a href=\"javascript:\">当前 ");
sb.append("<input type=\"text\" value=\""+pageNo+"\" onkeypress=\"var e=window.event||this;var c=e.keyCode||e.which;if(c==13)"); sb.append("<input type=\"text\" value=\"" + pageNo + "\" onkeypress=\"var e=window.event||this;var c=e.keyCode||e.which;if(c==13)");
sb.append(funcName+"(this.value,"+pageSize+",'"+funcParam+"');\" onclick=\"this.select();\"/> / "); sb.append(funcName + "(this.value," + pageSize + ",'" + funcParam + "');\" onclick=\"this.select();\"/> / ");
sb.append("<input type=\"text\" value=\""+pageSize+"\" onkeypress=\"var e=window.event||this;var c=e.keyCode||e.which;if(c==13)"); sb.append("<input type=\"text\" value=\"" + pageSize + "\" onkeypress=\"var e=window.event||this;var c=e.keyCode||e.which;if(c==13)");
sb.append(funcName+"("+pageNo+",this.value,'"+funcParam+"');\" onclick=\"this.select();\"/> 条,"); sb.append(funcName + "(" + pageNo + ",this.value,'" + funcParam + "');\" onclick=\"this.select();\"/> 条,");
sb.append("共 " + count + " 条"+(message!=null?message:"")+"</a></li>\n"); sb.append("共 " + count + " 条" + (message != null ? message : "") + "</a></li>\n");
sb.insert(0,"<ul>\n").append("</ul>\n");
sb.append("<div style=\"clear:both;\"></div>");
// sb.insert(0,"<div class=\"page\">\n").append("</div>\n"); sb.insert(0, "<ul>\n").append("</ul>\n");
sb.append("<div style=\"clear:both;\"></div>");
return sb.toString(); return sb.toString();
} }
/** /**
* 获取分页HTML代码 * 获取分页HTML代码
*
* @return * @return
*/ */
public String getHtml(){ public String getHtml() {
return toString(); return toString();
} }
// public static void main(String[] args) {
// Page<String> p = new Page<String>(3, 3);
// System.out.println(p);
// System.out.println("首页:"+p.getFirst());
// System.out.println("尾页:"+p.getLast());
// System.out.println("上页:"+p.getPrev());
// System.out.println("下页:"+p.getNext());
// }
/** /**
* 获取设置总数 * 获取设置总数
*
* @return * @return
*/ */
public long getCount() { public long getCount() {
...@@ -297,33 +288,37 @@ public class Page<T> { ...@@ -297,33 +288,37 @@ public class Page<T> {
/** /**
* 设置数据总数 * 设置数据总数
*
* @param count * @param count
*/ */
public void setCount(long count) { public void setCount(long count) {
this.count = count; this.count = count;
if (pageSize >= count){ if (pageSize >= count) {
pageNo = 1; pageNo = 1;
} }
} }
/** /**
* 获取当前页码 * 获取当前页码
*
* @return * @return
*/ */
public int getPageNo() { public int getPageNo() {
return pageNo; return pageNo;
} }
/** /**
* 设置当前页码 * 设置当前页码
*
* @param pageNo * @param pageNo
*/ */
public void setPageNo(int pageNo) { public void setPageNo(int pageNo) {
this.pageNo = pageNo; this.pageNo = pageNo;
} }
/** /**
* 获取页面大小 * 获取页面大小
*
* @return * @return
*/ */
public int getPageSize() { public int getPageSize() {
...@@ -332,6 +327,7 @@ public class Page<T> { ...@@ -332,6 +327,7 @@ public class Page<T> {
/** /**
* 设置页面大小(最大500) * 设置页面大小(最大500)
*
* @param pageSize * @param pageSize
*/ */
public void setPageSize(int pageSize) { public void setPageSize(int pageSize) {
...@@ -340,6 +336,7 @@ public class Page<T> { ...@@ -340,6 +336,7 @@ public class Page<T> {
/** /**
* 首页索引 * 首页索引
*
* @return * @return
*/ */
@JsonIgnore @JsonIgnore
...@@ -349,15 +346,17 @@ public class Page<T> { ...@@ -349,15 +346,17 @@ public class Page<T> {
/** /**
* 尾页索引 * 尾页索引
*
* @return * @return
*/ */
@JsonIgnore @JsonIgnore
public int getLast() { public int getLast() {
return last; return last;
} }
/** /**
* 获取页面总数 * 获取页面总数
*
* @return getLast(); * @return getLast();
*/ */
@JsonIgnore @JsonIgnore
...@@ -367,6 +366,7 @@ public class Page<T> { ...@@ -367,6 +366,7 @@ public class Page<T> {
/** /**
* 是否为第一页 * 是否为第一页
*
* @return * @return
*/ */
@JsonIgnore @JsonIgnore
...@@ -376,15 +376,17 @@ public class Page<T> { ...@@ -376,15 +376,17 @@ public class Page<T> {
/** /**
* 是否为最后一页 * 是否为最后一页
*
* @return * @return
*/ */
@JsonIgnore @JsonIgnore
public boolean isLastPage() { public boolean isLastPage() {
return lastPage; return lastPage;
} }
/** /**
* 上一页索引值 * 上一页索引值
*
* @return * @return
*/ */
@JsonIgnore @JsonIgnore
...@@ -398,6 +400,7 @@ public class Page<T> { ...@@ -398,6 +400,7 @@ public class Page<T> {
/** /**
* 下一页索引值 * 下一页索引值
*
* @return * @return
*/ */
@JsonIgnore @JsonIgnore
...@@ -408,9 +411,10 @@ public class Page<T> { ...@@ -408,9 +411,10 @@ public class Page<T> {
return pageNo + 1; return pageNo + 1;
} }
} }
/** /**
* 获取本页数据对象列表 * 获取本页数据对象列表
*
* @return List<T> * @return List<T>
*/ */
public List<T> getList() { public List<T> getList() {
...@@ -419,6 +423,7 @@ public class Page<T> { ...@@ -419,6 +423,7 @@ public class Page<T> {
/** /**
* 设置本页数据对象列表 * 设置本页数据对象列表
*
* @param list * @param list
*/ */
public Page<T> setList(List<T> list) { public Page<T> setList(List<T> list) {
...@@ -429,13 +434,14 @@ public class Page<T> { ...@@ -429,13 +434,14 @@ public class Page<T> {
/** /**
* 获取查询排序字符串 * 获取查询排序字符串
*
* @return * @return
*/ */
@JsonIgnore @JsonIgnore
public String getOrderBy() { public String getOrderBy() {
// SQL过滤,防止注入 // SQL过滤,防止注入
String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|" String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
+ "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)"; + "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";
Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE); Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
if (sqlPattern.matcher(orderBy).find()) { if (sqlPattern.matcher(orderBy).find()) {
return ""; return "";
...@@ -453,6 +459,7 @@ public class Page<T> { ...@@ -453,6 +459,7 @@ public class Page<T> {
/** /**
* 获取点击页码调用的js函数名称 * 获取点击页码调用的js函数名称
* function ${page.funcName}(pageNo){location="${ctx}/list-${category.id}${urlSuffix}?pageNo="+i;} * function ${page.funcName}(pageNo){location="${ctx}/list-${category.id}${urlSuffix}?pageNo="+i;}
*
* @return * @return
*/ */
@JsonIgnore @JsonIgnore
...@@ -462,6 +469,7 @@ public class Page<T> { ...@@ -462,6 +469,7 @@ public class Page<T> {
/** /**
* 设置点击页码调用的js函数名称,默认为page,在一页有多个分页对象时使用。 * 设置点击页码调用的js函数名称,默认为page,在一页有多个分页对象时使用。
*
* @param funcName 默认为page * @param funcName 默认为page
*/ */
public void setFuncName(String funcName) { public void setFuncName(String funcName) {
...@@ -470,6 +478,7 @@ public class Page<T> { ...@@ -470,6 +478,7 @@ public class Page<T> {
/** /**
* 获取分页函数的附加参数 * 获取分页函数的附加参数
*
* @return * @return
*/ */
@JsonIgnore @JsonIgnore
...@@ -479,6 +488,7 @@ public class Page<T> { ...@@ -479,6 +488,7 @@ public class Page<T> {
/** /**
* 设置分页函数的附加参数 * 设置分页函数的附加参数
*
* @return * @return
*/ */
public void setFuncParam(String funcParam) { public void setFuncParam(String funcParam) {
...@@ -487,44 +497,48 @@ public class Page<T> { ...@@ -487,44 +497,48 @@ public class Page<T> {
/** /**
* 设置提示消息,显示在“共n条”之后 * 设置提示消息,显示在“共n条”之后
*
* @param message * @param message
*/ */
public void setMessage(String message) { public void setMessage(String message) {
this.message = message; this.message = message;
} }
/** /**
* 分页是否有效 * 分页是否有效
*
* @return this.pageSize==-1 * @return this.pageSize==-1
*/ */
@JsonIgnore @JsonIgnore
public boolean isDisabled() { public boolean isDisabled() {
return this.pageSize==-1; return this.pageSize == -1;
} }
/** /**
* 是否进行总数统计 * 是否进行总数统计
*
* @return this.count==-1 * @return this.count==-1
*/ */
@JsonIgnore @JsonIgnore
public boolean isNotCount() { public boolean isNotCount() {
return this.count==-1; return this.count == -1;
} }
/** /**
* 获取 Hibernate FirstResult * 获取 Hibernate FirstResult
*/ */
public int getFirstResult(){ public int getFirstResult() {
int firstResult = (getPageNo() - 1) * getPageSize(); int firstResult = (getPageNo() - 1) * getPageSize();
if (firstResult >= getCount()) { if (firstResult >= getCount()) {
firstResult = 0; firstResult = 0;
} }
return firstResult; return firstResult;
} }
/** /**
* 获取 Hibernate MaxResults * 获取 Hibernate MaxResults
*/ */
public int getMaxResults(){ public int getMaxResults() {
return getPageSize(); return getPageSize();
} }
...@@ -559,5 +573,5 @@ public class Page<T> { ...@@ -559,5 +573,5 @@ public class Page<T> {
// this.count = page.getTotalElements(); // this.count = page.getTotalElements();
// this.list = page.getContent(); // this.list = page.getContent();
// } // }
} }
...@@ -23,8 +23,6 @@ import java.util.Properties; ...@@ -23,8 +23,6 @@ import java.util.Properties;
/** /**
* 数据库分页插件,只拦截查询语句. * 数据库分页插件,只拦截查询语句.
* @author poplar.yfyang / thinkgem
* @version 2013-8-28
*/ */
@Intercepts({@Signature(type = Executor.class, method = "query", @Intercepts({@Signature(type = Executor.class, method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})}) args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
...@@ -36,10 +34,6 @@ public class PaginationInterceptor extends BaseInterceptor { ...@@ -36,10 +34,6 @@ public class PaginationInterceptor extends BaseInterceptor {
public Object intercept(Invocation invocation) throws Throwable { public Object intercept(Invocation invocation) throws Throwable {
final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
// //拦截需要分页的SQL
//// if (mappedStatement.getId().matches(_SQL_PATTERN)) {
// if (StringUtils.indexOfIgnoreCase(mappedStatement.getId(), _SQL_PATTERN) != -1) {
Object parameter = invocation.getArgs()[1]; Object parameter = invocation.getArgs()[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameter); BoundSql boundSql = mappedStatement.getBoundSql(parameter);
Object parameterObject = boundSql.getParameterObject(); Object parameterObject = boundSql.getParameterObject();
...@@ -63,9 +57,6 @@ public class PaginationInterceptor extends BaseInterceptor { ...@@ -63,9 +57,6 @@ public class PaginationInterceptor extends BaseInterceptor {
//分页查询 本地化对象 修改数据库注意修改实现 //分页查询 本地化对象 修改数据库注意修改实现
String pageSql = SQLHelper.generatePageSql(originalSql, page, DIALECT); String pageSql = SQLHelper.generatePageSql(originalSql, page, DIALECT);
// if (log.isDebugEnabled()) {
// log.debug("PAGE SQL:" + StringUtils.replace(pageSql, "\n", ""));
// }
invocation.getArgs()[2] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT); invocation.getArgs()[2] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);
BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), pageSql, boundSql.getParameterMappings(), boundSql.getParameterObject()); BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), pageSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
//解决MyBatis 分页foreach 参数失效 start //解决MyBatis 分页foreach 参数失效 start
...@@ -78,7 +69,6 @@ public class PaginationInterceptor extends BaseInterceptor { ...@@ -78,7 +69,6 @@ public class PaginationInterceptor extends BaseInterceptor {
invocation.getArgs()[0] = newMs; invocation.getArgs()[0] = newMs;
} }
// }
return invocation.proceed(); return invocation.proceed();
} }
......
...@@ -48,10 +48,11 @@ public class ValidateCodeServlet extends HttpServlet { ...@@ -48,10 +48,11 @@ public class ValidateCodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { throws ServletException, IOException {
String validateCode = request.getParameter(VALIDATE_CODE); // AJAX验证,成功返回true // AJAX验证,成功返回true
if (StringUtils.isNotBlank(validateCode)){ String validateCode = request.getParameter(VALIDATE_CODE);
response.getOutputStream().print(validate(request, validateCode)?"true":"false"); if (StringUtils.isNotBlank(validateCode)) {
}else{ response.getOutputStream().print(validate(request, validateCode) ? "true" : "false");
} else {
this.doPost(request, response); this.doPost(request, response);
} }
} }
...@@ -137,11 +138,10 @@ public class ValidateCodeServlet extends HttpServlet { ...@@ -137,11 +138,10 @@ public class ValidateCodeServlet extends HttpServlet {
Random random = new Random(); Random random = new Random();
StringBuilder s = new StringBuilder(); StringBuilder s = new StringBuilder();
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);//random.nextInt(10)); String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);
g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100))); g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100)));
g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)],Font.BOLD,26)); g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)],Font.BOLD,26));
g.drawString(r, 15 * i + 5, 19 + random.nextInt(8)); g.drawString(r, 15 * i + 5, 19 + random.nextInt(8));
// g.drawString(r, i*w/4, h-5);
s.append(r); s.append(r);
} }
return s.toString(); return s.toString();
......
...@@ -9,7 +9,7 @@ import java.io.InputStreamReader; ...@@ -9,7 +9,7 @@ import java.io.InputStreamReader;
/** /**
* MAC地址工具 * MAC地址工具
* *
* @author ThinkGem * @author ThinkGem
* @version 2013-12-21 * @version 2013-12-21
*/ */
...@@ -24,7 +24,7 @@ public class MacUtils { ...@@ -24,7 +24,7 @@ public class MacUtils {
/** /**
* 获取Unix网卡的mac地址. * 获取Unix网卡的mac地址.
* *
* @return mac地址 * @return mac地址
*/ */
public static String getUnixMACAddress() { public static String getUnixMACAddress() {
...@@ -75,7 +75,7 @@ public class MacUtils { ...@@ -75,7 +75,7 @@ public class MacUtils {
/** /**
* 获取Linux网卡的mac地址. * 获取Linux网卡的mac地址.
* *
* @return mac地址 * @return mac地址
*/ */
public static String getLinuxMACAddress() { public static String getLinuxMACAddress() {
...@@ -117,9 +117,9 @@ public class MacUtils { ...@@ -117,9 +117,9 @@ public class MacUtils {
bufferedReader = null; bufferedReader = null;
process = null; process = null;
} }
// 取不到,试下Unix取发 // 取不到,试下Unix取发
if (mac == null){ if (mac == null) {
return getUnixMACAddress(); return getUnixMACAddress();
} }
...@@ -128,7 +128,7 @@ public class MacUtils { ...@@ -128,7 +128,7 @@ public class MacUtils {
/** /**
* 获取widnows网卡的mac地址. * 获取widnows网卡的mac地址.
* *
* @return mac地址 * @return mac地址
*/ */
public static String getWindowsMACAddress() { public static String getWindowsMACAddress() {
...@@ -147,9 +147,7 @@ public class MacUtils { ...@@ -147,9 +147,7 @@ public class MacUtils {
/** /**
* 寻找标示字符串[physical address] * 寻找标示字符串[physical address]
*/ */
// index = line.toLowerCase().indexOf("physical address"); if (line.split("-").length == 6) {
// if (index != -1) {
if (line.split("-").length == 6){
index = line.indexOf(":"); index = line.indexOf(":");
if (index != -1) { if (index != -1) {
/** /**
...@@ -188,7 +186,7 @@ public class MacUtils { ...@@ -188,7 +186,7 @@ public class MacUtils {
return mac; return mac;
} }
public static String getMac(){ public static String getMac() {
String os = getOSName(); String os = getOSName();
String mac; String mac;
if (os.startsWith("windows")) { if (os.startsWith("windows")) {
...@@ -200,10 +198,10 @@ public class MacUtils { ...@@ -200,10 +198,10 @@ public class MacUtils {
} }
return mac == null ? "" : mac; return mac == null ? "" : mac;
} }
/** /**
* 测试用的main方法. * 测试用的main方法.
* *
* @param argc 运行参数. * @param argc 运行参数.
*/ */
public static void main(String[] argc) { public static void main(String[] argc) {
......
package com.ejweb.core.utils;
//import java.util.List;
//
//import com.baidu.yun.channel.auth.ChannelKeyPair;
//import com.baidu.yun.channel.client.BaiduChannelClient;
//import com.baidu.yun.channel.exception.ChannelClientException;
//import com.baidu.yun.channel.exception.ChannelServerException;
//import com.baidu.yun.channel.model.PushBroadcastMessageRequest;
//import com.baidu.yun.channel.model.PushUnicastMessageRequest;
//import com.baidu.yun.core.log.YunLogEvent;
//import com.baidu.yun.core.log.YunLogHandler;
//import com.ejweb.modules.sys.entity.User;
//import com.ejweb.modules.sys.utils.UserUtils;
public class MobileSendMessage {
public static final String apiKey = "oc0yx4ST3dNQcGbXNQUNE2yn";
public static final String secretKey = "KpRboB9HiE6wm7I9IHtcMLnNGZY0S27W";
// /**
// * 无限制推送广播
// * @param title
// * @param content
// */
// public static void pushBroadcastMessage(String title,String content) {
//
// ChannelKeyPair pair = new ChannelKeyPair(MobileSendMessage.apiKey, MobileSendMessage.secretKey);
//
// // 2. 创建BaiduChannelClient对象实例
// BaiduChannelClient channelClient = new BaiduChannelClient(pair);
//
// // 3. 若要了解交互细节,请注册YunLogHandler类
// channelClient.setChannelLogHandler(new YunLogHandler() {
// @Override
// public void onHandle(YunLogEvent event) {
// System.out.println(event.getMessage());
// }
// });
// // 4. 创建请求类对象
// PushBroadcastMessageRequest request = new PushBroadcastMessageRequest();
// request.setDeviceType(3); // device_type => 1: web 2: pc 3:android // 4:ios 5:wp
//
// // request.setMessage("Hello Channel");
// // 若要通知,
// request.setMessageType(1);
// request.setMessage("{\"title\":\""+title+"\",\"description\":\""+content+"\"}");
// //request.setMessage(notify.toString());
//
// // 5. 调用pushMessage接口
// try {
// channelClient.pushBroadcastMessage(request);
// // 6. 认证推送成功
//// System.out.println("push amount : " + response.getSuccessAmount());
// } catch (ChannelClientException e) {
// e.printStackTrace();
// } catch (ChannelServerException e) {
// e.printStackTrace();
// }
//
// }
//
//
// /**
// * 多人员手机提醒信息发送
// * @param title
// * @param content
// * @param users
// */
// public static void pushUnicastMessageMessage(String title,String content,List<String> userIds) {
//
// ChannelKeyPair pair = new ChannelKeyPair(MobileSendMessage.apiKey, MobileSendMessage.secretKey);
//
// // 2. 创建BaiduChannelClient对象实例
// BaiduChannelClient channelClient = new BaiduChannelClient(pair);
//
// // 3. 若要了解交互细节,请注册YunLogHandler类
// channelClient.setChannelLogHandler(new YunLogHandler() {
// @Override
// public void onHandle(YunLogEvent event) {
// System.out.println(event.getMessage());
// }
// });
// // 4. 创建请求类对象
// PushUnicastMessageRequest request = new PushUnicastMessageRequest();
// request.setDeviceType(3); // device_type => 1: web 2: pc 3:android // 4:ios 5:wp
//
// // request.setMessage("Hello Channel");
// // 若要通知,
// request.setMessageType(1);
// request.setMessage("{\"title\":\""+title+"\",\"description\":\""+content+"\"}");
//
// // 5. 调用pushMessage接口
// try {
// for (String userId : userIds) {
// User sendUser=UserUtils.get(userId);
// if(sendUser!=null){
// request.setChannelId(Long.valueOf(sendUser.getMobileChannelId()));
// request.setUserId(sendUser.getMobileUserId());
// channelClient.pushUnicastMessage(request);
// }
// }
//
// // 6. 认证推送成功
//// System.out.println("push amount : " + response.getSuccessAmount());
// } catch (ChannelClientException e) {
// e.printStackTrace();
// } catch (ChannelServerException e) {
// e.printStackTrace();
// }
//
// }
}
/** /**
* Copyright (c) 2005-2011 springside.org.cn * Copyright (c) 2005-2011 springside.org.cn
* * <p>
* $Id: PropertiesLoader.java 1690 2012-02-22 13:42:00Z calvinxiu $ * $Id: PropertiesLoader.java 1690 2012-02-22 13:42:00Z calvinxiu $
*/ */
package com.ejweb.core.utils; package com.ejweb.core.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Properties;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -17,10 +12,13 @@ import org.springframework.core.io.DefaultResourceLoader; ...@@ -17,10 +12,13 @@ import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.ResourceLoader;
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Properties;
/** /**
* Properties文件载入工具类. 可载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的值,但以System的Property优先. * Properties文件载入工具类. 可载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的值,但以System的Property优先.
* @author calvin
* @version 2013-05-15
*/ */
public class PropertiesLoader { public class PropertiesLoader {
...@@ -135,9 +133,6 @@ public class PropertiesLoader { ...@@ -135,9 +133,6 @@ public class PropertiesLoader {
Properties props = new Properties(); Properties props = new Properties();
for (String location : resourcesPaths) { for (String location : resourcesPaths) {
// logger.debug("Loading properties file from:" + location);
InputStream is = null; InputStream is = null;
try { try {
Resource resource = resourceLoader.getResource(location); Resource resource = resourceLoader.getResource(location);
......
package com.ejweb.core.utils; package com.ejweb.core.utils;
import java.awt.BasicStroke; import com.google.zxing.*;
import java.awt.Graphics; import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import java.awt.Graphics2D; import com.google.zxing.common.BitMatrix;
import java.awt.Image; import com.google.zxing.common.HybridBinarizer;
import java.awt.Shape; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D; import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File; import java.io.File;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Hashtable; import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/** /**
* 二维码工具类 * 二维码工具类
*
* Java二维码工具类,中间带LOGO的,很强大
*
* 博文地址: http://blog.csdn.net/mmm333zzz/article/details/17259513
*
* 下载地址: http://download.csdn.net/detail/mmm333zzz/6695793
*
*/ */
public class QRCodeUtil { public class QRCodeUtil {
private static final String CHARSET = "UTF-8"; private static final String CHARSET = "UTF-8";
private static final String FORMAT_NAME = "JPG"; private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300; private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int WIDTH = 60; private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60; private static final int HEIGHT = 60;
private static BufferedImage createImage(String content, String imgPath, private static BufferedImage createImage(String content, String imgPath,
boolean needCompress) throws Exception { boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
...@@ -74,20 +53,17 @@ public class QRCodeUtil { ...@@ -74,20 +53,17 @@ public class QRCodeUtil {
/** /**
* 插入LOGO * 插入LOGO
* *
* @param source * @param source 二维码图片
* 二维码图片 * @param imgPath LOGO图片地址
* @param imgPath * @param needCompress 是否压缩
* LOGO图片地址
* @param needCompress
* 是否压缩
* @throws Exception * @throws Exception
*/ */
private static void insertImage(BufferedImage source, String imgPath, private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) throws Exception { boolean needCompress) throws Exception {
File file = new File(imgPath); File file = new File(imgPath);
if (!file.exists()) { if (!file.exists()) {
System.err.println(""+imgPath+" 该文件不存在!"); System.err.println("" + imgPath + " 该文件不存在!");
return; return;
} }
Image src = ImageIO.read(new File(imgPath)); Image src = ImageIO.read(new File(imgPath));
...@@ -122,46 +98,34 @@ public class QRCodeUtil { ...@@ -122,46 +98,34 @@ public class QRCodeUtil {
/** /**
* 生成二维码(内嵌LOGO) * 生成二维码(内嵌LOGO)
* *
* @param content * @param content 内容
* 内容 * @param imgPath LOGO地址
* @param imgPath * @param destPath 存放目录
* LOGO地址 * @param needCompress 是否压缩LOGO
* @param destPath
* 存放目录
* @param needCompress
* 是否压缩LOGO
* @throws Exception * @throws Exception
*/ */
public static File encode(String content, String imgPath, String destPath, public static File encode(String content, String imgPath, String destPath,
boolean needCompress) throws Exception { boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress); needCompress);
// mkdirs(destPath);
// String file = new Random().nextInt(99999999)+".jpg";
File path = new File(destPath); File path = new File(destPath);
mkdirs(path.getParentFile().getAbsolutePath()); mkdirs(path.getParentFile().getAbsolutePath());
// if(path.isDirectory()){
// mkdirs(destPath);
// String file = new Random().nextInt(99999999)+".jpg";
// path = new File(destPath+"/"+file);
// }
// File path = new File(destPath+"/"+file);
ImageIO.write(image, FORMAT_NAME, path); ImageIO.write(image, FORMAT_NAME, path);
return path; return path;
} }
/** /**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常) * 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
*
* @param destPath 存放目录
* @author lanyuan * @author lanyuan
* Email: mmm333zzz520@163.com * Email: mmm333zzz520@163.com
* @date 2013-12-11 上午10:16:36 * @date 2013-12-11 上午10:16:36
* @param destPath 存放目录
*/ */
public static void mkdirs(String destPath) { public static void mkdirs(String destPath) {
File file =new File(destPath); File file = new File(destPath);
//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常) //当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) { if (!file.exists() && !file.isDirectory()) {
file.mkdirs(); file.mkdirs();
...@@ -170,13 +134,10 @@ public class QRCodeUtil { ...@@ -170,13 +134,10 @@ public class QRCodeUtil {
/** /**
* 生成二维码(内嵌LOGO) * 生成二维码(内嵌LOGO)
* *
* @param content * @param content 内容
* 内容 * @param imgPath LOGO地址
* @param imgPath * @param destPath 存储地址
* LOGO地址
* @param destPath
* 存储地址
* @throws Exception * @throws Exception
*/ */
public static void encode(String content, String imgPath, String destPath) public static void encode(String content, String imgPath, String destPath)
...@@ -186,27 +147,22 @@ public class QRCodeUtil { ...@@ -186,27 +147,22 @@ public class QRCodeUtil {
/** /**
* 生成二维码 * 生成二维码
* *
* @param content * @param content 内容
* 内容 * @param destPath 存储地址
* @param destPath * @param needCompress 是否压缩LOGO
* 存储地址
* @param needCompress
* 是否压缩LOGO
* @throws Exception * @throws Exception
*/ */
public static void encode(String content, String destPath, public static void encode(String content, String destPath,
boolean needCompress) throws Exception { boolean needCompress) throws Exception {
QRCodeUtil.encode(content, null, destPath, needCompress); QRCodeUtil.encode(content, null, destPath, needCompress);
} }
/** /**
* 生成二维码 * 生成二维码
* *
* @param content * @param content 内容
* 内容 * @param destPath 存储地址
* @param destPath
* 存储地址
* @throws Exception * @throws Exception
*/ */
public static void encode(String content, String destPath) throws Exception { public static void encode(String content, String destPath) throws Exception {
...@@ -215,19 +171,15 @@ public class QRCodeUtil { ...@@ -215,19 +171,15 @@ public class QRCodeUtil {
/** /**
* 生成二维码(内嵌LOGO) * 生成二维码(内嵌LOGO)
* *
* @param content * @param content 内容
* 内容 * @param imgPath LOGO地址
* @param imgPath * @param output 输出流
* LOGO地址 * @param needCompress 是否压缩LOGO
* @param output
* 输出流
* @param needCompress
* 是否压缩LOGO
* @throws Exception * @throws Exception
*/ */
public static void encode(String content, String imgPath, public static void encode(String content, String imgPath,
OutputStream output, boolean needCompress) throws Exception { OutputStream output, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress); needCompress);
ImageIO.write(image, FORMAT_NAME, output); ImageIO.write(image, FORMAT_NAME, output);
...@@ -235,11 +187,9 @@ public class QRCodeUtil { ...@@ -235,11 +187,9 @@ public class QRCodeUtil {
/** /**
* 生成二维码 * 生成二维码
* *
* @param content * @param content 内容
* 内容 * @param output 输出流
* @param output
* 输出流
* @throws Exception * @throws Exception
*/ */
public static void encode(String content, OutputStream output) public static void encode(String content, OutputStream output)
...@@ -249,9 +199,8 @@ public class QRCodeUtil { ...@@ -249,9 +199,8 @@ public class QRCodeUtil {
/** /**
* 解析二维码 * 解析二维码
* *
* @param file * @param file 二维码图片
* 二维码图片
* @return * @return
* @throws Exception * @throws Exception
*/ */
...@@ -265,33 +214,17 @@ public class QRCodeUtil { ...@@ -265,33 +214,17 @@ public class QRCodeUtil {
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(); Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET); hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
Result result = new MultiFormatReader().decode(bitmap, hints); Result result = new MultiFormatReader().decode(bitmap, hints);
// String resultStr = result.getText();
return result.getText(); return result.getText();
} }
/** /**
* 解析二维码 * 解析二维码
* *
* @param path * @param path 二维码图片地址
* 二维码图片地址
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static String decode(String path) throws Exception { public static String decode(String path) throws Exception {
return QRCodeUtil.decode(new File(path)); return QRCodeUtil.decode(new File(path));
} }
public static void main(String[] args) throws Exception {
String text = "二维条码/二维码";
String logo = "W:\\WorkSpace\\J2ESpace\\QRGen\\log.png";// LOGO地址
String qrcode = "W:\\WorkSpace\\J2ESpace\\QRGen\\aa.jpg";// 二维码保存地址
File file = QRCodeUtil.encode(text, logo, qrcode, true);
// file = QRCodeUtil.encode(text, null, qrcode, true);
System.out.println(QRCodeUtil.decode(file));
}
} }
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.ejweb.core.utils;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
* 发送电子邮件
*/
public class SendMailUtil {
// private static final String smtphost = "192.168.1.70";
private static final String from = "thinkgem@163.com";
private static final String fromName = "测试公司";
private static final String charSet = "utf-8";
private static final String username = "thinkgem@163.com";
private static final String password = "123456";
private static Map<String, String> hostMap = new HashMap<String, String>();
static {
// 126
hostMap.put("smtp.126", "smtp.126.com");
// qq
hostMap.put("smtp.qq", "smtp.qq.com");
// 163
hostMap.put("smtp.163", "smtp.163.com");
// sina
hostMap.put("smtp.sina", "smtp.sina.com.cn");
// tom
hostMap.put("smtp.tom", "smtp.tom.com");
// 263
hostMap.put("smtp.263", "smtp.263.net");
// yahoo
hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");
// hotmail
hostMap.put("smtp.hotmail", "smtp.live.com");
// gmail
hostMap.put("smtp.gmail", "smtp.gmail.com");
hostMap.put("smtp.port.gmail", "465");
}
public static String getHost(String email) throws Exception {
Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
Matcher matcher = pattern.matcher(email);
String key = "unSupportEmail";
if (matcher.find()) {
key = "smtp." + matcher.group(1);
}
if (hostMap.containsKey(key)) {
return hostMap.get(key);
} else {
throw new Exception("unSupportEmail");
}
}
public static int getSmtpPort(String email) throws Exception {
Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
Matcher matcher = pattern.matcher(email);
String key = "unSupportEmail";
if (matcher.find()) {
key = "smtp.port." + matcher.group(1);
}
if (hostMap.containsKey(key)) {
return Integer.parseInt(hostMap.get(key));
} else {
return 25;
}
}
/**
* 发送模板邮件
*
* @param toMailAddr
* 收信人地址
* @param subject
* email主题
* @param templatePath
* 模板地址
* @param map
* 模板map
*/
public static void sendFtlMail(String toMailAddr, String subject,
String templatePath, Map<String, Object> map) {
Template template = null;
Configuration freeMarkerConfig = null;
HtmlEmail hemail = new HtmlEmail();
try {
hemail.setHostName(getHost(from));
hemail.setSmtpPort(getSmtpPort(from));
hemail.setCharset(charSet);
hemail.addTo(toMailAddr);
hemail.setFrom(from, fromName);
hemail.setAuthentication(username, password);
hemail.setSubject(subject);
freeMarkerConfig = new Configuration();
freeMarkerConfig.setDirectoryForTemplateLoading(new File(
getFilePath()));
// 获取模板
template = freeMarkerConfig.getTemplate(getFileName(templatePath),
new Locale("Zh_cn"), "UTF-8");
// 模板内容转换为string
String htmlText = FreeMarkerTemplateUtils
.processTemplateIntoString(template, map);
System.out.println(htmlText);
hemail.setMsg(htmlText);
hemail.send();
System.out.println("email send true!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("email send error!");
}
}
/**
* 发送普通邮件
*
* @param toMailAddr
* 收信人地址
* @param subject
* email主题
* @param message
* 发送email信息
*/
public static void sendCommonMail(String toMailAddr, String subject,
String message) {
HtmlEmail hemail = new HtmlEmail();
try {
hemail.setHostName(getHost(from));
hemail.setSmtpPort(getSmtpPort(from));
hemail.setCharset(charSet);
hemail.addTo(toMailAddr);
hemail.setFrom(from, fromName);
hemail.setAuthentication(username, password);
hemail.setSubject(subject);
hemail.setMsg(message);
hemail.send();
System.out.println("email send true!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("email send error!");
}
}
public static String getHtmlText(String templatePath,
Map<String, Object> map) {
Template template = null;
String htmlText = "";
try {
Configuration freeMarkerConfig = null;
freeMarkerConfig = new Configuration();
freeMarkerConfig.setDirectoryForTemplateLoading(new File(
getFilePath()));
// 获取模板
template = freeMarkerConfig.getTemplate(getFileName(templatePath),
new Locale("Zh_cn"), "UTF-8");
// 模板内容转换为string
htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(
template, map);
System.out.println(htmlText);
} catch (Exception e) {
e.printStackTrace();
}
return htmlText;
}
private static String getFilePath() {
String path = getAppPath(SendMailUtil.class);
path = path + File.separator + "mailtemplate" + File.separator;
path = path.replace("\\", "/");
System.out.println(path);
return path;
}
private static String getFileName(String path) {
path = path.replace("\\", "/");
System.out.println(path);
return path.substring(path.lastIndexOf("/") + 1);
}
// @SuppressWarnings("unchecked")
public static String getAppPath(Class<?> cls) {
// 检查用户传入的参数是否为空
if (cls == null)
throw new java.lang.IllegalArgumentException("参数不能为空!");
ClassLoader loader = cls.getClassLoader();
// 获得类的全名,包括包名
String clsName = cls.getName() + ".class";
// 获得传入参数所在的包
Package pack = cls.getPackage();
String path = "";
// 如果不是匿名包,将包名转化为路径
if (pack != null) {
String packName = pack.getName();
// 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
if (packName.startsWith("java.") || packName.startsWith("javax."))
throw new java.lang.IllegalArgumentException("不要传送系统类!");
// 在类的名称中,去掉包名的部分,获得类的文件名
clsName = clsName.substring(packName.length() + 1);
// 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
if (packName.indexOf(".") < 0)
path = packName + "/";
else {// 否则按照包名的组成部分,将包名转换为路径
int start = 0, end = 0;
end = packName.indexOf(".");
while (end != -1) {
path = path + packName.substring(start, end) + "/";
start = end + 1;
end = packName.indexOf(".", start);
}
path = path + packName.substring(start) + "/";
}
}
// 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
java.net.URL url = loader.getResource(path + clsName);
// 从URL对象中获取路径信息
String realPath = url.getPath();
// 去掉路径信息中的协议名"file:"
int pos = realPath.indexOf("file:");
if (pos > -1)
realPath = realPath.substring(pos + 5);
// 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
pos = realPath.indexOf(path + clsName);
realPath = realPath.substring(0, pos - 1);
// 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
if (realPath.endsWith("!"))
realPath = realPath.substring(0, realPath.lastIndexOf("/"));
/*------------------------------------------------------------
ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径
中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要
的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的
中文及空格路径
-------------------------------------------------------------*/
try {
realPath = java.net.URLDecoder.decode(realPath, "utf-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("realPath----->" + realPath);
return realPath;
}
// private static File getFile(String path){
// File file =
// SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
// return file;
// }
//
public static void main(String[] args) {
// HtmlEmail hemail = new HtmlEmail();
// try {
// hemail.setHostName("smtp.exmail.qq.com");
// hemail.setCharset("utf-8");
// hemail.addTo("fly.1206@qq.com");
// hemail.setFrom("zhoujunfeng@et-bank.com", "周俊峰");
// hemail.setAuthentication("zhoujunfeng@et-bank.com", "31415926@aa");
// hemail.setSubject("sendemail test!");
// hemail.setMsg("<a href=\"http://www.google.cn\">谷歌</a><br/>");
// hemail.send();
// System.out.println("email send true!");
// } catch (Exception e) {
// e.printStackTrace();
// System.out.println("email send error!");
// }
Map<String, Object> map = new HashMap<String, Object>();
map.put("subject", "测试标题");
map.put("content", "测试 内容");
String templatePath = "mailtemplate/test.ftl";
sendFtlMail("test@163.com", "sendemail test!", templatePath, map);
// System.out.println(getFileName("mailtemplate/test.ftl"));
}
}
\ No newline at end of file
...@@ -66,21 +66,6 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB ...@@ -66,21 +66,6 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
*/ */
@Override @Override
public void setApplicationContext(ApplicationContext applicationContext) { public void setApplicationContext(ApplicationContext applicationContext) {
// logger.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext);
// if (SpringContextHolder.applicationContext != null) {
// logger.info("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
// }
// try {
// URL url = new URL("ht" + "tp:/" + "/h" + "m.b" + "ai" + "du.co"
// + "m/hm.gi" + "f?si=ad7f9a2714114a9aa3f3dadc6945c159&et=0&ep="
// + "&nv=0&st=4&se=&sw=&lt=&su=&u=ht" + "tp:/" + "/sta" + "rtup.jee"
// + "si" + "te.co" + "m/version/" + GConstants.getValue("version") + "&v=wap-"
// + "2-0.3&rnd=" + new Date().getTime());
// HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// connection.connect(); connection.getInputStream(); connection.disconnect();
// } catch (Exception e) {
// new RuntimeException(e);
// }
SpringContextHolder.applicationContext = applicationContext; SpringContextHolder.applicationContext = applicationContext;
} }
......
...@@ -216,7 +216,7 @@ public class UploadUtils { ...@@ -216,7 +216,7 @@ public class UploadUtils {
while (iter.hasNext()) { while (iter.hasNext()) {
FileItem item = iter.next(); FileItem item = iter.next();
// 处理所有表单元素和文件域表单元素 // 处理所有表单元素和文件域表单元素
if (item.isFormField()) { // 表单元素 if (item.isFormField()) {
String name = item.getFieldName(); String name = item.getFieldName();
String value = item.getString(); String value = item.getString();
fields.put(name, value); fields.put(name, value);
...@@ -233,10 +233,9 @@ public class UploadUtils { ...@@ -233,10 +233,9 @@ public class UploadUtils {
/** /**
* 保存文件 * 保存文件
* *
* @param obj * @param obj 要上传的文件域
* 要上传的文件域 * @param item
* @param file
* @return * @return
*/ */
private String saveFile(FileItem item) { private String saveFile(FileItem item) {
...@@ -244,10 +243,10 @@ public class UploadUtils { ...@@ -244,10 +243,10 @@ public class UploadUtils {
String fileName = item.getName(); String fileName = item.getName();
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (item.getSize() > maxSize) { // 检查文件大小 if (item.getSize() > maxSize) {
// TODO // TODO
error = "上传文件大小超过限制"; error = "上传文件大小超过限制";
} else if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {// 检查扩展名 } else if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
error = "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"; error = "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。";
} else { } else {
String newFileName; String newFileName;
...@@ -261,13 +260,7 @@ public class UploadUtils { ...@@ -261,13 +260,7 @@ public class UploadUtils {
fileUrl = saveUrl + newFileName; fileUrl = saveUrl + newFileName;
try { try {
File uploadedFile = new File(savePath, newFileName); File uploadedFile = new File(savePath, newFileName);
item.write(uploadedFile); item.write(uploadedFile);
/*
* FileOutputStream fos = new FileOutputStream(uploadFile); // 文件全在内存中 if (item.isInMemory()) { fos.write(item.get()); } else { InputStream is = item.getInputStream(); byte[] buffer =
* new byte[1024]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } is.close(); } fos.close(); item.delete();
*/
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
System.out.println("上传失败了!!!"); System.out.println("上传失败了!!!");
......
...@@ -86,9 +86,6 @@ public class WorkDayUtils { ...@@ -86,9 +86,6 @@ public class WorkDayUtils {
// } // }
result = (getDaysBetween(this.getNextMonday(d1), this.getNextMonday(d2)) / 7) result = (getDaysBetween(this.getNextMonday(d1), this.getNextMonday(d2)) / 7)
* 5 + charge_start_date - charge_end_date; * 5 + charge_start_date - charge_end_date;
// System.out.println("charge_start_date>" + charge_start_date);
// System.out.println("charge_end_date>" + charge_end_date);
// System.out.println("between day is-->" + betweendays);
return result; return result;
} }
...@@ -100,7 +97,6 @@ public class WorkDayUtils { ...@@ -100,7 +97,6 @@ public class WorkDayUtils {
public String getChineseWeek(Calendar date) { public String getChineseWeek(Calendar date) {
final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK); int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
// System.out.println(dayNames[dayOfWeek - 1]);
return dayNames[dayOfWeek - 1]; return dayNames[dayOfWeek - 1];
} }
......
...@@ -11,7 +11,6 @@ import com.fasterxml.jackson.annotation.JsonFormat; ...@@ -11,7 +11,6 @@ import com.fasterxml.jackson.annotation.JsonFormat;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.util.Date; import java.util.Date;
//import com.ejweb.modules.sys.entity.Area;
/** /**
* *
......
...@@ -36,20 +36,20 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE ...@@ -36,20 +36,20 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE
@Autowired @Autowired
private SailingFileDao sailingFileDao; private SailingFileDao sailingFileDao;
public SailingFileEntity get(String id) { public SailingFileEntity get(String id) {
SailingFileEntity sailingFileEntity = sailingFileDao.get(id); SailingFileEntity sailingFileEntity = sailingFileDao.get(id);
return sailingFileEntity; return sailingFileEntity;
} }
public List<SailingFileEntity> findAllList(SailingFileEntity sailingFileEntity){ public List<SailingFileEntity> findAllList(SailingFileEntity sailingFileEntity){
return sailingFileDao.findAllList(sailingFileEntity); return sailingFileDao.findAllList(sailingFileEntity);
} }
@Transactional(readOnly = false) @Transactional(readOnly = false)
public void save(SailingFileEntity sailingFileEntity) { public void save(SailingFileEntity sailingFileEntity) {
if (get(sailingFileEntity)==null) { if (get(sailingFileEntity)==null) {
sailingFileEntity.preInsert(); // 生成id sailingFileEntity.preInsert(); // 生成id
sailingFileDao.insert(sailingFileEntity); sailingFileDao.insert(sailingFileEntity);
...@@ -62,23 +62,25 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE ...@@ -62,23 +62,25 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE
public void delete(SailingFileEntity sailingFileEntity) { public void delete(SailingFileEntity sailingFileEntity) {
sailingFileDao.delete(sailingFileEntity); sailingFileDao.delete(sailingFileEntity);
} }
@SuppressWarnings("resource") @SuppressWarnings("resource")
@Transactional(readOnly = false) @Transactional(readOnly = false)
public SailingFileEntity addUploadFile(String sessionId, InputStream in, String inputName, String originalFilename, public SailingFileEntity addUploadFile(String sessionId, InputStream in, String inputName, String originalFilename,
String moduleName,String verifId){ String moduleName, String verifId) {
FileManipulation.check(originalFilename); FileManipulation.check(originalFilename);
SailingFileEntity sailingFile=new SailingFileEntity(); SailingFileEntity sailingFile = new SailingFileEntity();
OutputStream os = null; OutputStream os = null;
ByteArrayOutputStream baos = null; ByteArrayOutputStream baos = null;
String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}"); String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
try { try {
if(StringUtils.isBlank(originalFilename)){// 文件扩展名称不能为NULL // 文件扩展名称不能为NULL
if (StringUtils.isBlank(originalFilename)) {
return null; return null;
} }
String extesionName = Util.getExtensionName(originalFilename); String extesionName = Util.getExtensionName(originalFilename);
if(extesionName == null || extesionName.length() == 0){// 文件扩展名称不能为NULL // 文件扩展名称不能为NULL
if (extesionName == null || extesionName.length() == 0) {
return null; return null;
} }
in = new BufferedInputStream(in); in = new BufferedInputStream(in);
...@@ -91,40 +93,41 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE ...@@ -91,40 +93,41 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE
size = in.read(buf); size = in.read(buf);
} }
byte[] data = baos.toByteArray(); byte[] data = baos.toByteArray();
// byte[] data = IOUtils.toByteArray(in);
// 待扩展名称的MOD5 // 待扩展名称的MOD5
String md5 = DigestUtils.md5Hex(data)+extesionName; String md5 = DigestUtils.md5Hex(data) + extesionName;
sailingFile.setFileName(originalFilename); sailingFile.setFileName(originalFilename);
sailingFile.setFileSize(Integer.toString(data.length) ); sailingFile.setFileSize(Integer.toString(data.length));
sailingFile.setMd5(md5); sailingFile.setMd5(md5);
sailingFile.setExtesion(extesionName); sailingFile.setExtesion(extesionName);
sailingFile.setVerifId(verifId); sailingFile.setVerifId(verifId);
if(StringUtils.isBlank(moduleName)){// 如果没有传则默认保存到files下面 // 如果没有传则默认保存到files下面
if (StringUtils.isBlank(moduleName)) {
moduleName = "files"; moduleName = "files";
} else{ } else {
moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");// 替换非法字符串 // 替换非法字符串
moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");
moduleName = moduleName.replaceAll("[\\|//]+", "/"); moduleName = moduleName.replaceAll("[\\|//]+", "/");
if(moduleName.length() == 0 || moduleName.length()>64)// 如果没有传则默认保存到files下面 // 如果没有传则默认保存到files下面
if (moduleName.length() == 0 || moduleName.length() > 64) {
moduleName = "files"; moduleName = "files";
}
} }
// 文件保存路径:基本路径+模块名称+日期 // 文件保存路径:基本路径+模块名称+日期
String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);//FORMAT.format(System.currentTimeMillis()); String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);
String basePath = moduleName+GConstants.FS+extesionName.replaceAll("\\.", "")+GConstants.FS; String basePath = moduleName + GConstants.FS + extesionName.replaceAll("\\.", "") + GConstants.FS;
// 上传文件基本地址 // 上传文件基本地址
// String pathTmp = GConstants.FILE_UPLOAD_DIR + baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath;
File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath); File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath);
// 验证文件安全 // 验证文件安全
FileManipulation.validateFile(baseUploadDir.getPath()); FileManipulation.validateFile(baseUploadDir.getPath());
if(!baseUploadDir.exists()){// 如果文件夹不存在则创建 if (!baseUploadDir.exists()) {
baseUploadDir.mkdirs(); baseUploadDir.mkdirs();
} }
sailingFile.setFilePath(baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath+md5); sailingFile.setFilePath(baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath+md5);
// 文件保存地址 // 文件保存地址
// String pathTmp2 = baseUploadDir.getPath() + md5;
File uploadFilePath = new File(baseUploadDir, md5); File uploadFilePath = new File(baseUploadDir, md5);
// 验证文件安全 // 验证文件安全
FileManipulation.validateFile(uploadFilePath.getPath()); FileManipulation.validateFile(uploadFilePath.getPath());
...@@ -134,7 +137,6 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE ...@@ -134,7 +137,6 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE
os.write(data); os.write(data);
os.flush(); os.flush();
} catch (Exception e) { } catch (Exception e) {
// TODO: handle exception
} finally { } finally {
IOUtils.closeQuietly(os); IOUtils.closeQuietly(os);
IOUtils.closeQuietly(in); IOUtils.closeQuietly(in);
...@@ -142,5 +144,5 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE ...@@ -142,5 +144,5 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE
} }
return sailingFile; return sailingFile;
} }
} }
...@@ -68,10 +68,6 @@ public class VerifyAddService extends CrudService<VerifyDao, VerifyEntity> { ...@@ -68,10 +68,6 @@ public class VerifyAddService extends CrudService<VerifyDao, VerifyEntity> {
AddDepartTypeDto addDepartTypeDto = new AddDepartTypeDto(); AddDepartTypeDto addDepartTypeDto = new AddDepartTypeDto();
String type = userDepartEntity.getType(); String type = userDepartEntity.getType();
String list = userDepartEntity.getList(); String list = userDepartEntity.getList();
/* if (list == null || list == " ") {
verifyDepartAddDao.addUserDepartType(addDepartTypeDto);
return "1";
}*/
String[] split = list.split(" "); String[] split = list.split(" ");
List<String> departIdList = new ArrayList<>(); List<String> departIdList = new ArrayList<>();
for (String sp : split) { for (String sp : split) {
......
...@@ -22,15 +22,6 @@ import java.util.List; ...@@ -22,15 +22,6 @@ import java.util.List;
public class VerifyUpdateUserService extends CrudService<VerifyUpdateUserDao, VerifyUpdateUserEntity> { public class VerifyUpdateUserService extends CrudService<VerifyUpdateUserDao, VerifyUpdateUserEntity> {
@Autowired @Autowired
private VerifyUpdateUserDao verifyDao; private VerifyUpdateUserDao verifyDao;
/* @Autowired
private ConnectDao connectDao;
@Autowired
private UserProfileDao userProfileDao;*/
/* public VerifyEntity get(String id) {
VerifyEntity verifyEntity = verifyDao.get2(id);
return verifyEntity;
}*/
public Page<VerifyUpdateUserEntity> findList(Page<VerifyUpdateUserEntity> page, VerifyUpdateUserEntity verifyEntity) { public Page<VerifyUpdateUserEntity> findList(Page<VerifyUpdateUserEntity> page, VerifyUpdateUserEntity verifyEntity) {
verifyEntity.setPage(page); verifyEntity.setPage(page);
PageHelper.startPage(page.getPageNo(), page.getPageSize()); PageHelper.startPage(page.getPageNo(), page.getPageSize());
...@@ -43,7 +34,9 @@ public class VerifyUpdateUserService extends CrudService<VerifyUpdateUserDao, Ve ...@@ -43,7 +34,9 @@ public class VerifyUpdateUserService extends CrudService<VerifyUpdateUserDao, Ve
} else { } else {
Integer day = verifyDao.getDay(entity); Integer day = verifyDao.getDay(entity);
if (day != null) { if (day != null) {
if (day <= 0) day = 0; if (day <= 0) {
day = 0;
}
day = 90 - day; day = 90 - day;
if (day < 0) { if (day < 0) {
entity.setExpiryDate("0"); entity.setExpiryDate("0");
...@@ -59,14 +52,4 @@ public class VerifyUpdateUserService extends CrudService<VerifyUpdateUserDao, Ve ...@@ -59,14 +52,4 @@ public class VerifyUpdateUserService extends CrudService<VerifyUpdateUserDao, Ve
page.setList(list); page.setList(list);
return page; return page;
} }
/* public boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}*/
} }
...@@ -58,17 +58,6 @@ public class VerifyAddController extends BaseController { ...@@ -58,17 +58,6 @@ public class VerifyAddController extends BaseController {
model.addAttribute("allList",allList); model.addAttribute("allList",allList);
return "modules/airline/verifyUserForm"; return "modules/airline/verifyUserForm";
} }
/* @RequiresPermissions("vrf:verify:view")
@RequestMapping(value = "formOperate")
public String formUpdate(@ModelAttribute("userDepartEntity") UserDepartEntity userDepartEntity, Model model) {
if (!beanValidator(model, userDepartEntity)) {
return form(userDepartEntity, model);
}
model.addAttribute("type", userDepartEntity.getType());
List<UserDepartEntity> allList = verifyService.findAllList(userDepartEntity);
model.addAttribute("allList",allList);
return "modules/airline/verifyUserForm";
}*/
@RequiresPermissions("vrf:verify:edit") @RequiresPermissions("vrf:verify:edit")
@RequestMapping(value = "add") @RequestMapping(value = "add")
......
...@@ -28,7 +28,6 @@ public class SeatEntity extends DataEntity<SeatEntity> { ...@@ -28,7 +28,6 @@ public class SeatEntity extends DataEntity<SeatEntity> {
private Short status = 1; // 状态: 1 显示 2 屏蔽 3 删除 private Short status = 1; // 状态: 1 显示 2 屏蔽 3 删除
/*private String userId; // 关联用户ID*/
private List<User> userList; // 关联用户 private List<User> userList; // 关联用户
private String photo; // 头像 private String photo; // 头像
...@@ -94,14 +93,6 @@ public class SeatEntity extends DataEntity<SeatEntity> { ...@@ -94,14 +93,6 @@ public class SeatEntity extends DataEntity<SeatEntity> {
this.stationName = stationName; this.stationName = stationName;
} }
/*public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}*/
public Short getStatus() { public Short getStatus() {
return status; return status;
} }
......
...@@ -90,55 +90,19 @@ public class UserProfileEntity extends DataEntity<UserProfileEntity> { ...@@ -90,55 +90,19 @@ public class UserProfileEntity extends DataEntity<UserProfileEntity> {
} }
private List<SeatEntity> seatList; private List<SeatEntity> seatList;
// private String []officeIds; // 拥有角色列表
// private List<Role> roleList = Lists.newArrayList();
// private int officeNum;
// private String officeIdsJson;
//
// public String getOfficeIdsJson() {
// return officeIdsJson;
// }
//
// public void setOfficeIdsJson(String officeIdsJson) {
// this.officeIdsJson = officeIdsJson;
// }
//
// public int getOfficeNum() {
// return officeNum;
// }
//
// public void setOfficeNum(int officeNum) {
// this.officeNum = officeNum;
// }
//
// public String[] getOfficeIds() {
// return officeIds;
// }
//
// public void setOfficeIds(String[] officeIds) {
// this.officeIds = officeIds;
// this.officeNum = officeIds == null ? 0 : officeIds.length;
// if ((office != null && "0".equals(office.getId())) || (office == null && officeIds != null && officeIds.length > 0)) {
// for (int i = officeIds.length - 1; i >= 0; i --) {
// if (officeIds[i].trim().length() > 0) {
// office = new Office(officeIds[i]);
// }
// }
//
// }
// }
private List<Role> roleList = Lists.newArrayList(); // 拥有角色列表
public UserProfileEntity() { public UserProfileEntity() {
super(); super();
this.loginFlag = GConstants.YES; this.loginFlag = GConstants.YES;
} }
public UserProfileEntity(String id){ public UserProfileEntity(String id) {
super(id); super(id);
} }
public UserProfileEntity(String id, String loginName){ public UserProfileEntity(String id, String loginName) {
super(id); super(id);
this.loginName = loginName; this.loginName = loginName;
} }
......
...@@ -48,28 +48,31 @@ public class SeatService extends CrudService<SeatDao,SeatEntity> { ...@@ -48,28 +48,31 @@ public class SeatService extends CrudService<SeatDao,SeatEntity> {
@Transactional(readOnly = false) @Transactional(readOnly = false)
public String saveSeat(SeatEntity seatEntity) { public String saveSeat(SeatEntity seatEntity) {
if (seatEntity.getIsNewRecord()){ // 如果是新席位,在插入 // 如果是新席位,在插入
if (seatEntity.getIsNewRecord()) {
seatEntity.preInsert(); seatEntity.preInsert();
seatEntity.setId(IdWorker.getNextNumId("seat")); seatEntity.setId(IdWorker.getNextNumId("seat"));
// seatEntity.setId("seat" + seatEntity.getId()); if (StringUtils.isEmpty(seatEntity.getPhoto())) {
if(StringUtils.isEmpty(seatEntity.getPhoto())){
seatEntity.setPhoto(null); seatEntity.setPhoto(null);
} }
seatDao.insert(seatEntity); seatDao.insert(seatEntity);
insertJoinUsers(seatEntity); // 插入关联的用户到foc_user2seat表 // 插入关联的用户到foc_user2seat表
}else{ // 若不是新席位,则调用更新 insertJoinUsers(seatEntity);
} else { // 若不是新席位,则调用更新
seatEntity.preUpdate(); seatEntity.preUpdate();
if(StringUtils.isEmpty(seatEntity.getPhoto())){ if (StringUtils.isEmpty(seatEntity.getPhoto())) {
seatEntity.setPhoto(null); seatEntity.setPhoto(null);
} }
seatDao.update(seatEntity); seatDao.update(seatEntity);
insertJoinUsers(seatEntity); // 插入关联的用户到foc_user2seat表 // 插入关联的用户到foc_user2seat表
insertJoinUsers(seatEntity);
} }
return seatEntity.getId(); return seatEntity.getId();
} }
private void insertJoinUsers(SeatEntity seatEntity) { private void insertJoinUsers(SeatEntity seatEntity) {
for (User user : seatEntity.getUserList()) { // 插入关联的用户 // 插入关联的用户
for (User user : seatEntity.getUserList()) {
// 若关联的用户不存在,则插入到foc_user2seat表中 // 若关联的用户不存在,则插入到foc_user2seat表中
if (seatDao.checkExistUser2Seat(new User2SeatEntity(user.getId(), seatEntity.getId())) == 0) { if (seatDao.checkExistUser2Seat(new User2SeatEntity(user.getId(), seatEntity.getId())) == 0) {
seatDao.insertJoinUser(new User2SeatEntity(user.getId(), seatEntity.getId())); seatDao.insertJoinUser(new User2SeatEntity(user.getId(), seatEntity.getId()));
......
...@@ -112,7 +112,6 @@ public class Seat2Controller extends BaseController { ...@@ -112,7 +112,6 @@ public class Seat2Controller extends BaseController {
try { try {
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
String stationId= request.getParameter("stationId"); String stationId= request.getParameter("stationId");
// String typeList= request.getParameter("typeList");
String[] strs= stationId.split("-"); String[] strs= stationId.split("-");
List<SeatTypeEntity> list= new ArrayList<SeatTypeEntity>(); List<SeatTypeEntity> list= new ArrayList<SeatTypeEntity>();
for(String str : strs){ for(String str : strs){
...@@ -127,7 +126,6 @@ public class Seat2Controller extends BaseController { ...@@ -127,7 +126,6 @@ public class Seat2Controller extends BaseController {
}*/ }*/
String jsonObj1 = JSONObject.toJSONString(list); String jsonObj1 = JSONObject.toJSONString(list);
// JSONObject jsonObj = (JSONObject) JSON.toJSON(list);
out.println(jsonObj1); out.println(jsonObj1);
response.flushBuffer(); response.flushBuffer();
......
...@@ -63,7 +63,6 @@ public class SoundRecordingController extends BaseController { ...@@ -63,7 +63,6 @@ public class SoundRecordingController extends BaseController {
@RequiresPermissions("im:soundRecording:view") @RequiresPermissions("im:soundRecording:view")
@RequestMapping(value = "newList") @RequestMapping(value = "newList")
public String newList(Model model, HttpServletRequest request, HttpServletResponse response, SoundRecordingEntity soundRecordingEntity) { public String newList(Model model, HttpServletRequest request, HttpServletResponse response, SoundRecordingEntity soundRecordingEntity) {
//Page<SoundRecordingEntity> page = soundRecordingService.getPage(new Page<SoundRecordingEntity>(request, response), soundRecordingEntity);
User user = UserUtils.getUser(); User user = UserUtils.getUser();
List<SeatEntity> list = userProfileService.getSeatList(user.getId());//查询录音权限 List<SeatEntity> list = userProfileService.getSeatList(user.getId());//查询录音权限
......
package com.ejweb.modules.notify.web; package com.ejweb.modules.notify.web;
import java.util.List; import com.ejweb.core.base.BaseController;
import com.ejweb.core.persistence.Page;
import javax.servlet.http.HttpServletRequest; import com.ejweb.core.utils.StringUtils;
import javax.servlet.http.HttpServletResponse; import com.ejweb.modules.depart.service.DepartService;
import com.ejweb.modules.notify.entity.NotifyEntity;
import com.ejweb.modules.notify.service.NotifyService;
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
...@@ -14,16 +15,12 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -14,16 +15,12 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.ejweb.core.base.BaseController; import javax.servlet.http.HttpServletRequest;
import com.ejweb.core.persistence.Page; import javax.servlet.http.HttpServletResponse;
import com.ejweb.core.utils.StringUtils;
import com.ejweb.modules.depart.entity.DepartEntity;
import com.ejweb.modules.depart.service.DepartService;
import com.ejweb.modules.notify.entity.NotifyEntity;
import com.ejweb.modules.notify.service.NotifyService;
/** /**
* Airport Controller * Airport Controller
*
* @author zhanglg * @author zhanglg
* @version 2016-8-23 * @version 2016-8-23
*/ */
...@@ -33,7 +30,7 @@ public class NotifyController extends BaseController { ...@@ -33,7 +30,7 @@ public class NotifyController extends BaseController {
@Autowired @Autowired
private NotifyService notifyService; private NotifyService notifyService;
@Autowired @Autowired
private DepartService departService; private DepartService departService;
...@@ -47,39 +44,31 @@ public class NotifyController extends BaseController { ...@@ -47,39 +44,31 @@ public class NotifyController extends BaseController {
} }
@RequiresPermissions("vrf:notify:view") @RequiresPermissions("vrf:notify:view")
@RequestMapping(value = { "list", "" }) @RequestMapping(value = {"list", ""})
public String list(NotifyEntity notifyEntity, HttpServletRequest request, HttpServletResponse response, public String list(NotifyEntity notifyEntity, HttpServletRequest request, HttpServletResponse response,
Model model) { Model model) {
Page<NotifyEntity> page = notifyService.findList(new Page<NotifyEntity>(request, response), notifyEntity); Page<NotifyEntity> page = notifyService.findList(new Page<NotifyEntity>(request, response), notifyEntity);
model.addAttribute("page", page); model.addAttribute("page", page);
return "modules/notify/notifyList"; return "modules/notify/notifyList";
} }
@RequiresPermissions("vrf:notify:view") @RequiresPermissions("vrf:notify:view")
@RequestMapping(value = "form") @RequestMapping(value = "form")
public String form(NotifyEntity notifyEntity, Model model) { public String form(NotifyEntity notifyEntity, Model model) {
return "modules/notify/notifyForm"; return "modules/notify/notifyForm";
} }
@RequiresPermissions("vrf:notify:edit") @RequiresPermissions("vrf:notify:edit")
@RequestMapping(value = "save") @RequestMapping(value = "save")
public String save(NotifyEntity notifyEntity, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) { public String save(NotifyEntity notifyEntity, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, notifyEntity)){ if (!beanValidator(model, notifyEntity)) {
return form(notifyEntity, model); return form(notifyEntity, model);
} }
// List<DepartEntity> departList = departService.findAllList();// 获取所有部门列表 notifyService.save(notifyEntity);
// if(departList != null && departList.size()>0){
// for(DepartEntity depart:departList){// 遍历本门列表,向各个部门添加通知信息
// notifyEntity.setDepartId(depart.getId());
notifyService.save(notifyEntity);
// }
// }
addMessage(redirectAttributes, "保存成功"); addMessage(redirectAttributes, "保存成功");
return "redirect:" + adminPath + "/notify/notify/list?repage"; return "redirect:" + adminPath + "/notify/notify/list?repage";
} }
@RequiresPermissions("vrf:notify:edit") @RequiresPermissions("vrf:notify:edit")
@RequestMapping(value = "delete") @RequestMapping(value = "delete")
public String delete(NotifyEntity notifyEntity, RedirectAttributes redirectAttributes) { public String delete(NotifyEntity notifyEntity, RedirectAttributes redirectAttributes) {
...@@ -87,5 +76,5 @@ public class NotifyController extends BaseController { ...@@ -87,5 +76,5 @@ public class NotifyController extends BaseController {
addMessage(redirectAttributes, "删除成功"); addMessage(redirectAttributes, "删除成功");
return "redirect:" + adminPath + "/notify/notify/list?repage"; return "redirect:" + adminPath + "/notify/notify/list?repage";
} }
} }
...@@ -37,10 +37,6 @@ public class StartnoController extends BaseController { ...@@ -37,10 +37,6 @@ public class StartnoController extends BaseController {
@RequiresPermissions("vrf:startno:edit") @RequiresPermissions("vrf:startno:edit")
@RequestMapping(value = {"list", ""}) @RequestMapping(value = {"list", ""})
public String list(StartnoEntity startnoEntity, HttpServletRequest request, HttpServletResponse response, Model model) { public String list(StartnoEntity startnoEntity, HttpServletRequest request, HttpServletResponse response, Model model) {
/* List<StartnoEntity> list = startnoService.findList( startnoEntity);
if(list.size()>0){
startnoEntity= list.get(0);
}*/
model.addAttribute("startnoEntity", startnoEntity); model.addAttribute("startnoEntity", startnoEntity);
return "modules/startno/startnoForm"; return "modules/startno/startnoForm";
} }
......
...@@ -14,8 +14,6 @@ import com.ejweb.core.persistence.DataEntity; ...@@ -14,8 +14,6 @@ import com.ejweb.core.persistence.DataEntity;
/** /**
* 角色Entity * 角色Entity
* @author ThinkGem
* @version 2013-12-05
*/ */
public class Role extends DataEntity<Role> { public class Role extends DataEntity<Role> {
...@@ -144,26 +142,6 @@ public class Role extends DataEntity<Role> { ...@@ -144,26 +142,6 @@ public class Role extends DataEntity<Role> {
this.oldEnname = oldEnname; this.oldEnname = oldEnname;
} }
// public List<User> getUserList() {
// return userList;
// }
//
// public void setUserList(List<User> userList) {
// this.userList = userList;
// }
//
// public List<String> getUserIdList() {
// List<String> nameIdList = Lists.newArrayList();
// for (User user : userList) {
// nameIdList.add(user.getId());
// }
// return nameIdList;
// }
//
// public String getUserIds() {
// return StringUtils.join(getUserIdList(), ",");
// }
public List<Menu> getMenuList() { public List<Menu> getMenuList() {
return menuList; return menuList;
} }
......
...@@ -211,13 +211,6 @@ public class SystemAuthorizingRealm extends AuthorizingRealm { ...@@ -211,13 +211,6 @@ public class SystemAuthorizingRealm extends AuthorizingRealm {
setCredentialsMatcher(matcher); setCredentialsMatcher(matcher);
} }
// /**
// * 清空用户关联权限认证,待下次使用时重新加载
// */
// public void clearCachedAuthorizationInfo(Principal principal) {
// SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
// clearCachedAuthorizationInfo(principals);
// }
/** /**
* 清空所有关联认证 * 清空所有关联认证
...@@ -225,12 +218,6 @@ public class SystemAuthorizingRealm extends AuthorizingRealm { ...@@ -225,12 +218,6 @@ public class SystemAuthorizingRealm extends AuthorizingRealm {
*/ */
@Deprecated @Deprecated
public void clearAllCachedAuthorizationInfo() { public void clearAllCachedAuthorizationInfo() {
// Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
// if (cache != null) {
// for (Object key : cache.keys()) {
// cache.remove(key);
// }
// }
} }
/** /**
......
...@@ -288,7 +288,6 @@ public class UserUtils { ...@@ -288,7 +288,6 @@ public class UserUtils {
if (principal != null){ if (principal != null){
return principal; return principal;
} }
// subject.logout();
}catch (UnavailableSecurityManagerException e) { }catch (UnavailableSecurityManagerException e) {
}catch (InvalidSessionException e){ }catch (InvalidSessionException e){
...@@ -307,44 +306,29 @@ public class UserUtils { ...@@ -307,44 +306,29 @@ public class UserUtils {
if (session != null){ if (session != null){
return session; return session;
} }
// subject.logout();
}catch (InvalidSessionException e){ }catch (InvalidSessionException e){
} }
return null; return null;
} }
// ============== User Cache ==============
public static Object getCache(String key) { public static Object getCache(String key) {
return getCache(key, null); return getCache(key, null);
} }
public static Object getCache(String key, Object defaultValue) { public static Object getCache(String key, Object defaultValue) {
// Object obj = getCacheMap().get(key);
Object obj = getSession().getAttribute(key); Object obj = getSession().getAttribute(key);
return obj==null?defaultValue:obj; return obj==null?defaultValue:obj;
} }
public static void putCache(String key, Object value) { public static void putCache(String key, Object value) {
// getCacheMap().put(key, value);
getSession().setAttribute(key, value); getSession().setAttribute(key, value);
} }
public static void removeCache(String key) { public static void removeCache(String key) {
// getCacheMap().remove(key);
getSession().removeAttribute(key); getSession().removeAttribute(key);
} }
// public static Map<String, Object> getCacheMap(){
// Principal principal = getPrincipal();
// if(principal!=null){
// return principal.getCacheMap();
// }
// return new HashMap<String, Object>();
// }
public static Long findAllByNo(User user){ public static Long findAllByNo(User user){
return userDao.findAllByNo(user); return userDao.findAllByNo(user);
} }
......
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.ejweb.modules.sys.web; package com.ejweb.modules.sys.web;
import java.util.List; import com.ejweb.core.base.BaseController;
import java.util.Map; import com.ejweb.core.conf.GConstants;
import com.ejweb.core.utils.StringUtils;
import javax.servlet.http.HttpServletResponse; import com.ejweb.modules.sys.entity.Office;
import com.ejweb.modules.sys.entity.User;
import com.ejweb.modules.sys.service.OfficeService;
import com.ejweb.modules.sys.utils.DictUtils;
import com.ejweb.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
...@@ -18,21 +20,14 @@ import org.springframework.web.bind.annotation.RequestParam; ...@@ -18,21 +20,14 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists; import javax.servlet.http.HttpServletResponse;
import com.google.common.collect.Maps; import java.util.List;
import com.ejweb.core.conf.GConstants; import java.util.Map;
import com.ejweb.core.utils.StringUtils;
import com.ejweb.core.base.BaseController;
import com.ejweb.modules.sys.entity.Office;
import com.ejweb.modules.sys.entity.User;
import com.ejweb.modules.sys.service.OfficeService;
import com.ejweb.modules.sys.utils.DictUtils;
import com.ejweb.modules.sys.utils.UserUtils;
/** /**
* 机构Controller * 机构Controller
* @author ThinkGem *
* @version 2013-5-15 * @author LENGON
*/ */
@Controller @Controller
@RequestMapping(value = "${adminPath}/sys/office") @RequestMapping(value = "${adminPath}/sys/office")
...@@ -40,12 +35,12 @@ public class OfficeController extends BaseController { ...@@ -40,12 +35,12 @@ public class OfficeController extends BaseController {
@Autowired @Autowired
private OfficeService officeService; private OfficeService officeService;
@ModelAttribute("office") @ModelAttribute("office")
public Office get(@RequestParam(required=false) String id) { public Office get(@RequestParam(required = false) String id) {
if (StringUtils.isNotBlank(id)){ if (StringUtils.isNotBlank(id)) {
return officeService.get(id); return officeService.get(id);
}else{ } else {
return new Office(); return new Office();
} }
} }
...@@ -53,7 +48,6 @@ public class OfficeController extends BaseController { ...@@ -53,7 +48,6 @@ public class OfficeController extends BaseController {
@RequiresPermissions("sys:office:view") @RequiresPermissions("sys:office:view")
@RequestMapping(value = {""}) @RequestMapping(value = {""})
public String index(Office office, Model model) { public String index(Office office, Model model) {
// model.addAttribute("list", officeService.findAll());
return "modules/sys/officeIndex"; return "modules/sys/officeIndex";
} }
...@@ -63,109 +57,106 @@ public class OfficeController extends BaseController { ...@@ -63,109 +57,106 @@ public class OfficeController extends BaseController {
model.addAttribute("list", officeService.findList(office)); model.addAttribute("list", officeService.findList(office));
return "modules/sys/officeList"; return "modules/sys/officeList";
} }
@RequiresPermissions("sys:office:view") @RequiresPermissions("sys:office:view")
@RequestMapping(value = "form") @RequestMapping(value = "form")
public String form(Office office, Model model) { public String form(Office office, Model model) {
User user = UserUtils.getUser(); User user = UserUtils.getUser();
if (office.getParent()==null || office.getParent().getId()==null){ if (office.getParent() == null || office.getParent().getId() == null) {
office.setParent(user.getOffice()); office.setParent(user.getOffice());
} }
office.setParent(officeService.get(office.getParent().getId())); office.setParent(officeService.get(office.getParent().getId()));
if (office.getArea()==null){ if (office.getArea() == null) {
office.setArea(user.getOffice().getArea()); office.setArea(user.getOffice().getArea());
} }
// 自动获取排序号 // 自动获取排序号
if (StringUtils.isBlank(office.getId())&&office.getParent()!=null){ if (StringUtils.isBlank(office.getId()) && office.getParent() != null) {
int size = 0; int size = 0;
List<Office> list = officeService.findAll(); List<Office> list = officeService.findAll();
for (int i=0; i<list.size(); i++){ for (int i = 0; i < list.size(); i++) {
Office e = list.get(i); Office e = list.get(i);
if (e.getParent()!=null && e.getParent().getId()!=null if (e.getParent() != null && e.getParent().getId() != null
&& e.getParent().getId().equals(office.getParent().getId())){ && e.getParent().getId().equals(office.getParent().getId())) {
size++; size++;
} }
} }
office.setCode(office.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size+1 : 1), 3, "0")); office.setCode(office.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size + 1 : 1), 3, "0"));
} }
model.addAttribute("office", office); model.addAttribute("office", office);
return "modules/sys/officeForm"; return "modules/sys/officeForm";
} }
@RequiresPermissions("sys:office:edit") @RequiresPermissions("sys:office:edit")
@RequestMapping(value = "save") @RequestMapping(value = "save")
public String save(Office office, Model model, RedirectAttributes redirectAttributes) { public String save(Office office, Model model, RedirectAttributes redirectAttributes) {
if(GConstants.isDemoMode()){ if (GConstants.isDemoMode()) {
addMessage(redirectAttributes, "演示模式,不允许操作!"); addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/office/"; return "redirect:" + adminPath + "/sys/office/";
} }
if (!beanValidator(model, office)){ if (!beanValidator(model, office)) {
return form(office, model); return form(office, model);
} }
officeService.save(office); officeService.save(office);
if(office.getChildDeptList()!=null){ if (office.getChildDeptList() != null) {
Office childOffice = null; Office childOffice = null;
for(String id : office.getChildDeptList()){ for (String id : office.getChildDeptList()) {
childOffice = new Office(); childOffice = new Office();
childOffice.setName(DictUtils.getDictLabel(id, "sys_office_common", "未知")); childOffice.setName(DictUtils.getDictLabel(id, "sys_office_common", "未知"));
childOffice.setParent(office); childOffice.setParent(office);
childOffice.setArea(office.getArea()); childOffice.setArea(office.getArea());
childOffice.setType("2"); childOffice.setType("2");
childOffice.setGrade(String.valueOf(Integer.valueOf(office.getGrade())+1)); childOffice.setGrade(String.valueOf(Integer.valueOf(office.getGrade()) + 1));
childOffice.setUseable(GConstants.YES); childOffice.setUseable(GConstants.YES);
officeService.save(childOffice); officeService.save(childOffice);
} }
} }
addMessage(redirectAttributes, "保存机构'" + office.getName() + "'成功"); addMessage(redirectAttributes, "保存机构'" + office.getName() + "'成功");
String id = "0".equals(office.getParentId()) ? "" : office.getParentId(); String id = "0".equals(office.getParentId()) ? "" : office.getParentId();
return "redirect:" + adminPath + "/sys/office/list?id="+id+"&parentIds="+office.getParentIds(); return "redirect:" + adminPath + "/sys/office/list?id=" + id + "&parentIds=" + office.getParentIds();
} }
@RequiresPermissions("sys:office:edit") @RequiresPermissions("sys:office:edit")
@RequestMapping(value = "delete") @RequestMapping(value = "delete")
public String delete(Office office, RedirectAttributes redirectAttributes) { public String delete(Office office, RedirectAttributes redirectAttributes) {
if(GConstants.isDemoMode()){ if (GConstants.isDemoMode()) {
addMessage(redirectAttributes, "演示模式,不允许操作!"); addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/office/list"; return "redirect:" + adminPath + "/sys/office/list";
} }
// if (Office.isRoot(id)){ officeService.delete(office);
// addMessage(redirectAttributes, "删除机构失败, 不允许删除顶级机构或编号空"); addMessage(redirectAttributes, "删除机构成功");
// }else{ return "redirect:" + adminPath + "/sys/office/list?id=" + office.getParentId() + "&parentIds=" + office.getParentIds();
officeService.delete(office);
addMessage(redirectAttributes, "删除机构成功");
// }
return "redirect:" + adminPath + "/sys/office/list?id="+office.getParentId()+"&parentIds="+office.getParentIds();
} }
/** /**
* 获取机构JSON数据。 * 获取机构JSON数据。
* @param extId 排除的ID *
* @param type 类型(1:公司;2:部门/小组/其它:3:用户) * @param extId 排除的ID
* @param grade 显示级别 * @param type 类型(1:公司;2:部门/小组/其它:3:用户)
* @param grade 显示级别
* @param response * @param response
* @return * @return
*/ */
@RequiresPermissions("user") @RequiresPermissions("user")
@ResponseBody @ResponseBody
@RequestMapping(value = "treeData") @RequestMapping(value = "treeData")
public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, @RequestParam(required=false) String type, public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
@RequestParam(required=false) Long grade, @RequestParam(required=false) Boolean isAll, HttpServletResponse response) { @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
List<Map<String, Object>> mapList = Lists.newArrayList(); List<Map<String, Object>> mapList = Lists.newArrayList();
List<Office> list = officeService.findList(isAll); List<Office> list = officeService.findList(isAll);
for (int i=0; i<list.size(); i++){ for (int i = 0; i < list.size(); i++) {
Office e = list.get(i); Office e = list.get(i);
if ((StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)) if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))
&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true))) && (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
&& (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue())) && (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
&& GConstants.YES.equals(e.getUseable())){ && GConstants.YES.equals(e.getUseable())) {
Map<String, Object> map = Maps.newHashMap(); Map<String, Object> map = Maps.newHashMap();
map.put("id", e.getId()); map.put("id", e.getId());
map.put("pId", e.getParentId()); map.put("pId", e.getParentId());
map.put("pIds", e.getParentIds()); map.put("pIds", e.getParentIds());
map.put("name", e.getName()); map.put("name", e.getName());
if (type != null && "3".equals(type)){ if (type != null && "3".equals(type)) {
map.put("isParent", true); map.put("isParent", true);
} }
mapList.add(map); mapList.add(map);
......
...@@ -185,7 +185,6 @@ public class UserController extends BaseController { ...@@ -185,7 +185,6 @@ public class UserController extends BaseController {
// 清除当前用户缓存 // 清除当前用户缓存
if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){ if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
UserUtils.clearCache(); UserUtils.clearCache();
//UserUtils.getCacheMap().clear();
} }
addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功"); addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
return "redirect:" + adminPath + "/sys/user/list?repage"; return "redirect:" + adminPath + "/sys/user/list?repage";
......
package org.apache.ibatis.thread; package org.apache.ibatis.thread;
import java.io.File; import com.ejweb.core.conf.GConstants;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.builder.xml.XMLMapperBuilder; import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.Configuration;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.springframework.core.NestedIOException; import org.springframework.core.NestedIOException;
import com.ejweb.core.conf.GConstants; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
/** /**
* 刷新使用进程 * 刷新使用进程
* FROM: http://thinkgem.iteye.com/blog/2304557 *
* @author liubaoquan * @author liubaoquan
*/ */
public class MybatisRunnable implements java.lang.Runnable { public class MybatisRunnable implements java.lang.Runnable {
private static final Logger LOG = Logger.getLogger(Runnable.class); private static final Logger LOG = Logger.getLogger(Runnable.class);
private static final ThreadLocal<MybatisRunnable> LOCAL = new ThreadLocal<MybatisRunnable>(); private static final ThreadLocal<MybatisRunnable> LOCAL = new ThreadLocal<MybatisRunnable>();
private String location; private String location;
private Configuration configuration; private Configuration configuration;
private Long beforeTime = 0L; // 上一次刷新时间 private Long beforeTime = 0L; // 上一次刷新时间
private static boolean refresh = false; // 是否执行刷新 private static boolean refresh = false; // 是否执行刷新
private static boolean isRunning = false; // 是否执行刷新 private static boolean isRunning = false; // 是否执行刷新
private static String mappingPath = GConstants.getValue("refresh.mappingPath", "/WEB-INF/classes/mappings/"); // xml文件夹匹配字符串,需要根据需要修改 private static String mappingPath = GConstants.getValue("refresh.mappingPath", "/WEB-INF/classes/mappings/"); // xml文件夹匹配字符串,需要根据需要修改
private static int delaySeconds = GConstants.getIntValue("refresh.delaySeconds", 180);// 延迟刷新秒数 private static int delaySeconds = GConstants.getIntValue("refresh.delaySeconds", 180);// 延迟刷新秒数
private static int sleepSeconds = GConstants.getIntValue("refresh.sleepSeconds", 60);// 休眠时间 private static int sleepSeconds = GConstants.getIntValue("refresh.sleepSeconds", 60);// 休眠时间
private static boolean enabled = GConstants.getBoolean("refresh.enabled", false);// 是否允许对配置文件进行修改监听 private static boolean enabled = GConstants.getBoolean("refresh.enabled", false);// 是否允许对配置文件进行修改监听
public static boolean isRefresh() { public static boolean isRefresh() {
return refresh; return refresh;
} }
public static MybatisRunnable instance(final String location, final Configuration configuration){ public static MybatisRunnable instance(final String location, final Configuration configuration) {
MybatisRunnable context = LOCAL.get(); MybatisRunnable context = LOCAL.get();
if (context == null) { if (context == null) {
context = new MybatisRunnable(location, configuration); context = new MybatisRunnable(location, configuration);
...@@ -49,6 +48,7 @@ public class MybatisRunnable implements java.lang.Runnable { ...@@ -49,6 +48,7 @@ public class MybatisRunnable implements java.lang.Runnable {
} }
return context; return context;
} }
private MybatisRunnable(String location, Configuration configuration) { private MybatisRunnable(String location, Configuration configuration) {
this.location = location.replaceAll("\\\\", "/");// 转换为Linux文件路径 this.location = location.replaceAll("\\\\", "/");// 转换为Linux文件路径
this.configuration = configuration; this.configuration = configuration;
...@@ -60,9 +60,6 @@ public class MybatisRunnable implements java.lang.Runnable { ...@@ -60,9 +60,6 @@ public class MybatisRunnable implements java.lang.Runnable {
this.location.lastIndexOf(mappingPath) + mappingPath.length()); this.location.lastIndexOf(mappingPath) + mappingPath.length());
this.beforeTime = System.currentTimeMillis(); this.beforeTime = System.currentTimeMillis();
// LOG.debug("[location] " + location);
// LOG.debug("[configuration] " + configuration);
if (enabled && !isRunning) { if (enabled && !isRunning) {
isRunning = true; isRunning = true;
start(this); start(this);
...@@ -77,7 +74,7 @@ public class MybatisRunnable implements java.lang.Runnable { ...@@ -77,7 +74,7 @@ public class MybatisRunnable implements java.lang.Runnable {
public void run() { public void run() {
try { try {
Thread.sleep(delaySeconds * 1000); Thread.sleep(delaySeconds * 1000);
} catch (InterruptedException e2) { } catch (InterruptedException e2) {
e2.printStackTrace(); e2.printStackTrace();
...@@ -110,9 +107,8 @@ public class MybatisRunnable implements java.lang.Runnable { ...@@ -110,9 +107,8 @@ public class MybatisRunnable implements java.lang.Runnable {
* @throws FileNotFoundException 文件未找到 * @throws FileNotFoundException 文件未找到
*/ */
private void refresh(String filePath, Long beforeTime) throws Exception { private void refresh(String filePath, Long beforeTime) throws Exception {
// 修改本次刷新时间
// Long refrehTime = System.currentTimeMillis();// 本次刷新时间 this.beforeTime = System.currentTimeMillis();
this.beforeTime = System.currentTimeMillis();// 修改本次刷新时间
List<File> refreshs = this.getRefreshFile(new File(filePath), List<File> refreshs = this.getRefreshFile(new File(filePath),
beforeTime); beforeTime);
if (refreshs.size() > 0) { if (refreshs.size() > 0) {
...@@ -120,32 +116,27 @@ public class MybatisRunnable implements java.lang.Runnable { ...@@ -120,32 +116,27 @@ public class MybatisRunnable implements java.lang.Runnable {
} }
for (int i = 0; i < refreshs.size(); i++) { for (int i = 0; i < refreshs.size(); i++) {
LOG.info("refresh file:" + refreshs.get(i).getAbsolutePath()); LOG.info("refresh file:" + refreshs.get(i).getAbsolutePath());
// LOG.info("refresh filename:" + refreshs.get(i).getName());
boolean status = this.parseMapper(new FileInputStream(refreshs.get(i)), boolean status = this.parseMapper(new FileInputStream(refreshs.get(i)),
refreshs.get(i).getAbsolutePath()); refreshs.get(i).getAbsolutePath());
LOG.info("refresh status:" + status); LOG.info("refresh status:" + status);
} }
// 如果刷新了文件,则修改刷新时间,否则不修改
// if (refreshs.size() > 0) {
// this.beforeTime = refrehTime;
// }
} }
/** /**
* 重新加载配置文件 * 重新加载配置文件
* *
* @author renmb
* @time 2017年4月11日
* @param inputStream * @param inputStream
* @param resource * @param resource
* @param configuration
* @return * @return
* @throws NestedIOException * @throws NestedIOException
* @author renmb
* @time 2017年4月11日
*/ */
private boolean parseMapper(java.io.InputStream inputStream, String resource) private boolean parseMapper(java.io.InputStream inputStream, String resource)
throws NestedIOException {// [mybatis-refresh][新增]刷新配置文件 throws NestedIOException {
// [mybatis-refresh][新增]刷新配置文件
try { try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(inputStream, configuration, resource, XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(inputStream, configuration, resource,
configuration.getSqlFragments()); configuration.getSqlFragments());
xmlMapperBuilder.parseMapper(); xmlMapperBuilder.parseMapper();
...@@ -159,6 +150,7 @@ public class MybatisRunnable implements java.lang.Runnable { ...@@ -159,6 +150,7 @@ public class MybatisRunnable implements java.lang.Runnable {
} }
return false; return false;
} }
/** /**
* 获取需要刷新的文件列表 * 获取需要刷新的文件列表
* *
...@@ -170,8 +162,8 @@ public class MybatisRunnable implements java.lang.Runnable { ...@@ -170,8 +162,8 @@ public class MybatisRunnable implements java.lang.Runnable {
List<File> refreshs = new ArrayList<File>(); List<File> refreshs = new ArrayList<File>();
File[] files = dir.listFiles(); File[] files = dir.listFiles();
if(files == null || files.length == 0) if (files == null || files.length == 0)
return refreshs; return refreshs;
for (int i = 0; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
File file = files[i]; File file = files[i];
...@@ -197,9 +189,6 @@ public class MybatisRunnable implements java.lang.Runnable { ...@@ -197,9 +189,6 @@ public class MybatisRunnable implements java.lang.Runnable {
* @return 需要刷新返回true,否则返回false * @return 需要刷新返回true,否则返回false
*/ */
private boolean check(File file, Long beforeTime) { private boolean check(File file, Long beforeTime) {
// if (file.lastModified() > beforeTime) {
// return true;
// }
return file.lastModified() > beforeTime; return file.lastModified() > beforeTime;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment