项目初始导入
This commit is contained in:
28
src/main/java/com/nis/datasource/CustomerContextHolder.java
Normal file
28
src/main/java/com/nis/datasource/CustomerContextHolder.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package com.nis.datasource;
|
||||
|
||||
public class CustomerContextHolder {
|
||||
public static final String DATA_SOURCE_A = "dataSourceA";
|
||||
public static final String DATA_SOURCE_B = "dataSourceB";
|
||||
public static final String DATA_SOURCE_C = "dataSourceC";
|
||||
public static final String DATA_SOURCE_D = "dataSourceD";
|
||||
public static final String DATA_SOURCE_E = "dataSourceE";
|
||||
public static final String DATA_SOURCE_F = "dataSourceF";
|
||||
public static final String DATA_SOURCE_G = "dataSourceG";
|
||||
public static final String DATA_SOURCE_H = "dataSourceH";
|
||||
|
||||
//线程本地环境
|
||||
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
|
||||
//设置数据源类型
|
||||
public static void setCustomerType(String customerType){
|
||||
contextHolder.set(customerType);
|
||||
}
|
||||
//获取数据源类型
|
||||
public static String getCustomerType(){
|
||||
return contextHolder.get();
|
||||
}
|
||||
//清除数据源类型
|
||||
public static void clearCustomerType(){
|
||||
contextHolder.remove();
|
||||
}
|
||||
|
||||
}
|
||||
12
src/main/java/com/nis/datasource/DynamicDataSource.java
Normal file
12
src/main/java/com/nis/datasource/DynamicDataSource.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.nis.datasource;
|
||||
|
||||
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
|
||||
|
||||
public class DynamicDataSource extends AbstractRoutingDataSource {
|
||||
|
||||
@Override
|
||||
protected Object determineCurrentLookupKey() {
|
||||
return CustomerContextHolder.getCustomerType();
|
||||
}
|
||||
|
||||
}
|
||||
168
src/main/java/com/nis/domain/BaseEntity.java
Normal file
168
src/main/java/com/nis/domain/BaseEntity.java
Normal file
@@ -0,0 +1,168 @@
|
||||
package com.nis.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.bind.annotation.XmlTransient;
|
||||
|
||||
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.supcan.SupCol;
|
||||
import com.nis.supcan.SupTreeList;
|
||||
import com.nis.util.Configurations;
|
||||
import com.nis.util.StringUtil;
|
||||
import com.nis.web.security.UserUtils;
|
||||
|
||||
/**
|
||||
* Entity支持类
|
||||
* @author ThinkGem
|
||||
* @version 2014-05-16
|
||||
*/
|
||||
@SupTreeList
|
||||
public abstract class BaseEntity<T> implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 删除标记(1:正常;0:删除;2:审核;)
|
||||
*/
|
||||
public static final String DEL_FLAG_NORMAL = "1";
|
||||
public static final String DEL_FLAG_DELETE = "0";
|
||||
public static final String DEL_FLAG_AUDIT = "2";
|
||||
|
||||
/**
|
||||
* 实体编号(唯一标识)
|
||||
*/
|
||||
protected Long id;
|
||||
|
||||
/**
|
||||
* 当前用户
|
||||
*/
|
||||
protected SysUser currentUser;
|
||||
|
||||
/**
|
||||
* 当前实体分页对象
|
||||
*/
|
||||
protected Page<T> page;
|
||||
|
||||
/**
|
||||
* 自定义SQL(SQL标识,SQL内容)
|
||||
*/
|
||||
protected Map<String, String> sqlMap;
|
||||
|
||||
/**
|
||||
* 是否是新记录(默认:false),调用setIsNewRecord()设置新记录,使用自定义ID。
|
||||
* 设置为true后强制执行插入语句,ID不会自动生成,需从手动传入。
|
||||
*/
|
||||
protected boolean isNewRecord = false;
|
||||
|
||||
public BaseEntity() {
|
||||
|
||||
}
|
||||
|
||||
public BaseEntity(Long id) {
|
||||
this();
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@SupCol(isUnique="true", isHide="true")
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public SysUser getCurrentUser() {
|
||||
if(currentUser == null){
|
||||
currentUser = UserUtils.getUser();
|
||||
}
|
||||
return currentUser;
|
||||
}
|
||||
|
||||
public void setCurrentUser(SysUser currentUser) {
|
||||
this.currentUser = currentUser;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public Page<T> getPage() {
|
||||
if (page == null){
|
||||
page = new Page<T>();
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
public Page<T> setPage(Page<T> page) {
|
||||
this.page = page;
|
||||
return page;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public Map<String, String> getSqlMap() {
|
||||
if (sqlMap == null){
|
||||
sqlMap = Maps.newHashMap();
|
||||
}
|
||||
return sqlMap;
|
||||
}
|
||||
|
||||
public void setSqlMap(Map<String, String> sqlMap) {
|
||||
this.sqlMap = sqlMap;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 是否是新记录(默认:false),调用setIsNewRecord()设置新记录,使用自定义ID。
|
||||
* 设置为true后强制执行插入语句,ID不会自动生成,需从手动传入。
|
||||
* @return
|
||||
*/
|
||||
@JsonIgnore
|
||||
public boolean getIsNewRecord() {
|
||||
return isNewRecord || StringUtil.isEmpty(getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否是新记录(默认:false),调用setIsNewRecord()设置新记录,使用自定义ID。
|
||||
* 设置为true后强制执行插入语句,ID不会自动生成,需从手动传入。
|
||||
*/
|
||||
public void setIsNewRecord(boolean isNewRecord) {
|
||||
this.isNewRecord = isNewRecord;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库名称
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getDbName(){
|
||||
return Configurations.getStringProperty("jdbc.type", "mysql");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (null == obj) {
|
||||
return false;
|
||||
}
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (!getClass().equals(obj.getClass())) {
|
||||
return false;
|
||||
}
|
||||
BaseEntity<?> that = (BaseEntity<?>) obj;
|
||||
return null == this.getId() ? false : this.getId().equals(that.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ReflectionToStringBuilder.toString(this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
120
src/main/java/com/nis/domain/ControlLog.java
Normal file
120
src/main/java/com/nis/domain/ControlLog.java
Normal file
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* @Title: ControlLog.java
|
||||
* @Package com.nis.domain
|
||||
* @Description: TODO(用一句话描述该文件做什么)
|
||||
* @author (darnell)
|
||||
* @date 2016年8月15日 下午4:11:12
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.nis.domain;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.wordnik.swagger.annotations.ApiModel;
|
||||
import com.wordnik.swagger.annotations.ApiModelProperty;
|
||||
|
||||
/**
|
||||
* @ClassName: ControlLog
|
||||
* @Description: TODO(这里用一句话描述这个类的作用)
|
||||
* @author (darnell)
|
||||
* @date 2016年8月15日 下午4:11:12
|
||||
* @version V1.0
|
||||
*/
|
||||
@ApiModel
|
||||
public class ControlLog extends BaseEntity<ControlLog> {
|
||||
/**
|
||||
* @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
|
||||
*/
|
||||
private static final long serialVersionUID = 7644628891063420679L;
|
||||
/**
|
||||
*/
|
||||
@ApiModelProperty(value="域名", required=true)
|
||||
private String domain;
|
||||
@ApiModelProperty(value="标题", required=true)
|
||||
private String title;
|
||||
@ApiModelProperty(value="源IP", required=true)
|
||||
private String srcIp;
|
||||
@ApiModelProperty(value="应答IP", required=true)
|
||||
private String resIp;
|
||||
@ApiModelProperty(value="状态", required=true)
|
||||
private Integer status;
|
||||
@ApiModelProperty(value="操作时间", required=true)
|
||||
private Date optTime;
|
||||
/**
|
||||
* @return domain
|
||||
*/
|
||||
public String getDomain() {
|
||||
return domain;
|
||||
}
|
||||
/**
|
||||
* @param domain 要设置的 domain
|
||||
*/
|
||||
public void setDomain(String domain) {
|
||||
this.domain = domain;
|
||||
}
|
||||
/**
|
||||
* @return title
|
||||
*/
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
/**
|
||||
* @param title 要设置的 title
|
||||
*/
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
/**
|
||||
* @return srcIp
|
||||
*/
|
||||
public String getSrcIp() {
|
||||
return srcIp;
|
||||
}
|
||||
/**
|
||||
* @param srcIp 要设置的 srcIp
|
||||
*/
|
||||
public void setSrcIp(String srcIp) {
|
||||
this.srcIp = srcIp;
|
||||
}
|
||||
/**
|
||||
* @return resIp
|
||||
*/
|
||||
public String getResIp() {
|
||||
return resIp;
|
||||
}
|
||||
/**
|
||||
* @param resIp 要设置的 resIp
|
||||
*/
|
||||
public void setResIp(String resIp) {
|
||||
this.resIp = resIp;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return status
|
||||
*/
|
||||
public Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
/**
|
||||
* @param status 要设置的 status
|
||||
*/
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
/**
|
||||
* @return optTime
|
||||
*/
|
||||
public Date getOptTime() {
|
||||
return optTime;
|
||||
}
|
||||
/**
|
||||
* @param optTime 要设置的 optTime
|
||||
*/
|
||||
public void setOptTime(Date optTime) {
|
||||
this.optTime = optTime;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
179
src/main/java/com/nis/domain/DfJitLogEntity.java
Normal file
179
src/main/java/com/nis/domain/DfJitLogEntity.java
Normal file
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* @Title: LogEntity.java
|
||||
* @Package com.nis.domain
|
||||
* @Description: TODO(用一句话描述该文件做什么)
|
||||
* @author (darnell)
|
||||
* @date 2016年9月1日 上午10:16:54
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.nis.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
import javax.xml.bind.annotation.XmlTransient;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.util.JsonDateSerializer;
|
||||
import com.wordnik.swagger.annotations.ApiModelProperty;
|
||||
|
||||
/**
|
||||
*
|
||||
* @ClassName: DfJitLogEntity
|
||||
* @Description: TODO(实时统计公共实体部分)
|
||||
* @author (rkg)
|
||||
* @date 2016年9月13日下午2:54:12
|
||||
* @version V1.0
|
||||
*/
|
||||
public abstract class DfJitLogEntity<T> implements Serializable {
|
||||
|
||||
@ApiModelProperty(value = "id", required = true)
|
||||
protected Long statId;
|
||||
@ApiModelProperty(value = "统计时间", required = true)
|
||||
protected Date reportTime;
|
||||
@ApiModelProperty(value = "ip所属国家", required = false)
|
||||
protected String nation;
|
||||
@ApiModelProperty(value = "ip所属省", required = false)
|
||||
protected String province;
|
||||
@ApiModelProperty(value = "ip所属市", required = false)
|
||||
protected String city;
|
||||
@ApiModelProperty(value = "日志数量", required = true)
|
||||
protected Long sum;
|
||||
@ApiModelProperty(value = "业务类型", required = true)
|
||||
protected Integer service;
|
||||
|
||||
/**
|
||||
* 公共查询部分
|
||||
*/
|
||||
protected String searchReportStartTime;
|
||||
protected String searchReportEndTime;
|
||||
protected String searchService;
|
||||
|
||||
/**
|
||||
* 当前实体分页对象
|
||||
*/
|
||||
protected Page<T> page;
|
||||
|
||||
/**
|
||||
* 自定义SQL(SQL标识,SQL内容)
|
||||
*/
|
||||
protected Map<String, String> sqlMap;
|
||||
|
||||
public DfJitLogEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Long getStatId() {
|
||||
return statId;
|
||||
}
|
||||
|
||||
public void setStatId(Long statId) {
|
||||
this.statId = statId;
|
||||
}
|
||||
|
||||
@JsonSerialize(using = JsonDateSerializer.class)
|
||||
public Date getReportTime() {
|
||||
return reportTime;
|
||||
}
|
||||
|
||||
public void setReportTime(Date reportTime) {
|
||||
this.reportTime = reportTime;
|
||||
}
|
||||
|
||||
public String getNation() {
|
||||
return nation;
|
||||
}
|
||||
|
||||
public void setNation(String nation) {
|
||||
this.nation = nation;
|
||||
}
|
||||
|
||||
public String getProvince() {
|
||||
return province;
|
||||
}
|
||||
|
||||
public void setProvince(String province) {
|
||||
this.province = province;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
|
||||
public Long getSum() {
|
||||
return sum;
|
||||
}
|
||||
|
||||
public void setSum(Long sum) {
|
||||
this.sum = sum;
|
||||
}
|
||||
|
||||
public Integer getService() {
|
||||
return service;
|
||||
}
|
||||
|
||||
public void setService(Integer service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getSearchReportStartTime() {
|
||||
return searchReportStartTime;
|
||||
}
|
||||
|
||||
public void setSearchReportStartTime(String searchReportStartTime) {
|
||||
this.searchReportStartTime = searchReportStartTime;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getSearchReportEndTime() {
|
||||
return searchReportEndTime;
|
||||
}
|
||||
|
||||
public void setSearchReportEndTime(String searchReportEndTime) {
|
||||
this.searchReportEndTime = searchReportEndTime;
|
||||
}
|
||||
|
||||
|
||||
@JsonIgnore
|
||||
public String getSearchService() {
|
||||
return searchService;
|
||||
}
|
||||
|
||||
public void setSearchService(String searchService) {
|
||||
this.searchService = searchService;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public Page<T> getPage() {
|
||||
if (page == null) {
|
||||
page = new Page<T>();
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
public void setPage(Page<T> page) {
|
||||
this.page = page;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public Map<String, String> getSqlMap() {
|
||||
if (sqlMap == null) {
|
||||
sqlMap = Maps.newHashMap();
|
||||
}
|
||||
return sqlMap;
|
||||
}
|
||||
|
||||
public void setSqlMap(Map<String, String> sqlMap) {
|
||||
this.sqlMap = sqlMap;
|
||||
}
|
||||
|
||||
}
|
||||
149
src/main/java/com/nis/domain/DfReportEntity.java
Normal file
149
src/main/java/com/nis/domain/DfReportEntity.java
Normal file
@@ -0,0 +1,149 @@
|
||||
package com.nis.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.bind.annotation.XmlTransient;
|
||||
|
||||
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.domain.Page;
|
||||
import com.nis.util.Configurations;
|
||||
import com.nis.util.JsonDateSerializer;
|
||||
import com.wordnik.swagger.annotations.ApiModelProperty;
|
||||
|
||||
public class DfReportEntity<T> implements Serializable {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 2990823464993846973L;
|
||||
@ApiModelProperty(value = "A系统", required = true)
|
||||
protected Long asum;
|
||||
@ApiModelProperty(value = "B系统", required = true)
|
||||
protected Long bsum;
|
||||
@ApiModelProperty(value = "C系统", required = true)
|
||||
protected Long csum;
|
||||
@ApiModelProperty(value = "统计时间", required = true)
|
||||
protected Date reportTime;
|
||||
|
||||
@ApiModelProperty(value = "全A+单B", required = true)
|
||||
protected Long absum;
|
||||
|
||||
public Long getAsum() {
|
||||
return asum;
|
||||
}
|
||||
|
||||
public void setAsum(Long asum) {
|
||||
this.asum = asum;
|
||||
}
|
||||
|
||||
public Long getBsum() {
|
||||
return bsum;
|
||||
}
|
||||
|
||||
public void setBsum(Long bsum) {
|
||||
this.bsum = bsum;
|
||||
}
|
||||
|
||||
@JsonSerialize(using = JsonDateSerializer.class)
|
||||
public Date getReportTime() {
|
||||
return reportTime;
|
||||
}
|
||||
|
||||
public void setReportTime(Date reportTime) {
|
||||
this.reportTime = reportTime;
|
||||
}
|
||||
|
||||
protected String searchReportStartTime;
|
||||
protected String searchReportEndTime;
|
||||
|
||||
@JsonIgnore
|
||||
public String getSearchReportStartTime() {
|
||||
return searchReportStartTime;
|
||||
}
|
||||
|
||||
public void setSearchReportStartTime(String searchReportStartTime) {
|
||||
this.searchReportStartTime = searchReportStartTime;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getSearchReportEndTime() {
|
||||
return searchReportEndTime;
|
||||
}
|
||||
|
||||
public void setSearchReportEndTime(String searchReportEndTime) {
|
||||
this.searchReportEndTime = searchReportEndTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前实体分页对象
|
||||
*/
|
||||
protected Page<T> page;
|
||||
|
||||
/**
|
||||
* 自定义SQL(SQL标识,SQL内容)
|
||||
*/
|
||||
protected Map<String, String> sqlMap;
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public Page<T> getPage() {
|
||||
if (page == null) {
|
||||
page = new Page<T>();
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
public Page<T> setPage(Page<T> page) {
|
||||
this.page = page;
|
||||
return page;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public Map<String, String> getSqlMap() {
|
||||
if (sqlMap == null) {
|
||||
sqlMap = Maps.newHashMap();
|
||||
}
|
||||
return sqlMap;
|
||||
}
|
||||
|
||||
public void setSqlMap(Map<String, String> sqlMap) {
|
||||
this.sqlMap = sqlMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库名称
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getDbName() {
|
||||
return Configurations.getStringProperty("jdbc.type", "mysql");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ReflectionToStringBuilder.toString(this);
|
||||
}
|
||||
|
||||
public Long getAbsum() {
|
||||
return absum;
|
||||
}
|
||||
|
||||
public void setAbsum(Long absum) {
|
||||
this.absum = absum;
|
||||
}
|
||||
|
||||
public Long getCsum() {
|
||||
return csum;
|
||||
}
|
||||
|
||||
public void setCsum(Long csum) {
|
||||
this.csum = csum;
|
||||
}
|
||||
|
||||
}
|
||||
841
src/main/java/com/nis/domain/LogEntity.java
Normal file
841
src/main/java/com/nis/domain/LogEntity.java
Normal file
@@ -0,0 +1,841 @@
|
||||
/**
|
||||
* @Title: LogEntity.java
|
||||
* @Package com.nis.domain
|
||||
* @Description: TODO(用一句话描述该文件做什么)
|
||||
* @author (darnell)
|
||||
* @date 2016年9月1日 上午10:16:54
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.nis.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.math.BigDecimal;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.bind.annotation.XmlTransient;
|
||||
|
||||
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.util.Configurations;
|
||||
import com.nis.util.JsonDateSerializer;
|
||||
import com.wordnik.swagger.annotations.ApiModelProperty;
|
||||
|
||||
/**
|
||||
* @ClassName: LogEntity
|
||||
* @Description: TODO(日志公共实体部分)
|
||||
* @author (darnell)
|
||||
* @date 2016年9月1日 上午10:16:54
|
||||
* @version V1.0
|
||||
*/
|
||||
public abstract class LogEntity<T> implements Serializable {
|
||||
|
||||
/**
|
||||
* @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value="日志编号", required=true)
|
||||
protected Long id;
|
||||
|
||||
@ApiModelProperty(value="配置ID", required=true)
|
||||
protected Long cfgId;
|
||||
@ApiModelProperty(value="发现时间", required=true)
|
||||
protected Date foundTime;
|
||||
@ApiModelProperty(value="接收时间", required=true)
|
||||
protected Date recvTime;
|
||||
/*@ApiModelProperty(value="外层嵌套关联信息ID", required=true)
|
||||
protected Long overId;*/
|
||||
@ApiModelProperty(value="外层嵌套关联信息ID", required=true)
|
||||
protected String overId;
|
||||
@ApiModelProperty(value="协议类型", required=true)
|
||||
protected String protocol;
|
||||
@ApiModelProperty(value="服务端ip地址", required=true)
|
||||
protected String serverIp;
|
||||
@ApiModelProperty(value="客户端ip地址", required=true)
|
||||
protected String clientIp;
|
||||
@ApiModelProperty(value="服务端端口", required=true)
|
||||
protected Integer serverPort;
|
||||
@ApiModelProperty(value="客户端端口", required=true)
|
||||
protected Integer clientPort;
|
||||
@ApiModelProperty(value="嵌套协议类型", required=true)
|
||||
protected String nestProtocol;
|
||||
@ApiModelProperty(value="嵌套服务端ip地址", required=true)
|
||||
protected String nestServerIp;
|
||||
@ApiModelProperty(value="嵌套客户端ip地址", required=true)
|
||||
protected String nestClientIp;
|
||||
@ApiModelProperty(value="嵌套服务端端口", required=true)
|
||||
protected Integer nestServerPort;
|
||||
@ApiModelProperty(value="嵌套客户端端口", required=true)
|
||||
protected Integer nestClientPort;
|
||||
@ApiModelProperty(value="业务类型", required=true)
|
||||
protected Integer serviceType;
|
||||
@ApiModelProperty(value="出入口编号", required=true)
|
||||
protected Long entranceId;
|
||||
@ApiModelProperty(value="处理机IP", required=true)
|
||||
protected String cljIp;
|
||||
@ApiModelProperty(value="封堵包记录文件", required=true)
|
||||
protected String injectedPktFile;
|
||||
|
||||
@ApiModelProperty(value="存放现场日志文件的URL地址", required=true)
|
||||
protected String sceneFile;
|
||||
@ApiModelProperty(value="管控动作", required=true)
|
||||
protected Integer action;
|
||||
@ApiModelProperty(value="服务端地址定位信息", required=true)
|
||||
protected String serverLocate;
|
||||
@ApiModelProperty(value="客户端地址定位信息", required=true)
|
||||
protected String clientLocate;
|
||||
|
||||
|
||||
protected Long foundTimeCluster;
|
||||
protected Long recvTimeCluster;
|
||||
|
||||
|
||||
|
||||
|
||||
protected String searchFoundStartTime;
|
||||
protected String searchFoundEndTime;
|
||||
protected Long searchFoundStartTimeCluster;
|
||||
protected Long searchFoundEndTimeCluster;
|
||||
protected String searchCfgId;
|
||||
protected String searchProtocol;
|
||||
protected String searchServiceType;
|
||||
protected String searchServerIp;
|
||||
protected String searchClientIp;
|
||||
protected String searchEntranceId;
|
||||
protected String searchCljIp;
|
||||
protected String tableName;//神通数据库根据A/B版,动态切换表名
|
||||
|
||||
@JsonIgnore
|
||||
public Long getFoundTimeCluster() {
|
||||
return foundTimeCluster;
|
||||
}
|
||||
@JsonIgnore
|
||||
public Long getRecvTimeCluster() {
|
||||
return recvTimeCluster;
|
||||
}
|
||||
public void setFoundTimeCluster(Long foundTimeCluster) {
|
||||
this.foundTimeCluster = foundTimeCluster;
|
||||
}
|
||||
public void setRecvTimeCluster(Long recvTimeCluster) {
|
||||
this.recvTimeCluster = recvTimeCluster;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public Long getSearchFoundStartTimeCluster() {
|
||||
return searchFoundStartTimeCluster;
|
||||
}
|
||||
public void setSearchFoundStartTimeCluster(Long searchFoundStartTimeCluster) {
|
||||
this.searchFoundStartTimeCluster = searchFoundStartTimeCluster;
|
||||
}
|
||||
@JsonIgnore
|
||||
public Long getSearchFoundEndTimeCluster() {
|
||||
return searchFoundEndTimeCluster;
|
||||
}
|
||||
public void setSearchFoundEndTimeCluster(Long searchFoundEndTimeCluster) {
|
||||
this.searchFoundEndTimeCluster = searchFoundEndTimeCluster;
|
||||
}
|
||||
@JsonIgnore
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
public void setTableName(String tableName) {
|
||||
this.tableName = tableName;
|
||||
}
|
||||
public String getOverId() {
|
||||
return overId;
|
||||
}
|
||||
public void setOverId(String overId) {
|
||||
this.overId = overId;
|
||||
}
|
||||
/**
|
||||
* 当前实体分页对象
|
||||
*/
|
||||
protected Page<T> page;
|
||||
|
||||
/**
|
||||
* 自定义SQL(SQL标识,SQL内容)
|
||||
*/
|
||||
protected Map<String, String> sqlMap;
|
||||
|
||||
/**
|
||||
* @Title:
|
||||
* @Description: TODO
|
||||
* @param 入参
|
||||
*/
|
||||
public LogEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public String getInjectedPktFile() {
|
||||
return injectedPktFile;
|
||||
}
|
||||
|
||||
public void setInjectedPktFile(String injectedPktFile) {
|
||||
this.injectedPktFile = injectedPktFile;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return id
|
||||
*/
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param id 要设置的 id
|
||||
*/
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return cfgId
|
||||
*/
|
||||
public Long getCfgId() {
|
||||
return cfgId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param cfgId 要设置的 cfgId
|
||||
*/
|
||||
public void setCfgId(Long cfgId) {
|
||||
this.cfgId = cfgId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return foundTime
|
||||
*/
|
||||
@JsonSerialize(using=JsonDateSerializer.class)
|
||||
public Date getFoundTime() {
|
||||
if(foundTime ==null && this.foundTimeCluster != null){
|
||||
foundTime=new Date(this.foundTimeCluster*1000);
|
||||
}
|
||||
return foundTime;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param foundTime 要设置的 foundTime
|
||||
*/
|
||||
public void setFoundTime(Date foundTime) {
|
||||
this.foundTime = foundTime;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return recvTime
|
||||
*/
|
||||
@JsonSerialize(using=JsonDateSerializer.class)
|
||||
public Date getRecvTime() {
|
||||
if(recvTime ==null && this.recvTimeCluster != null){
|
||||
recvTime=new Date(this.recvTimeCluster*1000);
|
||||
}
|
||||
return recvTime;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param recvTime 要设置的 recvTime
|
||||
*/
|
||||
public void setRecvTime(Date recvTime) {
|
||||
this.recvTime = recvTime;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return overId
|
||||
*/
|
||||
/*public Long getOverId() {
|
||||
return overId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
*//**
|
||||
* @param overId 要设置的 overId
|
||||
*//*
|
||||
public void setOverId(Long overId) {
|
||||
this.overId = overId;
|
||||
}*/
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return protocol
|
||||
*/
|
||||
public String getProtocol() {
|
||||
return protocol;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param protocol 要设置的 protocol
|
||||
*/
|
||||
public void setProtocol(String protocol) {
|
||||
this.protocol = protocol;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return serverIp
|
||||
*/
|
||||
public String getServerIp() {
|
||||
return serverIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param serverIp 要设置的 serverIp
|
||||
*/
|
||||
public void setServerIp(String serverIp) {
|
||||
this.serverIp = serverIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return clientIp
|
||||
*/
|
||||
public String getClientIp() {
|
||||
return clientIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param clientIp 要设置的 clientIp
|
||||
*/
|
||||
public void setClientIp(String clientIp) {
|
||||
this.clientIp = clientIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return serverPort
|
||||
*/
|
||||
public Integer getServerPort() {
|
||||
return serverPort;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param serverPort 要设置的 serverPort
|
||||
*/
|
||||
public void setServerPort(Integer serverPort) {
|
||||
this.serverPort = serverPort;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return clientPort
|
||||
*/
|
||||
public Integer getClientPort() {
|
||||
return clientPort;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param clientPort 要设置的 clientPort
|
||||
*/
|
||||
public void setClientPort(Integer clientPort) {
|
||||
this.clientPort = clientPort;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return nestProtocol
|
||||
*/
|
||||
public String getNestProtocol() {
|
||||
return nestProtocol;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param nestProtocol 要设置的 nestProtocol
|
||||
*/
|
||||
public void setNestProtocol(String nestProtocol) {
|
||||
this.nestProtocol = nestProtocol;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return nestServerIp
|
||||
*/
|
||||
public String getNestServerIp() {
|
||||
return nestServerIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param nestServerIp 要设置的 nestServerIp
|
||||
*/
|
||||
public void setNestServerIp(String nestServerIp) {
|
||||
this.nestServerIp = nestServerIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return nestClientIp
|
||||
*/
|
||||
public String getNestClientIp() {
|
||||
return nestClientIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param nestClientIp 要设置的 nestClientIp
|
||||
*/
|
||||
public void setNestClientIp(String nestClientIp) {
|
||||
this.nestClientIp = nestClientIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return nestServerPort
|
||||
*/
|
||||
public Integer getNestServerPort() {
|
||||
return nestServerPort;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param nestServerPort 要设置的 nestServerPort
|
||||
*/
|
||||
public void setNestServerPort(Integer nestServerPort) {
|
||||
this.nestServerPort = nestServerPort;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return nestClientPort
|
||||
*/
|
||||
public Integer getNestClientPort() {
|
||||
return nestClientPort;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param nestClientPort 要设置的 nestClientPort
|
||||
*/
|
||||
public void setNestClientPort(Integer nestClientPort) {
|
||||
this.nestClientPort = nestClientPort;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return serviceType
|
||||
*/
|
||||
public Integer getServiceType() {
|
||||
return serviceType;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param serviceType 要设置的 serviceType
|
||||
*/
|
||||
public void setServiceType(Integer serviceType) {
|
||||
this.serviceType = serviceType;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return entranceId
|
||||
*/
|
||||
public Long getEntranceId() {
|
||||
return entranceId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param entranceId 要设置的 entranceId
|
||||
*/
|
||||
public void setEntranceId(Long entranceId) {
|
||||
this.entranceId = entranceId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return cljIp
|
||||
*/
|
||||
public String getCljIp() {
|
||||
return cljIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param cljIp 要设置的 cljIp
|
||||
*/
|
||||
public void setCljIp(String cljIp) {
|
||||
this.cljIp = cljIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public String getServerLocate() {
|
||||
return serverLocate;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public void setServerLocate(String serverLocate) {
|
||||
this.serverLocate = serverLocate;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public String getClientLocate() {
|
||||
return clientLocate;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public void setClientLocate(String clientLocate) {
|
||||
this.clientLocate = clientLocate;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public Page<T> getPage() {
|
||||
if (page == null){
|
||||
page = new Page<T>();
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
public Page<T> setPage(Page<T> page) {
|
||||
this.page = page;
|
||||
return page;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public Map<String, String> getSqlMap() {
|
||||
if (sqlMap == null){
|
||||
sqlMap = Maps.newHashMap();
|
||||
}
|
||||
return sqlMap;
|
||||
}
|
||||
|
||||
public void setSqlMap(Map<String, String> sqlMap) {
|
||||
this.sqlMap = sqlMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库名称
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getDbName(){
|
||||
return Configurations.getStringProperty("jdbc.type", "mysql");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (null == obj) {
|
||||
return false;
|
||||
}
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (!getClass().equals(obj.getClass())) {
|
||||
return false;
|
||||
}
|
||||
LogEntity<?> that = (LogEntity<?>) obj;
|
||||
return null == this.getId() ? false : this.getId().equals(that.getId());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return searchFoundStartTime
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getSearchFoundStartTime() {
|
||||
return searchFoundStartTime;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param searchFoundStartTime 要设置的 searchFoundStartTime
|
||||
*/
|
||||
public void setSearchFoundStartTime(String searchFoundStartTime) {
|
||||
this.searchFoundStartTime = searchFoundStartTime;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return searchFoundEndTime
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getSearchFoundEndTime() {
|
||||
return searchFoundEndTime;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param searchFoundEndTime 要设置的 searchFoundEndTime
|
||||
*/
|
||||
public void setSearchFoundEndTime(String searchFoundEndTime) {
|
||||
this.searchFoundEndTime = searchFoundEndTime;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return searchCfgId
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getSearchCfgId() {
|
||||
return searchCfgId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param searchCfgId 要设置的 searchCfgId
|
||||
*/
|
||||
public void setSearchCfgId(String searchCfgId) {
|
||||
this.searchCfgId = searchCfgId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return searchProtocol
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getSearchProtocol() {
|
||||
return searchProtocol;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param searchProtocol 要设置的 searchProtocol
|
||||
*/
|
||||
public void setSearchProtocol(String searchProtocol) {
|
||||
this.searchProtocol = searchProtocol;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return searchServerIp
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getSearchServerIp() {
|
||||
return searchServerIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param searchServerIp 要设置的 searchServerIp
|
||||
*/
|
||||
public void setSearchServerIp(String searchServerIp) {
|
||||
this.searchServerIp = searchServerIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return searchClientIp
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getSearchClientIp() {
|
||||
return searchClientIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param searchClientIp 要设置的 searchClientIp
|
||||
*/
|
||||
public void setSearchClientIp(String searchClientIp) {
|
||||
this.searchClientIp = searchClientIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return searchEntranceId
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getSearchEntranceId() {
|
||||
return searchEntranceId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param searchEntranceId 要设置的 searchEntranceId
|
||||
*/
|
||||
public void setSearchEntranceId(String searchEntranceId) {
|
||||
this.searchEntranceId = searchEntranceId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return searchCljIp
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getSearchCljIp() {
|
||||
return searchCljIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param searchCljIp 要设置的 searchCljIp
|
||||
*/
|
||||
|
||||
public void setSearchCljIp(String searchCljIp) {
|
||||
this.searchCljIp = searchCljIp;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return searchServiceType
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getSearchServiceType() {
|
||||
return searchServiceType;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @param searchServiceType 要设置的 searchServiceType
|
||||
*/
|
||||
public void setSearchServiceType(String searchServiceType) {
|
||||
this.searchServiceType = searchServiceType;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public String getSceneFile() {
|
||||
return sceneFile;
|
||||
}
|
||||
public void setSceneFile(String sceneFile) {
|
||||
this.sceneFile = sceneFile;
|
||||
}
|
||||
|
||||
public Integer getAction() {
|
||||
return action;
|
||||
}
|
||||
public void setAction(Integer action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ReflectionToStringBuilder.toString(this);
|
||||
}
|
||||
|
||||
}
|
||||
780
src/main/java/com/nis/domain/Page.java
Normal file
780
src/main/java/com/nis/domain/Page.java
Normal file
@@ -0,0 +1,780 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.domain;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.ibatis.mapping.ResultMap;
|
||||
import org.apache.ibatis.mapping.ResultMapping;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.nis.util.Configurations;
|
||||
import com.nis.util.Constants;
|
||||
import com.nis.util.CookieUtil;
|
||||
import com.nis.util.StringUtil;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
/**
|
||||
* 分页类
|
||||
* @author ThinkGem
|
||||
* @version 2013-7-2
|
||||
* @param <T>
|
||||
*/
|
||||
public class Page<T> {
|
||||
|
||||
private int pageNo = 1; // 当前页码
|
||||
private int pageSize = Integer.valueOf(Configurations.getIntProperty("page.pageSize", 30)); // 页面大小,设置为“-1”表示不进行分页(分页无效)
|
||||
|
||||
private long count;// 总记录数,设置为“-1”表示不查询总数
|
||||
private int first;// 首页索引
|
||||
private int last;// 尾页索引
|
||||
private int prev;// 上一页索引
|
||||
private int next;// 下一页索引
|
||||
|
||||
|
||||
private boolean firstPage;//是否是第一页
|
||||
private boolean lastPage;//是否是最后一页
|
||||
|
||||
private int length = 8;// 显示页面长度
|
||||
private int slider = 1;// 前后显示页面长度
|
||||
|
||||
private List<T> list = new ArrayList<T>();
|
||||
|
||||
private String orderBy = ""; // 标准查询有效, 实例: updatedate desc, name asc
|
||||
|
||||
private String fields ="";//制定资源的字段
|
||||
|
||||
private String where;
|
||||
|
||||
private String funcName = "page"; // 设置点击页码调用的js函数名称,默认为page,在一页有多个分页对象时使用。
|
||||
|
||||
private String funcParam = ""; // 函数的附加参数,第三个参数值。
|
||||
|
||||
private String message = ""; // 设置提示消息,显示在“共n条”之后
|
||||
|
||||
public Page() {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
* @param request 传递 repage 参数,来记住页码
|
||||
* @param response 用于设置 Cookie,记住页码
|
||||
*/
|
||||
public Page(HttpServletRequest request, HttpServletResponse response){
|
||||
|
||||
//this(request, response,Integer.valueOf(Configurations.getIntProperty("page.pageSize", 30)));
|
||||
|
||||
}
|
||||
/**
|
||||
* 构造方法
|
||||
* @param request 传递 repage 参数,来记住页码
|
||||
* @param response 用于设置 Cookie,记住页码
|
||||
*
|
||||
*/
|
||||
public Page(HttpServletRequest request, HttpServletResponse response,Class clazz){
|
||||
|
||||
this(request, response,clazz.getSimpleName(),Integer.valueOf(Configurations.getIntProperty("page.pageSize", 30)));
|
||||
|
||||
}
|
||||
public Page(HttpServletRequest request, HttpServletResponse response,int defaultPageSize){
|
||||
|
||||
this(request, response,"",Integer.valueOf(Configurations.getIntProperty("page.pageSize", 30)));
|
||||
|
||||
}
|
||||
|
||||
public Page(HttpServletRequest request, HttpServletResponse response,String className, int defaultPageSize){
|
||||
try {
|
||||
// 设置页码参数(传递repage参数,来记住页码)
|
||||
String no = request.getParameter("pageNo");
|
||||
if (StringUtils.isNotBlank(no)) {
|
||||
if (StringUtils.isNumeric(no)){
|
||||
CookieUtil.addCookie(response, "pageNo", no);
|
||||
this.setPageNo(Integer.parseInt(no));
|
||||
}else if (request.getParameter("repage")!=null){
|
||||
no = CookieUtil.getValue(request, "pageNo");
|
||||
if (StringUtils.isNumeric(no)){
|
||||
this.setPageNo(Integer.parseInt(no));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 设置页面大小参数(传递repage参数,来记住页码大小)
|
||||
String size = request.getParameter("pageSize");
|
||||
if (StringUtils.isNotBlank(size)) {
|
||||
|
||||
if (StringUtils.isNumeric(size) || size.equals("-1")){
|
||||
CookieUtil.addCookie(response, "pageSize", size);
|
||||
this.setPageSize(Integer.parseInt(size));
|
||||
} else if (request.getParameter("repage")!=null){
|
||||
size = CookieUtil.getValue(request, "pageSize");
|
||||
if (StringUtils.isNumeric(size)){
|
||||
this.setPageSize(Integer.parseInt(size));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.pageSize = defaultPageSize;
|
||||
}
|
||||
//超出每页最大显示条数,取限制的最大条数
|
||||
if(this.pageSize > Constants.MAX_PAGE_SIZE){
|
||||
this.pageSize = Constants.MAX_PAGE_SIZE;
|
||||
}
|
||||
|
||||
String fields = request.getParameter("fields");
|
||||
if (StringUtils.isNotBlank(fields)){
|
||||
fields=getFiledsSql(className, fields);
|
||||
this.setFields(fields);
|
||||
}
|
||||
|
||||
// 设置排序参数
|
||||
String orderBy = request.getParameter("orderBy");
|
||||
if (StringUtils.isNotBlank(orderBy)){
|
||||
orderBy=getOrderBySql(className, orderBy);
|
||||
this.setOrderBy(orderBy);
|
||||
}
|
||||
this.count=Integer.valueOf(Configurations.getIntProperty("page.count", -1));
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title: getWhere
|
||||
* @Description: TODO(抽取where查询条件)
|
||||
* @param @param request
|
||||
* @param @return 入参
|
||||
* @return String 返回类型
|
||||
* @author (darnell)
|
||||
* @throws
|
||||
* @date 2016年8月17日 上午9:28:21
|
||||
* @version V1.0
|
||||
*/
|
||||
private String getWhere(HttpServletRequest request) {
|
||||
Map<String, String[]> requestMap = request.getParameterMap();
|
||||
StringBuilder whereBuilder = new StringBuilder(512);
|
||||
for(String paramName : request.getParameterMap().keySet()) {
|
||||
if (paramName.startsWith("search")) {
|
||||
whereBuilder.append(paramName.substring("search_".length()))
|
||||
.append("=").append(requestMap.get(paramName)[0]).append(" and ");
|
||||
}
|
||||
}
|
||||
if (whereBuilder.length() > 0) {
|
||||
whereBuilder.delete(whereBuilder.lastIndexOf(" and "), whereBuilder.length());
|
||||
}
|
||||
return whereBuilder.toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
* @param pageNo 当前页码
|
||||
* @param pageSize 分页大小
|
||||
*/
|
||||
public Page(int pageNo, int pageSize) {
|
||||
this(pageNo, pageSize, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
* @param pageNo 当前页码
|
||||
* @param pageSize 分页大小
|
||||
* @param count 数据条数
|
||||
*/
|
||||
public Page(int pageNo, int pageSize, long count) {
|
||||
this(pageNo, pageSize, count, new ArrayList<T>());
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
* @param pageNo 当前页码
|
||||
* @param pageSize 分页大小
|
||||
* @param count 数据条数
|
||||
* @param list 本页数据对象列表
|
||||
*/
|
||||
public Page(int pageNo, int pageSize, long count, List<T> list) {
|
||||
this.setCount(count);
|
||||
this.setPageNo(pageNo);
|
||||
this.pageSize = pageSize;
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化参数
|
||||
*/
|
||||
public void initialize(){
|
||||
|
||||
//1
|
||||
this.first = 1;
|
||||
|
||||
this.last = (int)(count / (this.pageSize < 1 ? 20 : this.pageSize) + first - 1);
|
||||
|
||||
if (this.count % this.pageSize != 0 || this.last == 0) {
|
||||
this.last++;
|
||||
}
|
||||
|
||||
if (this.last < this.first) {
|
||||
this.last = this.first;
|
||||
}
|
||||
|
||||
if (this.pageNo <= 1) {
|
||||
this.pageNo = this.first;
|
||||
this.firstPage=true;
|
||||
}
|
||||
|
||||
if (this.pageNo >= this.last) {
|
||||
this.pageNo = this.last;
|
||||
this.lastPage=true;
|
||||
}
|
||||
|
||||
if (this.pageNo < this.last - 1) {
|
||||
this.next = this.pageNo + 1;
|
||||
} else {
|
||||
this.next = this.last;
|
||||
}
|
||||
|
||||
if (this.pageNo > 1) {
|
||||
this.prev = this.pageNo - 1;
|
||||
} else {
|
||||
this.prev = this.first;
|
||||
}
|
||||
|
||||
//2
|
||||
if (this.pageNo < this.first) {// 如果当前页小于首页
|
||||
this.pageNo = this.first;
|
||||
}
|
||||
|
||||
if (this.pageNo > this.last) {// 如果当前页大于尾页
|
||||
this.pageNo = this.last;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认输出当前分页标签
|
||||
* <div class="page">${page}</div>
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
if (pageNo == first) {// 如果是首页
|
||||
sb.append("<li class=\"disabled\"><a href=\"javascript:\">« 上一页</a></li>\n");
|
||||
} else {
|
||||
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+prev+","+pageSize+",'"+funcParam+"');\">« 上一页</a></li>\n");
|
||||
}
|
||||
|
||||
int begin = pageNo - (length / 2);
|
||||
|
||||
if (begin < first) {
|
||||
begin = first;
|
||||
}
|
||||
|
||||
int end = begin + length - 1;
|
||||
|
||||
if (end >= last) {
|
||||
end = last;
|
||||
begin = end - length + 1;
|
||||
if (begin < first) {
|
||||
begin = first;
|
||||
}
|
||||
}
|
||||
|
||||
if (begin > first) {
|
||||
int i = 0;
|
||||
for (i = first; i < first + slider && i < begin; i++) {
|
||||
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">"
|
||||
+ (i + 1 - first) + "</a></li>\n");
|
||||
}
|
||||
if (i < begin) {
|
||||
sb.append("<li class=\"disabled\"><a href=\"javascript:\">...</a></li>\n");
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = begin; i <= end; i++) {
|
||||
if (i == pageNo) {
|
||||
sb.append("<li class=\"active\"><a href=\"javascript:\">" + (i + 1 - first)
|
||||
+ "</a></li>\n");
|
||||
} else {
|
||||
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">"
|
||||
+ (i + 1 - first) + "</a></li>\n");
|
||||
}
|
||||
}
|
||||
|
||||
if (last - end > slider) {
|
||||
sb.append("<li class=\"disabled\"><a href=\"javascript:\">...</a></li>\n");
|
||||
end = last - slider;
|
||||
}
|
||||
|
||||
for (int i = end + 1; i <= last; i++) {
|
||||
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">"
|
||||
+ (i + 1 - first) + "</a></li>\n");
|
||||
}
|
||||
|
||||
if (pageNo == last) {
|
||||
sb.append("<li class=\"disabled\"><a href=\"javascript:\">下一页 »</a></li>\n");
|
||||
} else {
|
||||
sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+next+","+pageSize+",'"+funcParam+"');\">"
|
||||
+ "下一页 »</a></li>\n");
|
||||
}
|
||||
|
||||
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(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(funcName+"("+pageNo+",this.value,'"+funcParam+"');\" onclick=\"this.select();\"/> 条,");
|
||||
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");
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取分页HTML代码
|
||||
* @return
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getHtml(){
|
||||
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
|
||||
*/
|
||||
public long getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置数据总数
|
||||
* @param count
|
||||
*/
|
||||
public void setCount(long count) {
|
||||
this.count = count;
|
||||
if (pageSize >= count){
|
||||
pageNo = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前页码
|
||||
* @return
|
||||
*/
|
||||
public int getPageNo() {
|
||||
return pageNo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置当前页码
|
||||
* @param pageNo
|
||||
*/
|
||||
public void setPageNo(int pageNo) {
|
||||
this.pageNo = pageNo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取页面大小
|
||||
* @return
|
||||
*/
|
||||
public int getPageSize() {
|
||||
return pageSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置页面大小(最大500)
|
||||
* @param pageSize
|
||||
*/
|
||||
public void setPageSize(int pageSize) {
|
||||
if (pageSize == -1 || pageSize > 0 ) {
|
||||
this.pageSize = pageSize;
|
||||
} else {
|
||||
this.pageSize = Integer.valueOf(Configurations.getIntProperty("page.pageSize", 30));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 首页索引
|
||||
* @return
|
||||
*/
|
||||
@JsonIgnore
|
||||
public int getFirst() {
|
||||
return first;
|
||||
}
|
||||
|
||||
/**
|
||||
* 尾页索引
|
||||
* @return
|
||||
*/
|
||||
public int getLast() {
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取页面总数
|
||||
* @return getLast();
|
||||
*/
|
||||
@JsonIgnore
|
||||
public int getTotalPage() {
|
||||
return getLast();
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为第一页
|
||||
* @return
|
||||
*/
|
||||
@JsonIgnore
|
||||
public boolean isFirstPage() {
|
||||
return firstPage;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为最后一页
|
||||
* @return
|
||||
*/
|
||||
@JsonIgnore
|
||||
public boolean isLastPage() {
|
||||
return lastPage;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return where
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getWhere() {
|
||||
return where;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param where 要设置的 where
|
||||
*/
|
||||
public void setWhere(String where) {
|
||||
this.where = where;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上一页索引值
|
||||
* @return
|
||||
*/
|
||||
@JsonIgnore
|
||||
public int getPrev() {
|
||||
if (isFirstPage()) {
|
||||
return pageNo;
|
||||
} else {
|
||||
return pageNo - 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 下一页索引值
|
||||
* @return
|
||||
*/
|
||||
@JsonIgnore
|
||||
public int getNext() {
|
||||
if (isLastPage()) {
|
||||
return pageNo;
|
||||
} else {
|
||||
return pageNo + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本页数据对象列表
|
||||
* @return List<T>
|
||||
*/
|
||||
public List<T> getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置本页数据对象列表
|
||||
* @param list
|
||||
*/
|
||||
public Page<T> setList(List<T> list) {
|
||||
this.list = list;
|
||||
initialize();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取查询排序字符串
|
||||
* @return
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getOrderBy() {
|
||||
// SQL过滤,防止注入
|
||||
String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
|
||||
+ "(\\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);
|
||||
if (sqlPattern.matcher(orderBy).find()) {
|
||||
return "";
|
||||
}
|
||||
return orderBy;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置查询排序,标准查询有效, 实例: updatedate desc, name asc
|
||||
*/
|
||||
public void setOrderBy(String orderBy) {
|
||||
this.orderBy = orderBy;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @return fields 字段属性查询,拼接用,分隔
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getFields() {
|
||||
return fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param fields 要设置的 fields
|
||||
*/
|
||||
public void setFields(String fields) {
|
||||
this.fields = fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取点击页码调用的js函数名称
|
||||
* function ${page.funcName}(pageNo){location="${ctx}/list-${category.id}${urlSuffix}?pageNo="+i;}
|
||||
* @return
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getFuncName() {
|
||||
return funcName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置点击页码调用的js函数名称,默认为page,在一页有多个分页对象时使用。
|
||||
* @param funcName 默认为page
|
||||
*/
|
||||
public void setFuncName(String funcName) {
|
||||
this.funcName = funcName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取分页函数的附加参数
|
||||
* @return
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getFuncParam() {
|
||||
return funcParam;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置分页函数的附加参数
|
||||
* @return
|
||||
*/
|
||||
public void setFuncParam(String funcParam) {
|
||||
this.funcParam = funcParam;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置提示消息,显示在“共n条”之后
|
||||
* @param message
|
||||
*/
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页是否有效
|
||||
* @return this.pageSize==-1
|
||||
*/
|
||||
@JsonIgnore
|
||||
public boolean isDisabled() {
|
||||
return this.pageSize==-1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否进行总数统计
|
||||
* @return this.count==-1
|
||||
*/
|
||||
@JsonIgnore
|
||||
public boolean isNotCount() {
|
||||
return this.count==-1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Hibernate FirstResult
|
||||
*/
|
||||
@JsonIgnore
|
||||
public int getFirstResult(){
|
||||
int firstResult = (getPageNo() - 1) * getPageSize();
|
||||
if (firstResult >= getCount()) {
|
||||
firstResult = 0;
|
||||
}
|
||||
return firstResult;
|
||||
}
|
||||
/**
|
||||
* 获取 Hibernate MaxResults
|
||||
*/
|
||||
@JsonIgnore
|
||||
public int getMaxResults(){
|
||||
return getPageSize();
|
||||
}
|
||||
/**
|
||||
* @Title: getFiledsSql
|
||||
* @Description: 将fields的属性名称替换为字段名称
|
||||
* @param @param mapName
|
||||
* @param @param fileds
|
||||
* @param @return
|
||||
* @param @throws Exception
|
||||
* @return Map 返回类型
|
||||
* @author (DDM)
|
||||
* @version V1.0
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getFiledsSql(String mapName,String fileds) throws Exception{
|
||||
String[] fieldsColoumn=null;
|
||||
String orderByStr="";
|
||||
//所有字段名
|
||||
List<String> columnList=new ArrayList<String>();
|
||||
//所有属性名
|
||||
List<String> propertyList=new ArrayList<String>();
|
||||
//属性名称为key,字段名称为value
|
||||
Map<String, String> columnMap=new HashMap<String, String>();
|
||||
|
||||
if(!StringUtil.isBlank(fileds)){
|
||||
//解析Fileds的字段/属性名称
|
||||
fieldsColoumn=fileds.split(",");
|
||||
|
||||
//从resultMap中获取字段名称和属性名称
|
||||
if(fieldsColoumn != null){
|
||||
SqlSessionFactory sqlSessionFactory=SpringContextHolder.getBean(SqlSessionFactory.class);
|
||||
ResultMap map= sqlSessionFactory.getConfiguration().getResultMap(mapName+"Map");
|
||||
List<ResultMapping> mapping= map.getResultMappings();
|
||||
for(ResultMapping mapp:mapping){
|
||||
columnList.add(mapp.getColumn().toLowerCase());
|
||||
propertyList.add(mapp.getProperty());
|
||||
columnMap.put(mapp.getProperty(), mapp.getColumn());
|
||||
}
|
||||
}
|
||||
if(fieldsColoumn != null){
|
||||
fileds="";
|
||||
for (String column : fieldsColoumn) {
|
||||
if(!StringUtil.isBlank(column)){
|
||||
column=column.trim();
|
||||
if(columnList.contains(column.toLowerCase())){
|
||||
fileds+=","+column;
|
||||
}else if(propertyList.contains(column)){
|
||||
fileds+=","+columnMap.get(column).toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!StringUtil.isBlank(fileds)){
|
||||
fileds=fileds.substring(1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
return fileds;
|
||||
}
|
||||
/**
|
||||
* @Title: getOrderBySql
|
||||
* @Description: 将orderBy的属性名称替换为字段名称
|
||||
* @param @param mapName
|
||||
* @param @param orderBy
|
||||
* @param @return
|
||||
* @param @throws Exception
|
||||
* @return Map 返回类型
|
||||
* @author (DDM)
|
||||
* @version V1.0
|
||||
*/
|
||||
@JsonIgnore
|
||||
public static String getOrderBySql(String mapName,String orderBy) throws Exception{
|
||||
String[] orderByColoumn=null;
|
||||
//所有字段名
|
||||
List<String> columnList=new ArrayList<String>();
|
||||
//所有属性名
|
||||
List<String> propertyList=new ArrayList<String>();
|
||||
Map<String, String> columnMap=new HashMap<String, String>();
|
||||
|
||||
if(!StringUtil.isBlank(orderBy)){
|
||||
//解析orderBy的字段/属性名称
|
||||
orderByColoumn=orderBy.split(",");
|
||||
//从resultMap中获取字段名称和属性名称
|
||||
if(orderByColoumn != null){
|
||||
SqlSessionFactory sqlSessionFactory=SpringContextHolder.getBean(SqlSessionFactory.class);
|
||||
ResultMap map= sqlSessionFactory.getConfiguration().getResultMap(mapName+"Map");
|
||||
List<ResultMapping> mapping= map.getResultMappings();
|
||||
for(ResultMapping mapp:mapping){
|
||||
columnList.add(mapp.getColumn().toLowerCase());
|
||||
propertyList.add(mapp.getProperty());
|
||||
columnMap.put(mapp.getProperty(), mapp.getColumn());
|
||||
}
|
||||
}
|
||||
if(orderByColoumn != null){
|
||||
orderBy="";
|
||||
for (String column : orderByColoumn) {
|
||||
if(!StringUtil.isBlank(column)){
|
||||
if(columnList.contains(replaceOrderBy(column))){
|
||||
orderBy+=","+column;
|
||||
}else if(propertyList.contains(replaceOrderBy(column))){
|
||||
//如果是实体类名字则获取对应数据库名字+排序方式
|
||||
orderBy+=","+columnMap.get(replaceOrderBy(column)).toString()
|
||||
+column.replace(replaceOrderBy(column), "");
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!StringUtil.isBlank(orderBy)){
|
||||
orderBy=orderBy.substring(1);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return orderBy;
|
||||
}
|
||||
/**
|
||||
* @Title: replaceOrderBy
|
||||
* @Description: 去掉orderBy中的desc和asc
|
||||
* @param @param str
|
||||
* @param @return
|
||||
* @return Map 返回类型
|
||||
* @author (DDM)
|
||||
* @version V1.0
|
||||
*/
|
||||
public static String replaceOrderBy(String str){
|
||||
if(!StringUtil.isBlank(str)){
|
||||
str=str.trim();
|
||||
str=str.replace(" asc","");
|
||||
str=str.replace(" ASC","");
|
||||
str=str.replace(" DESC","");
|
||||
str=str.replace(" desc","");
|
||||
str=str.trim();
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
}
|
||||
220
src/main/java/com/nis/domain/ServicesRequestLog.java
Normal file
220
src/main/java/com/nis/domain/ServicesRequestLog.java
Normal file
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
*@Title: ServicesRequestLog.java
|
||||
*@Package com.nis.domain
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年10月13日 下午3:39:14
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
import com.nis.util.JsonMapper;
|
||||
|
||||
/**
|
||||
* @ClassName: ServicesRequestLog.java
|
||||
* @Description: TODO
|
||||
* @author (dell)
|
||||
* @date 2016年10月13日 下午3:39:14
|
||||
* @version V1.0
|
||||
*/
|
||||
public class ServicesRequestLog implements Serializable {
|
||||
|
||||
/**
|
||||
* @Fields serialVersionUID:TODO(用一句话描述这个变量表示什么)
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
|
||||
private static final long serialVersionUID = 3374409440640840339L;
|
||||
private Long id;
|
||||
private String operator;
|
||||
private String version;
|
||||
private Integer opAction;
|
||||
private Date opTime;
|
||||
private String requestContent;
|
||||
private Date requestTime;
|
||||
private Long consumerTime;
|
||||
private String requestIp;
|
||||
private Integer businessCode;
|
||||
private String exceptionInfo;
|
||||
private String serverIp;
|
||||
|
||||
/**
|
||||
* serverIp
|
||||
* @return serverIp
|
||||
*/
|
||||
|
||||
public String getServerIp() {
|
||||
return serverIp;
|
||||
}
|
||||
/**
|
||||
* @param serverIp the serverIp to set
|
||||
*/
|
||||
public void setServerIp(String serverIp) {
|
||||
this.serverIp = serverIp;
|
||||
}
|
||||
/**
|
||||
* businessCode
|
||||
* @return businessCode
|
||||
*/
|
||||
|
||||
public Integer getBusinessCode() {
|
||||
return businessCode;
|
||||
}
|
||||
/**
|
||||
* @param businessCode the businessCode to set
|
||||
*/
|
||||
public void setBusinessCode(Integer businessCode) {
|
||||
this.businessCode = businessCode;
|
||||
}
|
||||
/**
|
||||
* id
|
||||
* @return id
|
||||
*/
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
/**
|
||||
* @param id the id to set
|
||||
*/
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
/**
|
||||
* operator
|
||||
* @return operator
|
||||
*/
|
||||
|
||||
public String getOperator() {
|
||||
return operator;
|
||||
}
|
||||
/**
|
||||
* @param operator the operator to set
|
||||
*/
|
||||
public void setOperator(String operator) {
|
||||
this.operator = operator;
|
||||
}
|
||||
/**
|
||||
* version
|
||||
* @return version
|
||||
*/
|
||||
|
||||
public String getVersion() {
|
||||
return version;
|
||||
}
|
||||
/**
|
||||
* @param version the version to set
|
||||
*/
|
||||
public void setVersion(String version) {
|
||||
this.version = version;
|
||||
}
|
||||
/**
|
||||
* opAction
|
||||
* @return opAction
|
||||
*/
|
||||
|
||||
public Integer getOpAction() {
|
||||
return opAction;
|
||||
}
|
||||
/**
|
||||
* @param opAction the opAction to set
|
||||
*/
|
||||
public void setOpAction(Integer opAction) {
|
||||
this.opAction = opAction;
|
||||
}
|
||||
/**
|
||||
* opTime
|
||||
* @return opTime
|
||||
*/
|
||||
|
||||
public Date getOpTime() {
|
||||
return opTime;
|
||||
}
|
||||
/**
|
||||
* @param opTime the opTime to set
|
||||
*/
|
||||
public void setOpTime(Date opTime) {
|
||||
this.opTime = opTime;
|
||||
}
|
||||
/**
|
||||
* requestContent
|
||||
* @return requestContent
|
||||
*/
|
||||
|
||||
public String getRequestContent() {
|
||||
return requestContent;
|
||||
}
|
||||
/**
|
||||
* @param requestContent the requestContent to set
|
||||
*/
|
||||
public void setRequestContent(String requestContent) {
|
||||
this.requestContent = requestContent;
|
||||
}
|
||||
/**
|
||||
* @param requestContent the requestContent to set
|
||||
*/
|
||||
public void setRequestContent(Object requestContent) {
|
||||
this.requestContent = JsonMapper.getInstance().toJsonString(requestContent);
|
||||
}
|
||||
/**
|
||||
* requestTime
|
||||
* @return requestTime
|
||||
*/
|
||||
|
||||
public Date getRequestTime() {
|
||||
return requestTime;
|
||||
}
|
||||
/**
|
||||
* @param requestTime the requestTime to set
|
||||
*/
|
||||
public void setRequestTime(Date requestTime) {
|
||||
this.requestTime = requestTime;
|
||||
}
|
||||
/**
|
||||
* consumerTime
|
||||
* @return consumerTime
|
||||
*/
|
||||
|
||||
public Long getConsumerTime() {
|
||||
return consumerTime;
|
||||
}
|
||||
/**
|
||||
* @param consumerTime the consumerTime to set
|
||||
*/
|
||||
public void setConsumerTime(Long consumerTime) {
|
||||
this.consumerTime = consumerTime;
|
||||
}
|
||||
/**
|
||||
* requestIp
|
||||
* @return requestIp
|
||||
*/
|
||||
|
||||
public String getRequestIp() {
|
||||
return requestIp;
|
||||
}
|
||||
/**
|
||||
* @param requestIp the requestIp to set
|
||||
*/
|
||||
public void setRequestIp(String requestIp) {
|
||||
this.requestIp = requestIp;
|
||||
}
|
||||
/**
|
||||
* exceptionInfo
|
||||
* @return exceptionInfo
|
||||
*/
|
||||
|
||||
public String getExceptionInfo() {
|
||||
return exceptionInfo;
|
||||
}
|
||||
/**
|
||||
* @param exceptionInfo the exceptionInfo to set
|
||||
*/
|
||||
public void setExceptionInfo(String exceptionInfo) {
|
||||
this.exceptionInfo = exceptionInfo;
|
||||
}
|
||||
|
||||
}
|
||||
145
src/main/java/com/nis/domain/SrcIp.java
Normal file
145
src/main/java/com/nis/domain/SrcIp.java
Normal file
@@ -0,0 +1,145 @@
|
||||
package com.nis.domain;
|
||||
|
||||
public class SrcIp {
|
||||
private Integer seqId;
|
||||
|
||||
private Integer ipStartAddr;
|
||||
|
||||
private Integer ipEndAddr;
|
||||
|
||||
private Integer ipAddrRange;
|
||||
|
||||
private String ipStartString;
|
||||
|
||||
private String ipEndString;
|
||||
|
||||
private Integer port;
|
||||
|
||||
private Long ispId;
|
||||
|
||||
private Long areaId;
|
||||
|
||||
private Integer flag;
|
||||
|
||||
private String description;
|
||||
|
||||
private Integer yl1;
|
||||
|
||||
private String yl2;
|
||||
|
||||
|
||||
private String searchIp;
|
||||
|
||||
|
||||
public String getSearchIp() {
|
||||
return searchIp;
|
||||
}
|
||||
|
||||
public void setSearchIp(String searchIp) {
|
||||
this.searchIp = searchIp;
|
||||
}
|
||||
|
||||
public Integer getSeqId() {
|
||||
return seqId;
|
||||
}
|
||||
|
||||
public void setSeqId(Integer seqId) {
|
||||
this.seqId = seqId;
|
||||
}
|
||||
|
||||
public Integer getIpStartAddr() {
|
||||
return ipStartAddr;
|
||||
}
|
||||
|
||||
public void setIpStartAddr(Integer ipStartAddr) {
|
||||
this.ipStartAddr = ipStartAddr;
|
||||
}
|
||||
|
||||
public Integer getIpEndAddr() {
|
||||
return ipEndAddr;
|
||||
}
|
||||
|
||||
public void setIpEndAddr(Integer ipEndAddr) {
|
||||
this.ipEndAddr = ipEndAddr;
|
||||
}
|
||||
|
||||
public Integer getIpAddrRange() {
|
||||
return ipAddrRange;
|
||||
}
|
||||
|
||||
public void setIpAddrRange(Integer ipAddrRange) {
|
||||
this.ipAddrRange = ipAddrRange;
|
||||
}
|
||||
|
||||
public String getIpStartString() {
|
||||
return ipStartString;
|
||||
}
|
||||
|
||||
public void setIpStartString(String ipStartString) {
|
||||
this.ipStartString = ipStartString == null ? null : ipStartString.trim();
|
||||
}
|
||||
|
||||
public String getIpEndString() {
|
||||
return ipEndString;
|
||||
}
|
||||
|
||||
public void setIpEndString(String ipEndString) {
|
||||
this.ipEndString = ipEndString == null ? null : ipEndString.trim();
|
||||
}
|
||||
|
||||
public Integer getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(Integer port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public Long getIspId() {
|
||||
return ispId;
|
||||
}
|
||||
|
||||
public void setIspId(Long ispId) {
|
||||
this.ispId = ispId;
|
||||
}
|
||||
|
||||
public Long getAreaId() {
|
||||
return areaId;
|
||||
}
|
||||
|
||||
public void setAreaId(Long areaId) {
|
||||
this.areaId = areaId;
|
||||
}
|
||||
|
||||
public Integer getFlag() {
|
||||
return flag;
|
||||
}
|
||||
|
||||
public void setFlag(Integer flag) {
|
||||
this.flag = flag;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description == null ? null : description.trim();
|
||||
}
|
||||
|
||||
public Integer getYl1() {
|
||||
return yl1;
|
||||
}
|
||||
|
||||
public void setYl1(Integer yl1) {
|
||||
this.yl1 = yl1;
|
||||
}
|
||||
|
||||
public String getYl2() {
|
||||
return yl2;
|
||||
}
|
||||
|
||||
public void setYl2(String yl2) {
|
||||
this.yl2 = yl2 == null ? null : yl2.trim();
|
||||
}
|
||||
}
|
||||
203
src/main/java/com/nis/domain/StatLogEntity.java
Normal file
203
src/main/java/com/nis/domain/StatLogEntity.java
Normal file
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* @Title: StatLogEntity.java
|
||||
* @Package com.nis.domain
|
||||
* @Description: TODO(用一句话描述该文件做什么)
|
||||
* @author (ddm)
|
||||
* @date 2016年9月13日 上午10:49:01
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.nis.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.bind.annotation.XmlTransient;
|
||||
|
||||
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.util.Configurations;
|
||||
import com.nis.util.JsonDateSerializer;
|
||||
import com.wordnik.swagger.annotations.ApiModelProperty;
|
||||
|
||||
/**
|
||||
* @ClassName: StatLogEntity
|
||||
* @Description: TODO(日志报表公共实体部分)
|
||||
* @author (ddm)
|
||||
* @date 2016年9月1日 上午10:16:54
|
||||
* @version V1.0
|
||||
*/
|
||||
public abstract class StatLogEntity<T> implements Serializable {
|
||||
|
||||
/**
|
||||
* @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
|
||||
*/
|
||||
private static final long serialVersionUID = -5210683756718456730L;
|
||||
|
||||
@ApiModelProperty(value="私有标签", required=true)
|
||||
protected Integer service;
|
||||
@ApiModelProperty(value="生效系统", required=true)
|
||||
protected Integer activeSys;
|
||||
@ApiModelProperty(value="A版总计", required=true)
|
||||
protected Long asum;
|
||||
@ApiModelProperty(value="B版总计", required=true)
|
||||
protected Long bsum;
|
||||
@ApiModelProperty(value="全A+单B数量", required=true)
|
||||
protected Long absum;
|
||||
@ApiModelProperty(value="统计时间", required=true)
|
||||
protected Date statTime;
|
||||
|
||||
protected String searchStatStartTime;
|
||||
protected String searchStatEndTime;
|
||||
protected String searchService;
|
||||
protected String searchStatActiveSys;
|
||||
|
||||
|
||||
@JsonSerialize(using=JsonDateSerializer.class)
|
||||
public Date getStatTime() {
|
||||
return statTime;
|
||||
}
|
||||
public void setStatTime(Date statTime) {
|
||||
this.statTime = statTime;
|
||||
}
|
||||
|
||||
public Integer getActiveSys() {
|
||||
return activeSys;
|
||||
}
|
||||
public void setActiveSys(Integer activeSys) {
|
||||
this.activeSys = activeSys;
|
||||
}
|
||||
|
||||
public Integer getService() {
|
||||
return service;
|
||||
}
|
||||
|
||||
|
||||
public void setService(Integer service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
|
||||
public Long getAbsum() {
|
||||
return absum;
|
||||
}
|
||||
public Long getBsum() {
|
||||
return bsum;
|
||||
}
|
||||
public void setAbsum(Long absum) {
|
||||
this.absum = absum;
|
||||
}
|
||||
public void setBsum(Long bsum) {
|
||||
this.bsum = bsum;
|
||||
}
|
||||
public Long getAsum() {
|
||||
return asum;
|
||||
}
|
||||
public void setAsum(Long asum) {
|
||||
this.asum = asum;
|
||||
}
|
||||
|
||||
|
||||
@JsonIgnore
|
||||
public String getSearchStatStartTime() {
|
||||
return searchStatStartTime;
|
||||
}
|
||||
|
||||
|
||||
public void setSearchStatStartTime(String searchStatStartTime) {
|
||||
this.searchStatStartTime = searchStatStartTime;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getSearchStatEndTime() {
|
||||
return searchStatEndTime;
|
||||
}
|
||||
|
||||
|
||||
public void setSearchStatEndTime(String searchStatEndTime) {
|
||||
this.searchStatEndTime = searchStatEndTime;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getSearchService() {
|
||||
return searchService;
|
||||
}
|
||||
|
||||
|
||||
public void setSearchService(String searchService) {
|
||||
this.searchService = searchService;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getSearchStatActiveSys() {
|
||||
return searchStatActiveSys;
|
||||
}
|
||||
public void setSearchStatActiveSys(String searchStatActiveSys) {
|
||||
this.searchStatActiveSys = searchStatActiveSys;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前实体分页对象
|
||||
*/
|
||||
protected Page<T> page;
|
||||
|
||||
/**
|
||||
* 自定义SQL(SQL标识,SQL内容)
|
||||
*/
|
||||
protected Map<String, String> sqlMap;
|
||||
|
||||
/**
|
||||
* @Title:
|
||||
* @Description: TODO
|
||||
* @param 入参
|
||||
*/
|
||||
public StatLogEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public Page<T> getPage() {
|
||||
if (page == null){
|
||||
page = new Page<T>();
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
public Page<T> setPage(Page<T> page) {
|
||||
this.page = page;
|
||||
return page;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
@XmlTransient
|
||||
public Map<String, String> getSqlMap() {
|
||||
if (sqlMap == null){
|
||||
sqlMap = Maps.newHashMap();
|
||||
}
|
||||
return sqlMap;
|
||||
}
|
||||
|
||||
public void setSqlMap(Map<String, String> sqlMap) {
|
||||
this.sqlMap = sqlMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库名称
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getDbName(){
|
||||
return Configurations.getStringProperty("jdbc.type", "mysql");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ReflectionToStringBuilder.toString(this);
|
||||
}
|
||||
|
||||
}
|
||||
80
src/main/java/com/nis/domain/SysArea.java
Normal file
80
src/main/java/com/nis/domain/SysArea.java
Normal file
@@ -0,0 +1,80 @@
|
||||
package com.nis.domain;
|
||||
|
||||
|
||||
public class SysArea extends TreeEntity<SysArea>{
|
||||
|
||||
private static final long serialVersionUID = -6425455761476080303L;
|
||||
|
||||
private String code;
|
||||
|
||||
private String type;
|
||||
|
||||
private String remarks;
|
||||
|
||||
private double longitude;
|
||||
|
||||
private double latitude;
|
||||
|
||||
private Integer delFlag;
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code == null ? null : code.trim();
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type == null ? null : type.trim();
|
||||
}
|
||||
|
||||
public String getRemarks() {
|
||||
return remarks;
|
||||
}
|
||||
|
||||
public void setRemarks(String remarks) {
|
||||
this.remarks = remarks == null ? null : remarks.trim();
|
||||
}
|
||||
|
||||
public Integer getDelFlag() {
|
||||
return delFlag;
|
||||
}
|
||||
|
||||
public void setDelFlag(Integer delFlag) {
|
||||
this.delFlag = delFlag;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public double getLongitude() {
|
||||
return longitude;
|
||||
}
|
||||
|
||||
public void setLongitude(double longitude) {
|
||||
this.longitude = longitude;
|
||||
}
|
||||
|
||||
public double getLatitude() {
|
||||
return latitude;
|
||||
}
|
||||
|
||||
public void setLatitude(double latitude) {
|
||||
this.latitude = latitude;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SysArea getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setParent(SysArea parent) {
|
||||
this.parent = parent;
|
||||
|
||||
}
|
||||
}
|
||||
76
src/main/java/com/nis/domain/SysDataDictionaryItem.java
Normal file
76
src/main/java/com/nis/domain/SysDataDictionaryItem.java
Normal file
@@ -0,0 +1,76 @@
|
||||
package com.nis.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
public class SysDataDictionaryItem implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private Long id;
|
||||
private String itemCode;
|
||||
private String itemValue;
|
||||
private String itemDesc;
|
||||
private int itemSort;
|
||||
private SysDataDictionaryName sysDataDictionaryName;
|
||||
private int dictionaryId;
|
||||
|
||||
public int getItemSort() {
|
||||
return itemSort;
|
||||
}
|
||||
public void setItemSort(int itemSort) {
|
||||
this.itemSort = itemSort;
|
||||
}
|
||||
private int status;
|
||||
|
||||
private int type;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
public String getItemCode() {
|
||||
return itemCode;
|
||||
}
|
||||
public String getItemValue() {
|
||||
return itemValue;
|
||||
}
|
||||
public String getItemDesc() {
|
||||
return itemDesc;
|
||||
}
|
||||
public int getStatus() {
|
||||
return status;
|
||||
}
|
||||
public int getType() {
|
||||
return type;
|
||||
}
|
||||
public SysDataDictionaryName getSysDataDictionaryName() {
|
||||
return sysDataDictionaryName;
|
||||
}
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setItemCode(String itemCode) {
|
||||
this.itemCode = itemCode;
|
||||
}
|
||||
public void setItemValue(String itemValue) {
|
||||
this.itemValue = itemValue;
|
||||
}
|
||||
public void setItemDesc(String itemDesc) {
|
||||
this.itemDesc = itemDesc;
|
||||
}
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
public void setType(int type) {
|
||||
this.type = type;
|
||||
}
|
||||
public void setSysDataDictionaryName(SysDataDictionaryName sysDataDictionaryName) {
|
||||
this.sysDataDictionaryName = sysDataDictionaryName;
|
||||
}
|
||||
public int getDictionaryId() {
|
||||
return dictionaryId;
|
||||
}
|
||||
public void setDictionaryId(int dictionaryId) {
|
||||
this.dictionaryId = dictionaryId;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
116
src/main/java/com/nis/domain/SysDataDictionaryName.java
Normal file
116
src/main/java/com/nis/domain/SysDataDictionaryName.java
Normal file
@@ -0,0 +1,116 @@
|
||||
package com.nis.domain;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class SysDataDictionaryName extends BaseEntity<SysDataDictionaryName> {
|
||||
|
||||
private static final long serialVersionUID = 8475518325068404528L;
|
||||
|
||||
private String moduleName;
|
||||
|
||||
private String mark;
|
||||
|
||||
private String remark;
|
||||
|
||||
private String revision;
|
||||
|
||||
private Date createTime;
|
||||
|
||||
private Date modifyTime;
|
||||
|
||||
private Integer status;
|
||||
|
||||
private List<SysDataDictionaryItem> dictItemList = Lists.newArrayList();
|
||||
|
||||
private Date beginDate; // 开始日期
|
||||
private Date endDate; // 结束日期
|
||||
|
||||
|
||||
|
||||
public String getModuleName() {
|
||||
return moduleName;
|
||||
}
|
||||
|
||||
public void setModuleName(String moduleName) {
|
||||
this.moduleName = moduleName == null ? null : moduleName.trim();
|
||||
}
|
||||
|
||||
public String getMark() {
|
||||
return mark;
|
||||
}
|
||||
|
||||
public void setMark(String mark) {
|
||||
this.mark = mark == null ? null : mark.trim();
|
||||
}
|
||||
|
||||
public String getRemark() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setRemark(String remark) {
|
||||
this.remark = remark == null ? null : remark.trim();
|
||||
}
|
||||
|
||||
public String getRevision() {
|
||||
return revision;
|
||||
}
|
||||
|
||||
public void setRevision(String revision) {
|
||||
this.revision = revision == null ? null : revision.trim();
|
||||
}
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
|
||||
public Date getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(Date createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
|
||||
public Date getModifyTime() {
|
||||
return modifyTime;
|
||||
}
|
||||
|
||||
public void setModifyTime(Date modifyTime) {
|
||||
this.modifyTime = modifyTime;
|
||||
}
|
||||
|
||||
public Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public List<SysDataDictionaryItem> getDictItemList() {
|
||||
return dictItemList;
|
||||
}
|
||||
|
||||
public void setDictItemList(List<SysDataDictionaryItem> dictItemList) {
|
||||
this.dictItemList = dictItemList;
|
||||
}
|
||||
|
||||
public Date getBeginDate() {
|
||||
return beginDate;
|
||||
}
|
||||
|
||||
public void setBeginDate(Date beginDate) {
|
||||
this.beginDate = beginDate;
|
||||
}
|
||||
|
||||
public Date getEndDate() {
|
||||
return endDate;
|
||||
}
|
||||
|
||||
public void setEndDate(Date endDate) {
|
||||
this.endDate = endDate;
|
||||
}
|
||||
|
||||
}
|
||||
180
src/main/java/com/nis/domain/SysLog.java
Normal file
180
src/main/java/com/nis/domain/SysLog.java
Normal file
@@ -0,0 +1,180 @@
|
||||
package com.nis.domain;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.nis.util.StringUtils;
|
||||
|
||||
|
||||
public class SysLog extends BaseEntity<SysLog>{
|
||||
private static final long serialVersionUID = -926412650391800311L;
|
||||
|
||||
private Integer type;//日志类型:运行日志(1000-系统登录 1001-系统退出)、操作(2000-添加 2001-删除 2002-修改 2003-查询) \404 未知操作
|
||||
|
||||
private String title;// 日志标题
|
||||
|
||||
private Date createDate;//创建日期
|
||||
|
||||
private String remoteAddr;// 操作用户的IP地址
|
||||
|
||||
private String userAgent;// 操作用户代理信息
|
||||
|
||||
private String requestUri;// 操作的URI
|
||||
|
||||
private String method;// 操作的方式
|
||||
|
||||
private Integer state;//0-失败 1-成功
|
||||
|
||||
private String params; // 操作提交的数据
|
||||
|
||||
private String exception; // 异常信息
|
||||
|
||||
private Long consumerTime;//消费时间
|
||||
|
||||
public Long getConsumerTime() {
|
||||
return consumerTime;
|
||||
}
|
||||
|
||||
public void setConsumerTime(Long consumerTime) {
|
||||
this.consumerTime = consumerTime;
|
||||
}
|
||||
|
||||
private Date beginDate; // 开始日期
|
||||
private Date endDate; // 结束日期
|
||||
|
||||
|
||||
|
||||
public Date getBeginDate() {
|
||||
return beginDate;
|
||||
}
|
||||
|
||||
public void setBeginDate(Date beginDate) {
|
||||
this.beginDate = beginDate;
|
||||
}
|
||||
|
||||
public Date getEndDate() {
|
||||
return endDate;
|
||||
}
|
||||
|
||||
public void setEndDate(Date endDate) {
|
||||
this.endDate = endDate;
|
||||
}
|
||||
|
||||
public Integer getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(Integer type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title == null ? null : title.trim();
|
||||
}
|
||||
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
public Date getCreateDate() {
|
||||
return createDate;
|
||||
}
|
||||
|
||||
public void setCreateDate(Date createDate) {
|
||||
this.createDate = createDate;
|
||||
}
|
||||
|
||||
public String getRemoteAddr() {
|
||||
return remoteAddr;
|
||||
}
|
||||
|
||||
public void setRemoteAddr(String remoteAddr) {
|
||||
this.remoteAddr = remoteAddr == null ? null : remoteAddr.trim();
|
||||
}
|
||||
|
||||
public String getUserAgent() {
|
||||
return userAgent;
|
||||
}
|
||||
|
||||
public void setUserAgent(String userAgent) {
|
||||
this.userAgent = userAgent == null ? null : userAgent.trim();
|
||||
}
|
||||
|
||||
public String getRequestUri() {
|
||||
return requestUri;
|
||||
}
|
||||
|
||||
public void setRequestUri(String requestUri) {
|
||||
this.requestUri = requestUri == null ? null : requestUri.trim();
|
||||
}
|
||||
|
||||
public String getMethod() {
|
||||
return method;
|
||||
}
|
||||
|
||||
public void setMethod(String method) {
|
||||
this.method = method == null ? null : method.trim();
|
||||
}
|
||||
|
||||
public Integer getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public void setState(Integer state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public String getParams() {
|
||||
return params;
|
||||
}
|
||||
|
||||
public void setParams(String params) {
|
||||
this.params = params;
|
||||
}
|
||||
|
||||
public String getException() {
|
||||
return exception;
|
||||
}
|
||||
|
||||
public void setException(String exception) {
|
||||
this.exception = exception;
|
||||
}
|
||||
|
||||
private String createBy;// 创建者
|
||||
|
||||
public String getCreateBy() {
|
||||
return createBy;
|
||||
}
|
||||
|
||||
public void setCreateBy(String createBy) {
|
||||
this.createBy = createBy;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置请求参数
|
||||
* @param paramMap
|
||||
*/
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void setParams(Map paramMap){
|
||||
if (paramMap == null){
|
||||
return;
|
||||
}
|
||||
StringBuilder params = new StringBuilder();
|
||||
for (Map.Entry<String, String[]> param : ((Map<String, String[]>)paramMap).entrySet()){
|
||||
params.append(("".equals(params.toString()) ? "" : "&") + param.getKey() + "=");
|
||||
String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");
|
||||
params.append(StringUtils.abbr(StringUtils.endsWithIgnoreCase(param.getKey(), "password") ? "" : paramValue, 100));
|
||||
}
|
||||
this.params = params.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return ReflectionToStringBuilder.toString(this);
|
||||
}
|
||||
}
|
||||
253
src/main/java/com/nis/domain/SysMenu.java
Normal file
253
src/main/java/com/nis/domain/SysMenu.java
Normal file
@@ -0,0 +1,253 @@
|
||||
package com.nis.domain;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
|
||||
public class SysMenu extends BaseEntity<SysMenu>{
|
||||
|
||||
private static final long serialVersionUID = 8586837252075033023L;
|
||||
|
||||
|
||||
private SysMenu parent; // 父级菜单
|
||||
|
||||
private Long parentId;
|
||||
|
||||
private String parentIds;
|
||||
|
||||
private String name;
|
||||
|
||||
private Integer sort;
|
||||
|
||||
private String href;
|
||||
|
||||
private String target;
|
||||
|
||||
private String icon;
|
||||
|
||||
private Integer isShow;
|
||||
|
||||
private String permission;
|
||||
|
||||
private SysUser createBy; // 创建者
|
||||
|
||||
private Date createDate;
|
||||
|
||||
private SysUser updateBy;
|
||||
|
||||
private Date updateDate;
|
||||
|
||||
private String remarks;
|
||||
|
||||
private Integer delFlag;
|
||||
|
||||
private Integer quickAction;
|
||||
|
||||
private String menuBg;
|
||||
|
||||
private List<SysMenu> children = new ArrayList<SysMenu>();
|
||||
|
||||
public SysMenu(){
|
||||
super();
|
||||
this.sort = 30;
|
||||
this.isShow = 1;
|
||||
}
|
||||
|
||||
public SysMenu(Long id){
|
||||
super(id);
|
||||
}
|
||||
|
||||
public List<SysMenu> getChildren() {
|
||||
return children;
|
||||
}
|
||||
|
||||
public void setChildren(List<SysMenu> children) {
|
||||
this.children = children;
|
||||
}
|
||||
|
||||
public Long getParentId() {
|
||||
return (parent != null && parent.getId() != null) ? parent.getId() : 0 ;
|
||||
}
|
||||
|
||||
public void setParentId(Long parentId) {
|
||||
this.parentId = parentId;
|
||||
}
|
||||
|
||||
public String getParentIds() {
|
||||
return parentIds;
|
||||
}
|
||||
|
||||
public void setParentIds(String parentIds) {
|
||||
this.parentIds = parentIds == null ? null : parentIds.trim();
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name == null ? null : name.trim();
|
||||
}
|
||||
|
||||
|
||||
public Integer getSort() {
|
||||
return sort;
|
||||
}
|
||||
|
||||
public void setSort(Integer sort) {
|
||||
this.sort = sort;
|
||||
}
|
||||
|
||||
public String getHref() {
|
||||
return href;
|
||||
}
|
||||
|
||||
public void setHref(String href) {
|
||||
this.href = href == null ? null : href.trim();
|
||||
}
|
||||
|
||||
public String getTarget() {
|
||||
return target;
|
||||
}
|
||||
|
||||
public void setTarget(String target) {
|
||||
this.target = target == null ? null : target.trim();
|
||||
}
|
||||
|
||||
public String getIcon() {
|
||||
return icon;
|
||||
}
|
||||
|
||||
public void setIcon(String icon) {
|
||||
this.icon = icon == null ? null : icon.trim();
|
||||
}
|
||||
|
||||
public String getMenuBg() {
|
||||
return menuBg;
|
||||
}
|
||||
|
||||
public void setMenuBg(String menuBg) {
|
||||
this.menuBg = menuBg;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Integer getIsShow() {
|
||||
return isShow;
|
||||
}
|
||||
|
||||
public void setIsShow(Integer isShow) {
|
||||
this.isShow = isShow;
|
||||
}
|
||||
|
||||
public String getPermission() {
|
||||
return permission;
|
||||
}
|
||||
|
||||
public void setPermission(String permission) {
|
||||
this.permission = permission == null ? null : permission.trim();
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Date getCreateDate() {
|
||||
return createDate;
|
||||
}
|
||||
|
||||
public void setCreateDate(Date createDate) {
|
||||
this.createDate = createDate;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public SysUser getCreateBy() {
|
||||
return createBy;
|
||||
}
|
||||
|
||||
public void setCreateBy(SysUser createBy) {
|
||||
this.createBy = createBy;
|
||||
}
|
||||
|
||||
public SysUser getUpdateBy() {
|
||||
return updateBy;
|
||||
}
|
||||
|
||||
public void setUpdateBy(SysUser updateBy) {
|
||||
this.updateBy = updateBy;
|
||||
}
|
||||
|
||||
public Date getUpdateDate() {
|
||||
return updateDate;
|
||||
}
|
||||
|
||||
public void setUpdateDate(Date updateDate) {
|
||||
this.updateDate = updateDate;
|
||||
}
|
||||
|
||||
public String getRemarks() {
|
||||
return remarks;
|
||||
}
|
||||
|
||||
public void setRemarks(String remarks) {
|
||||
this.remarks = remarks == null ? null : remarks.trim();
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Integer getDelFlag() {
|
||||
return delFlag;
|
||||
}
|
||||
|
||||
public void setDelFlag(Integer delFlag) {
|
||||
this.delFlag = delFlag;
|
||||
}
|
||||
|
||||
public Integer getQuickAction() {
|
||||
return quickAction;
|
||||
}
|
||||
|
||||
public void setQuickAction(Integer quickAction) {
|
||||
this.quickAction = quickAction;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public static void sortList(List<SysMenu> list, List<SysMenu> sourcelist, Long parentId, boolean cascade){
|
||||
for (int i=0; i<sourcelist.size(); i++){
|
||||
SysMenu menu = sourcelist.get(i);
|
||||
if (menu.getParent()!=null && menu.getParent().getId()!=null
|
||||
&& menu.getParent().getId().equals(parentId)){
|
||||
list.add(menu);
|
||||
if (cascade){
|
||||
// 判断是否还有子节点, 有则继续获取子节点
|
||||
for (int j=0; j<sourcelist.size(); j++){
|
||||
SysMenu child = sourcelist.get(j);
|
||||
if (child.getParent()!=null && child.getParent().getId()!=null
|
||||
&& child.getParent().getId().equals(menu.getId())){
|
||||
sortList(list, sourcelist, menu.getId(), true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public static Long getRootId(){
|
||||
return 1l;
|
||||
}
|
||||
|
||||
@JsonBackReference
|
||||
public SysMenu getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
public void setParent(SysMenu parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
}
|
||||
221
src/main/java/com/nis/domain/SysOffice.java
Normal file
221
src/main/java/com/nis/domain/SysOffice.java
Normal file
@@ -0,0 +1,221 @@
|
||||
package com.nis.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class SysOffice extends TreeEntity<SysOffice> implements Serializable{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 7057026197597361766L;
|
||||
|
||||
private SysArea area;
|
||||
|
||||
private String code;
|
||||
|
||||
private Integer type;// 机构类型(1:公司;2:部门;3:小组)
|
||||
|
||||
private Integer grade;// 机构等级(1:一级;2:二级;3:三级;4:四级)
|
||||
|
||||
private Integer jobType;//部门职责分类
|
||||
|
||||
private String address;
|
||||
|
||||
private String zipCode;
|
||||
|
||||
private String master;
|
||||
|
||||
private String phone;
|
||||
|
||||
private String fax;
|
||||
|
||||
private String email;
|
||||
|
||||
private Integer useable;
|
||||
|
||||
private SysUser primaryPerson;
|
||||
|
||||
private SysUser deputyPerson;
|
||||
|
||||
private String remarks;
|
||||
|
||||
private Integer delFlag;
|
||||
|
||||
private Date createTime;
|
||||
|
||||
public Date getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(Date createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
private List<String> childDeptList;//快速添加子部门
|
||||
|
||||
public SysOffice(){
|
||||
super();
|
||||
this.type = 2;
|
||||
}
|
||||
|
||||
public SysOffice(Long id){
|
||||
super(id);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code == null ? null : code.trim();
|
||||
}
|
||||
|
||||
public Integer getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(Integer type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public Integer getGrade() {
|
||||
return grade;
|
||||
}
|
||||
|
||||
public void setGrade(Integer grade) {
|
||||
this.grade = grade;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address == null ? null : address.trim();
|
||||
}
|
||||
|
||||
public String getZipCode() {
|
||||
return zipCode;
|
||||
}
|
||||
|
||||
public void setZipCode(String zipCode) {
|
||||
this.zipCode = zipCode == null ? null : zipCode.trim();
|
||||
}
|
||||
|
||||
public String getMaster() {
|
||||
return master;
|
||||
}
|
||||
|
||||
public void setMaster(String master) {
|
||||
this.master = master == null ? null : master.trim();
|
||||
}
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone == null ? null : phone.trim();
|
||||
}
|
||||
|
||||
public String getFax() {
|
||||
return fax;
|
||||
}
|
||||
|
||||
public void setFax(String fax) {
|
||||
this.fax = fax == null ? null : fax.trim();
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email == null ? null : email.trim();
|
||||
}
|
||||
|
||||
public Integer getUseable() {
|
||||
return useable;
|
||||
}
|
||||
|
||||
public void setUseable(Integer useable) {
|
||||
this.useable = useable;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public SysOffice getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
public void setParent(SysOffice parent) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
public SysArea getArea() {
|
||||
return area;
|
||||
}
|
||||
|
||||
public void setArea(SysArea area) {
|
||||
this.area = area;
|
||||
}
|
||||
|
||||
public SysUser getPrimaryPerson() {
|
||||
return primaryPerson;
|
||||
}
|
||||
|
||||
public void setPrimaryPerson(SysUser primaryPerson) {
|
||||
this.primaryPerson = primaryPerson;
|
||||
}
|
||||
|
||||
public SysUser getDeputyPerson() {
|
||||
return deputyPerson;
|
||||
}
|
||||
|
||||
public void setDeputyPerson(SysUser deputyPerson) {
|
||||
this.deputyPerson = deputyPerson;
|
||||
}
|
||||
|
||||
public List<String> getChildDeptList() {
|
||||
return childDeptList;
|
||||
}
|
||||
|
||||
public void setChildDeptList(List<String> childDeptList) {
|
||||
this.childDeptList = childDeptList;
|
||||
}
|
||||
|
||||
public String getRemarks() {
|
||||
return remarks;
|
||||
}
|
||||
|
||||
public void setRemarks(String remarks) {
|
||||
this.remarks = remarks == null ? null : remarks.trim();
|
||||
}
|
||||
|
||||
public Integer getDelFlag() {
|
||||
return delFlag;
|
||||
}
|
||||
|
||||
public void setDelFlag(Integer delFlag) {
|
||||
this.delFlag = delFlag;
|
||||
}
|
||||
|
||||
public Integer getJobType() {
|
||||
return jobType;
|
||||
}
|
||||
|
||||
public void setJobType(Integer jobType) {
|
||||
this.jobType = jobType;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
132
src/main/java/com/nis/domain/SysRole.java
Normal file
132
src/main/java/com/nis/domain/SysRole.java
Normal file
@@ -0,0 +1,132 @@
|
||||
package com.nis.domain;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class SysRole extends BaseEntity<SysRole>{
|
||||
private static final long serialVersionUID = -5388120268433030734L;
|
||||
private String name;
|
||||
public String getOldName() {
|
||||
return oldName;
|
||||
}
|
||||
|
||||
public void setOldName(String oldName) {
|
||||
this.oldName = oldName;
|
||||
}
|
||||
|
||||
private String oldName; // 原角色名称
|
||||
private String roleType;
|
||||
private Integer dataScope;
|
||||
private String remark;
|
||||
private List<SysMenu> menuList = Lists.newArrayList(); // 拥有菜单列表
|
||||
|
||||
|
||||
public List<SysMenu> getMenuList() {
|
||||
return menuList;
|
||||
}
|
||||
|
||||
public void setMenuList(List<SysMenu> menuList) {
|
||||
this.menuList = menuList;
|
||||
}
|
||||
|
||||
public Integer getDataScope() {
|
||||
return dataScope;
|
||||
}
|
||||
|
||||
public void setDataScope(Integer dataScope) {
|
||||
this.dataScope = dataScope;
|
||||
}
|
||||
|
||||
private Integer status;
|
||||
|
||||
private Date createTime;
|
||||
|
||||
// 数据范围(1:所有数据;2:所在公司及以下数据;3:所在公司数据;4:所在部门及以下数据;5:所在部门数据;8:所在单位及以下数据;9:所在单位数据)
|
||||
public static final Integer DATA_SCOPE_ALL = 1;
|
||||
public static final Integer DATA_SCOPE_COMPANY_AND_CHILD = 2;
|
||||
public static final Integer DATA_SCOPE_COMPANY = 3;
|
||||
public static final Integer DATA_SCOPE_OFFICE_AND_CHILD = 4;
|
||||
public static final Integer DATA_SCOPE_OFFICE = 5;
|
||||
public static final Integer DATA_SCOPE_ENTITY_AND_CHILD = 6;
|
||||
public static final Integer DATA_SCOPE_ENTITY = 7;
|
||||
|
||||
|
||||
|
||||
|
||||
public String getRoleType() {
|
||||
return roleType;
|
||||
}
|
||||
|
||||
public void setRoleType(String roleType) {
|
||||
this.roleType = roleType;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name == null ? null : name.trim();
|
||||
}
|
||||
|
||||
|
||||
|
||||
public String getRemark() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setRemark(String remark) {
|
||||
this.remark = remark == null ? null : remark.trim();
|
||||
}
|
||||
|
||||
|
||||
public Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Date getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(Date createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
public List<Long> getMenuIdList() {
|
||||
List<Long> menuIdList = Lists.newArrayList();
|
||||
for (SysMenu menu : menuList) {
|
||||
menuIdList.add(menu.getId());
|
||||
}
|
||||
return menuIdList;
|
||||
}
|
||||
|
||||
public void setMenuIdList(List<String> menuIdList) {
|
||||
menuList = Lists.newArrayList();
|
||||
for (String menuId : menuIdList) {
|
||||
SysMenu menu = new SysMenu();
|
||||
menu.setId(Long.parseLong(menuId));
|
||||
menuList.add(menu);
|
||||
}
|
||||
}
|
||||
|
||||
public String getMenuIds() {
|
||||
return StringUtils.join(getMenuIdList(), ",");
|
||||
}
|
||||
|
||||
public void setMenuIds(String menuIds) {
|
||||
menuList = Lists.newArrayList();
|
||||
if (menuIds != null){
|
||||
String[] ids = StringUtils.split(menuIds, ",");
|
||||
setMenuIdList(Lists.newArrayList(ids));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
243
src/main/java/com/nis/domain/SysUser.java
Normal file
243
src/main/java/com/nis/domain/SysUser.java
Normal file
@@ -0,0 +1,243 @@
|
||||
package com.nis.domain;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.util.Collections3;
|
||||
import com.nis.util.StringUtil;
|
||||
import com.nis.util.StringUtils;
|
||||
import com.nis.util.excel.ExcelField;
|
||||
import com.nis.util.excel.fieldtype.RoleListType;
|
||||
|
||||
|
||||
|
||||
public class SysUser extends BaseEntity<SysUser> {
|
||||
private static final long serialVersionUID = -4871709358302801032L;
|
||||
private String loginId;
|
||||
private String photo; // 头像
|
||||
private String name;
|
||||
private String email;//电子邮箱
|
||||
private String password;
|
||||
private String newPassword; // 新密码
|
||||
private SysRole role;
|
||||
|
||||
|
||||
|
||||
private String oldLoginId;// 原登录名
|
||||
private Date createTime;
|
||||
private Integer status;
|
||||
private Integer identity;//用户身份标识 1-信访办 0-办理人员
|
||||
private List<SysRole> userRoleList = new ArrayList<SysRole>();
|
||||
private SysOffice company;//所属公司
|
||||
private SysOffice entity;//归属单位
|
||||
private SysOffice office;//用户所在部门
|
||||
|
||||
|
||||
|
||||
public SysUser() {
|
||||
super();
|
||||
}
|
||||
|
||||
public SysUser(Long id, String loginId) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.loginId = loginId;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public SysUser(Long id, String loginId, String name, String email,
|
||||
String password, String oldLoginId, Date createTime, Integer status) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.loginId = loginId;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.oldLoginId = oldLoginId;
|
||||
this.createTime = createTime;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getPhoto() {
|
||||
return photo;
|
||||
}
|
||||
|
||||
public void setPhoto(String photo) {
|
||||
this.photo = photo;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public SysOffice getEntity() {
|
||||
return entity;
|
||||
}
|
||||
|
||||
public void setEntity(SysOffice entity) {
|
||||
this.entity = entity;
|
||||
}
|
||||
|
||||
public String getOldLoginId() {
|
||||
return oldLoginId;
|
||||
}
|
||||
public void setOldLoginId(String oldLoginId) {
|
||||
this.oldLoginId = oldLoginId;
|
||||
}
|
||||
|
||||
@ExcelField(title="姓名", align=2, sort=40)
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
public Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public Integer getIdentity() {
|
||||
return identity;
|
||||
}
|
||||
|
||||
public void setIdentity(Integer identity) {
|
||||
this.identity = identity;
|
||||
}
|
||||
|
||||
public SysOffice getOffice() {
|
||||
return office;
|
||||
}
|
||||
|
||||
public void setOffice(SysOffice office) {
|
||||
this.office = office;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public SysOffice getCompany() {
|
||||
return company;
|
||||
}
|
||||
|
||||
public void setCompany(SysOffice company) {
|
||||
this.company = company;
|
||||
}
|
||||
|
||||
public SysRole getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(SysRole role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getNewPassword() {
|
||||
return newPassword;
|
||||
}
|
||||
|
||||
public void setNewPassword(String newPassword) {
|
||||
this.newPassword = newPassword;
|
||||
}
|
||||
|
||||
|
||||
@ExcelField(title="拥有角色", align=1, sort=800, fieldType=RoleListType.class)
|
||||
public List<SysRole> getUserRoleList() {
|
||||
return userRoleList;
|
||||
}
|
||||
|
||||
public void setUserRoleList(List<SysRole> userRoleList) {
|
||||
this.userRoleList = userRoleList;
|
||||
}
|
||||
|
||||
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
|
||||
public boolean isAdmin(){
|
||||
return isAdmin(this.loginId);
|
||||
}
|
||||
|
||||
public static boolean isAdmin(String loginId){
|
||||
return loginId != null && "admin".equals(loginId);
|
||||
}
|
||||
|
||||
|
||||
@JsonIgnore
|
||||
public List<Long> getRoleIdList() {
|
||||
List<Long> roleIdList = Lists.newArrayList();
|
||||
for (SysRole role : userRoleList) {
|
||||
roleIdList.add(role.getId());
|
||||
}
|
||||
return roleIdList;
|
||||
}
|
||||
|
||||
public void setRoleIdList(List<Long> roleIdList) {
|
||||
userRoleList = Lists.newArrayList();
|
||||
for (Long roleId : roleIdList) {
|
||||
SysRole role = new SysRole();
|
||||
role.setId(roleId);
|
||||
userRoleList.add(role);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户拥有的角色名称字符串, 多个角色名称用','分隔.
|
||||
*/
|
||||
public String getRoleNames() {
|
||||
return Collections3.extractToString(userRoleList, "name", ",");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public String getPassword() {
|
||||
return this.password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@ExcelField(title="创建日期", type=1, align=1, sort=110)
|
||||
public Date getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(Date createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
|
||||
@ExcelField(title="登录名", align=1, sort=20)
|
||||
public String getLoginId() {
|
||||
return loginId;
|
||||
}
|
||||
|
||||
public void setLoginId(String loginId) {
|
||||
this.loginId = loginId;
|
||||
}
|
||||
|
||||
@ExcelField(title="邮箱", align=1, sort=50)
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
79
src/main/java/com/nis/domain/TreeEntity.java
Normal file
79
src/main/java/com/nis/domain/TreeEntity.java
Normal file
@@ -0,0 +1,79 @@
|
||||
package com.nis.domain;
|
||||
|
||||
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||
import com.nis.util.Reflections;
|
||||
import com.nis.util.StringUtil;
|
||||
|
||||
/**
|
||||
* 数据Entity类
|
||||
* @author ThinkGem
|
||||
* @version 2014-05-16
|
||||
*/
|
||||
public abstract class TreeEntity<T> extends BaseEntity<T> {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
protected T parent; // 父级编号
|
||||
protected String parentIds; // 所有父级编号
|
||||
protected String name; // 机构名称
|
||||
protected Long sort; // 排序
|
||||
|
||||
public TreeEntity() {
|
||||
super();
|
||||
this.sort = 30L;
|
||||
}
|
||||
|
||||
public TreeEntity(Long id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 父对象,只能通过子类实现,父类实现mybatis无法读取
|
||||
* @return
|
||||
*/
|
||||
@JsonBackReference
|
||||
public abstract T getParent();
|
||||
|
||||
/**
|
||||
* 父对象,只能通过子类实现,父类实现mybatis无法读取
|
||||
* @return
|
||||
*/
|
||||
public abstract void setParent(T parent);
|
||||
|
||||
public String getParentIds() {
|
||||
return parentIds;
|
||||
}
|
||||
|
||||
public void setParentIds(String parentIds) {
|
||||
this.parentIds = parentIds;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Long getSort() {
|
||||
return sort;
|
||||
}
|
||||
|
||||
public void setSort(Long sort) {
|
||||
this.sort = sort;
|
||||
}
|
||||
|
||||
public Long getParentId() {
|
||||
Long id = null;
|
||||
if (parent != null){
|
||||
id = (Long)Reflections.getFieldValue(parent, "id");
|
||||
}
|
||||
return StringUtil.isEmpty(id) ? 0 : id;
|
||||
}
|
||||
|
||||
}
|
||||
29
src/main/java/com/nis/exceptions/ServiceException.java
Normal file
29
src/main/java/com/nis/exceptions/ServiceException.java
Normal file
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.exceptions;
|
||||
|
||||
/**
|
||||
* Service层公用的Exception, 从由Spring管理事务的函数中抛出时会触发事务回滚.
|
||||
* @author ThinkGem
|
||||
*/
|
||||
public class ServiceException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public ServiceException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ServiceException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ServiceException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public ServiceException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
54
src/main/java/com/nis/filter/CORSFilter.java
Normal file
54
src/main/java/com/nis/filter/CORSFilter.java
Normal file
@@ -0,0 +1,54 @@
|
||||
package com.nis.filter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.annotation.WebFilter;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.nis.filter.wrapper.RestHttpServletRequestWrapper;
|
||||
import com.nis.util.Constants;
|
||||
|
||||
/**
|
||||
* @ClassName: CORSFilter
|
||||
* @Description: TODO(解决跨域问题的过滤器)
|
||||
* @author (DDM)
|
||||
* @date 2016年9月20日 上午9:12:50
|
||||
* @version V1.0
|
||||
*/
|
||||
@WebFilter
|
||||
public class CORSFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
//将请求封装起来,使得body中的内容可以多次获取
|
||||
req=new RestHttpServletRequestWrapper((HttpServletRequest)req);
|
||||
HttpServletResponse response=(HttpServletResponse) res;
|
||||
response.setHeader("Access-Control-Allow-Origin",Constants.TARGET_URL);
|
||||
response.setHeader("Access-Control-Allow-Methods","POST,GET,PUT,OPT,IONS,DELETE");
|
||||
response.setHeader("Access-Control-Max-Age",Constants.ACCESS_CONTROL_MAX_AGE);
|
||||
response.setHeader("Access-Control-Allow-Headers","*");
|
||||
chain.doFilter(req, res);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig arg0) throws ServletException {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
*@Title: HttpServletRequestWrapper.java
|
||||
*@Package com.nis.filter.wrapper
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年11月15日 下午12:36:14
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.filter.wrapper;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
import javax.servlet.ReadListener;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
|
||||
/**
|
||||
* @ClassName: HttpServletRequestWrapper.java
|
||||
* @Description: 主要目的是将request的body取出来,然后缓存起来。这样可以实现request的body多次取
|
||||
* @author (wx)
|
||||
* @date 2016年11月15日 下午12:36:14
|
||||
* @version V1.0
|
||||
*/
|
||||
public class RestHttpServletRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper {
|
||||
private final byte[] body;
|
||||
/**
|
||||
* 创建一个新的实例 RestHttpServletRequestWrapper.
|
||||
*
|
||||
* @param request
|
||||
* @throws IOException
|
||||
*/
|
||||
public RestHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
|
||||
super(request);
|
||||
// TODO Auto-generated constructor stub
|
||||
body=StreamUtils.copyToByteArray(request.getInputStream());
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see javax.servlet.ServletRequestWrapper#getInputStream()
|
||||
*/
|
||||
@Override
|
||||
public ServletInputStream getInputStream() throws IOException {
|
||||
// TODO Auto-generated method stub
|
||||
final ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(body);
|
||||
return new ServletInputStream(){
|
||||
|
||||
@Override
|
||||
public boolean isFinished() {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isReady() {
|
||||
// TODO Auto-generated method stub
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setReadListener(ReadListener arg0) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
// TODO Auto-generated method stub
|
||||
return byteArrayInputStream.read();
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
/* (non-Javadoc)
|
||||
* @see javax.servlet.ServletRequestWrapper#getReader()
|
||||
*/
|
||||
@Override
|
||||
public BufferedReader getReader() throws IOException {
|
||||
// TODO Auto-generated method stub
|
||||
return new BufferedReader(new InputStreamReader(getInputStream()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.nis.interceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import com.nis.datasource.CustomerContextHolder;
|
||||
|
||||
public class DataSourceBInterceptor implements HandlerInterceptor {
|
||||
Logger logger = Logger.getLogger(DataSourceBInterceptor.class);
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request,
|
||||
HttpServletResponse response, Object handler) throws Exception {
|
||||
logger.info("开启数据源配置操作库---");
|
||||
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_B);//开启数据源B
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(HttpServletRequest request,
|
||||
HttpServletResponse response, Object handler,
|
||||
ModelAndView modelAndView) throws Exception {
|
||||
logger.info("postHandle---");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request,
|
||||
HttpServletResponse response, Object handler, Exception ex)
|
||||
throws Exception {
|
||||
|
||||
CustomerContextHolder.clearCustomerType();
|
||||
logger.info("释放数据源配置操作库---");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.nis.interceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import com.nis.datasource.CustomerContextHolder;
|
||||
import com.nis.util.Constants;
|
||||
|
||||
public class DataSourceCInterceptor implements HandlerInterceptor {
|
||||
Logger logger = Logger.getLogger(DataSourceCInterceptor.class);
|
||||
String searchActiveSys="";
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request,
|
||||
HttpServletResponse response, Object handler) throws Exception {
|
||||
searchActiveSys=request.getParameter("searchActiveSys");
|
||||
if(searchActiveSys == null
|
||||
|| !(Constants.ACTIVESYS_A.equals(searchActiveSys)
|
||||
|| Constants.ACTIVESYS_C.equals(searchActiveSys))
|
||||
) searchActiveSys=Constants.ACTIVESYS_B;
|
||||
if(Constants.ACTIVESYS_A.equals(searchActiveSys)){
|
||||
logger.info("开启数据源日志A操作库---"+System.currentTimeMillis());
|
||||
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_F);//开启数据源F
|
||||
}else if(Constants.ACTIVESYS_C.equals(searchActiveSys)){
|
||||
logger.info("开启数据源日志C操作库---"+System.currentTimeMillis());
|
||||
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_G);//开启数据源F
|
||||
}else{
|
||||
logger.info("开启数据源日志B操作库---"+System.currentTimeMillis());
|
||||
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_C);//开启数据源C
|
||||
}
|
||||
logger.info("日志数据源开启成功---"+System.currentTimeMillis());
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
|
||||
throws Exception {
|
||||
logger.info("postHandle---");
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request,
|
||||
HttpServletResponse response, Object handler, Exception ex)
|
||||
throws Exception {
|
||||
CustomerContextHolder.clearCustomerType();
|
||||
logger.info("释放数据源日志操作库---");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.nis.interceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import com.nis.datasource.CustomerContextHolder;
|
||||
|
||||
public class DataSourceDInterceptor implements HandlerInterceptor {
|
||||
Logger logger = Logger.getLogger(DataSourceDInterceptor.class);
|
||||
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request,
|
||||
HttpServletResponse response, Object handler) throws Exception {
|
||||
logger.info("开启测试配置库---");
|
||||
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_D);//开启数据源C
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
|
||||
throws Exception {
|
||||
logger.info("postHandle---");
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request,
|
||||
HttpServletResponse response, Object handler, Exception ex)
|
||||
throws Exception {
|
||||
CustomerContextHolder.clearCustomerType();
|
||||
logger.info("释放测试配置库---");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.nis.interceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import com.nis.datasource.CustomerContextHolder;
|
||||
|
||||
public class DataSourceEInterceptor implements HandlerInterceptor {
|
||||
Logger logger = Logger.getLogger(DataSourceEInterceptor.class);
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
|
||||
throws Exception {
|
||||
CustomerContextHolder.clearCustomerType();
|
||||
logger.info("释放数据静控操作库---");
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
|
||||
throws Exception {
|
||||
logger.info("postHandle---");
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
|
||||
logger.info("开启数据源静控操作库---");
|
||||
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_E);//开启数据源C
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
74
src/main/java/com/nis/interceptor/LogInterceptor.java
Normal file
74
src/main/java/com/nis/interceptor/LogInterceptor.java
Normal file
@@ -0,0 +1,74 @@
|
||||
package com.nis.interceptor;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.core.NamedThreadLocal;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import com.nis.util.DateUtils;
|
||||
import com.nis.util.LogUtils;
|
||||
import com.nis.web.service.BaseService;
|
||||
|
||||
public class LogInterceptor extends BaseService implements HandlerInterceptor{
|
||||
|
||||
private static final ThreadLocal<Long> timeThreadLocal =
|
||||
new NamedThreadLocal<Long>("ThreadLocal StartTime");
|
||||
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
|
||||
throws Exception {
|
||||
long beginTime = System.currentTimeMillis();//1、开始时间
|
||||
timeThreadLocal.set(beginTime); //线程绑定变量(该数据只有当前请求的线程可见)
|
||||
if (logger.isDebugEnabled()){
|
||||
logger.debug("开始计时: {} URI: {}", new SimpleDateFormat("hh:mm:ss.SSS")
|
||||
.format(beginTime), request.getRequestURI());
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
|
||||
ModelAndView modelAndView) throws Exception {
|
||||
if (modelAndView != null){
|
||||
logger.info("ViewName: " + modelAndView.getViewName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
|
||||
throws Exception {
|
||||
long beginTime = timeThreadLocal.get();//得到线程绑定的局部变量(开始时间)
|
||||
long endTime = System.currentTimeMillis(); //2、结束时间
|
||||
|
||||
long consumerTime = endTime - beginTime;
|
||||
|
||||
// 打印JVM信息。
|
||||
if (logger.isDebugEnabled()){
|
||||
|
||||
Object[] params = new Object[]{
|
||||
new SimpleDateFormat("hh:mm:ss.SSS").format(endTime)
|
||||
, DateUtils.formatDateTime(consumerTime)
|
||||
,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};
|
||||
logger.debug("计时结束:{} 耗时:{} URI: {} 最大内存: {}m 已分配内存: {}m 已分配内存中的剩余空间: {}m 最大可用内存: {}m",params);
|
||||
|
||||
}
|
||||
|
||||
// 保存日志
|
||||
LogUtils.saveLog(request, handler, ex, null, consumerTime);
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
37
src/main/java/com/nis/listener/SystemConfigListener.java
Normal file
37
src/main/java/com/nis/listener/SystemConfigListener.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package com.nis.listener;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.context.support.WebApplicationContextUtils;
|
||||
|
||||
import com.nis.datasource.CustomerContextHolder;
|
||||
|
||||
/**
|
||||
* 项目启动时加载数据字典
|
||||
*
|
||||
* @author RenKaiGe-Office
|
||||
* @Date:2016-11-03
|
||||
*/
|
||||
public class SystemConfigListener extends ContextLoaderListener {
|
||||
private static WebApplicationContext webApplicationContext;
|
||||
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent event) {
|
||||
try {
|
||||
CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_B);
|
||||
webApplicationContext = WebApplicationContextUtils
|
||||
.getRequiredWebApplicationContext(event.getServletContext());
|
||||
CustomerContextHolder.clearCustomerType();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
|
||||
/**
|
||||
* Cluster方言的实现[神通数据库]
|
||||
*
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class ClusterDialect implements Dialect {
|
||||
|
||||
|
||||
@Override
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
return getLimitString(sql, offset, Integer.toString(offset),
|
||||
Integer.toString(limit));
|
||||
}
|
||||
|
||||
public boolean supportsLimit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
|
||||
* <pre>
|
||||
* 如mysql
|
||||
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
|
||||
* select * from user limit :offset,:limit
|
||||
* </pre>
|
||||
*
|
||||
* @param sql 实际SQL语句
|
||||
* @param offset 分页开始纪录条数
|
||||
* @param offsetPlaceholder 分页开始纪录条数-占位符号
|
||||
* @param limitPlaceholder 分页纪录条数占位符号
|
||||
* @return 包含占位符的分页sql
|
||||
*/
|
||||
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
|
||||
StringBuilder stringBuilder = new StringBuilder(sql);
|
||||
if(stringBuilder.indexOf("limit") == -1 && stringBuilder.indexOf("LIMIT") == -1 ){
|
||||
stringBuilder.append(" limit ");
|
||||
stringBuilder.append(limitPlaceholder);
|
||||
stringBuilder.append(" offset ");
|
||||
stringBuilder.append(offsetPlaceholder);
|
||||
}
|
||||
System.out.println("cluster分页sql:"+stringBuilder.toString());
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
88
src/main/java/com/nis/persistence/dialect/DB2Dialect.java
Normal file
88
src/main/java/com/nis/persistence/dialect/DB2Dialect.java
Normal file
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
|
||||
/**
|
||||
* DB2的分页数据库方言实现
|
||||
*
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class DB2Dialect implements Dialect {
|
||||
@Override
|
||||
public boolean supportsLimit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
private static String getRowNumber(String sql) {
|
||||
StringBuilder rownumber = new StringBuilder(50)
|
||||
.append("rownumber() over(");
|
||||
|
||||
int orderByIndex = sql.toLowerCase().indexOf("order by");
|
||||
|
||||
if (orderByIndex > 0 && !hasDistinct(sql)) {
|
||||
rownumber.append(sql.substring(orderByIndex));
|
||||
}
|
||||
|
||||
rownumber.append(") as rownumber_,");
|
||||
|
||||
return rownumber.toString();
|
||||
}
|
||||
|
||||
private static boolean hasDistinct(String sql) {
|
||||
return sql.toLowerCase().contains("select distinct");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
return getLimitString(sql, offset, Integer.toString(offset), Integer.toString(limit));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
|
||||
* <pre>
|
||||
* 如mysql
|
||||
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
|
||||
* select * from user limit :offset,:limit
|
||||
* </pre>
|
||||
*
|
||||
* @param sql 实际SQL语句
|
||||
* @param offset 分页开始纪录条数
|
||||
* @param offsetPlaceholder 分页开始纪录条数-占位符号
|
||||
* @param limitPlaceholder 分页纪录条数占位符号
|
||||
* @return 包含占位符的分页sql
|
||||
*/
|
||||
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
|
||||
int startOfSelect = sql.toLowerCase().indexOf("select");
|
||||
|
||||
StringBuilder pagingSelect = new StringBuilder(sql.length() + 100)
|
||||
.append(sql.substring(0, startOfSelect)) //add the comment
|
||||
.append("select * from ( select ") //nest the main query in an outer select
|
||||
.append(getRowNumber(sql)); //add the rownnumber bit into the outer query select list
|
||||
|
||||
if (hasDistinct(sql)) {
|
||||
pagingSelect.append(" row_.* from ( ") //add another (inner) nested select
|
||||
.append(sql.substring(startOfSelect)) //add the main query
|
||||
.append(" ) as row_"); //close off the inner nested select
|
||||
} else {
|
||||
pagingSelect.append(sql.substring(startOfSelect + 6)); //add the main query
|
||||
}
|
||||
|
||||
pagingSelect.append(" ) as temp_ where rownumber_ ");
|
||||
|
||||
//add the restriction to the outer select
|
||||
if (offset > 0) {
|
||||
// int end = offset + limit;
|
||||
String endString = offsetPlaceholder + "+" + limitPlaceholder;
|
||||
pagingSelect.append("between ").append(offsetPlaceholder)
|
||||
.append("+1 and ").append(endString);
|
||||
} else {
|
||||
pagingSelect.append("<= ").append(limitPlaceholder);
|
||||
}
|
||||
|
||||
return pagingSelect.toString();
|
||||
}
|
||||
}
|
||||
43
src/main/java/com/nis/persistence/dialect/DerbyDialect.java
Normal file
43
src/main/java/com/nis/persistence/dialect/DerbyDialect.java
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
|
||||
/**
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class DerbyDialect implements Dialect {
|
||||
@Override
|
||||
public boolean supportsLimit() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
// return getLimitString(sql,offset,Integer.toString(offset),limit,Integer.toString(limit));
|
||||
throw new UnsupportedOperationException("paged queries not supported");
|
||||
}
|
||||
|
||||
/**
|
||||
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
|
||||
* <pre>
|
||||
* 如mysql
|
||||
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
|
||||
* select * from user limit :offset,:limit
|
||||
* </pre>
|
||||
*
|
||||
* @param sql 实际SQL语句
|
||||
* @param offset 分页开始纪录条数
|
||||
* @param offsetPlaceholder 分页开始纪录条数-占位符号
|
||||
* @param limit 分页每页显示纪录条数
|
||||
* @param limitPlaceholder 分页纪录条数占位符号
|
||||
* @return 包含占位符的分页sql
|
||||
*/
|
||||
public String getLimitString(String sql, int offset,String offsetPlaceholder, int limit, String limitPlaceholder) {
|
||||
throw new UnsupportedOperationException( "paged queries not supported" );
|
||||
}
|
||||
|
||||
}
|
||||
33
src/main/java/com/nis/persistence/dialect/Dialect.java
Normal file
33
src/main/java/com/nis/persistence/dialect/Dialect.java
Normal file
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
/**
|
||||
* 类似hibernate的Dialect,但只精简出分页部分
|
||||
*
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2011-11-18 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public interface Dialect {
|
||||
|
||||
/**
|
||||
* 数据库本身是否支持分页当前的分页查询方式
|
||||
* 如果数据库不支持的话,则不进行数据库分页
|
||||
*
|
||||
* @return true:支持当前的分页查询方式
|
||||
*/
|
||||
public boolean supportsLimit();
|
||||
|
||||
/**
|
||||
* 将sql转换为分页SQL,分别调用分页sql
|
||||
*
|
||||
* @param sql SQL语句
|
||||
* @param offset 开始条数
|
||||
* @param limit 每页显示多少纪录条数
|
||||
* @return 分页查询的sql
|
||||
*/
|
||||
public String getLimitString(String sql, int offset, int limit);
|
||||
|
||||
}
|
||||
44
src/main/java/com/nis/persistence/dialect/H2Dialect.java
Normal file
44
src/main/java/com/nis/persistence/dialect/H2Dialect.java
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
|
||||
/**
|
||||
* A dialect compatible with the H2 database.
|
||||
*
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class H2Dialect implements Dialect {
|
||||
|
||||
public boolean supportsLimit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
|
||||
* <pre>
|
||||
* 如mysql
|
||||
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
|
||||
* select * from user limit :offset,:limit
|
||||
* </pre>
|
||||
*
|
||||
* @param sql 实际SQL语句
|
||||
* @param offset 分页开始纪录条数
|
||||
* @param offsetPlaceholder 分页开始纪录条数-占位符号
|
||||
* @param limit 分页每页显示纪录条数
|
||||
* @param limitPlaceholder 分页纪录条数占位符号
|
||||
* @return 包含占位符的分页sql
|
||||
*/
|
||||
private String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
|
||||
return sql + ((offset > 0) ? " limit " + limitPlaceholder + " offset "
|
||||
+ offsetPlaceholder : " limit " + limitPlaceholder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
return getLimitString(sql, offset, Integer.toString(offset), limit, Integer.toString(limit));
|
||||
}
|
||||
}
|
||||
49
src/main/java/com/nis/persistence/dialect/HSQLDialect.java
Normal file
49
src/main/java/com/nis/persistence/dialect/HSQLDialect.java
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
|
||||
/**
|
||||
* Dialect for HSQLDB
|
||||
*
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class HSQLDialect implements Dialect {
|
||||
@Override
|
||||
public boolean supportsLimit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
return getLimitString(sql, offset, Integer.toString(offset),
|
||||
Integer.toString(limit));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
|
||||
* <pre>
|
||||
* 如mysql
|
||||
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
|
||||
* select * from user limit :offset,:limit
|
||||
* </pre>
|
||||
*
|
||||
* @param sql 实际SQL语句
|
||||
* @param offset 分页开始纪录条数
|
||||
* @param offsetPlaceholder 分页开始纪录条数-占位符号
|
||||
* @param limitPlaceholder 分页纪录条数占位符号
|
||||
* @return 包含占位符的分页sql
|
||||
*/
|
||||
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
|
||||
boolean hasOffset = offset > 0;
|
||||
return
|
||||
new StringBuffer(sql.length() + 10)
|
||||
.append(sql)
|
||||
.insert(sql.toLowerCase().indexOf("select") + 6, hasOffset ? " limit " + offsetPlaceholder + " " + limitPlaceholder : " top " + limitPlaceholder)
|
||||
.toString();
|
||||
}
|
||||
|
||||
}
|
||||
52
src/main/java/com/nis/persistence/dialect/MySQLDialect.java
Normal file
52
src/main/java/com/nis/persistence/dialect/MySQLDialect.java
Normal file
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
|
||||
/**
|
||||
* Mysql方言的实现
|
||||
*
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class MySQLDialect implements Dialect {
|
||||
|
||||
|
||||
@Override
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
return getLimitString(sql, offset, Integer.toString(offset),
|
||||
Integer.toString(limit));
|
||||
}
|
||||
|
||||
public boolean supportsLimit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
|
||||
* <pre>
|
||||
* 如mysql
|
||||
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
|
||||
* select * from user limit :offset,:limit
|
||||
* </pre>
|
||||
*
|
||||
* @param sql 实际SQL语句
|
||||
* @param offset 分页开始纪录条数
|
||||
* @param offsetPlaceholder 分页开始纪录条数-占位符号
|
||||
* @param limitPlaceholder 分页纪录条数占位符号
|
||||
* @return 包含占位符的分页sql
|
||||
*/
|
||||
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
|
||||
StringBuilder stringBuilder = new StringBuilder(sql);
|
||||
stringBuilder.append(" limit ");
|
||||
if (offset > 0) {
|
||||
stringBuilder.append(offsetPlaceholder).append(",").append(limitPlaceholder);
|
||||
} else {
|
||||
stringBuilder.append(limitPlaceholder);
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
67
src/main/java/com/nis/persistence/dialect/OracleDialect.java
Normal file
67
src/main/java/com/nis/persistence/dialect/OracleDialect.java
Normal file
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
|
||||
/**
|
||||
* Oracle的方言实现
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class OracleDialect implements Dialect {
|
||||
@Override
|
||||
public boolean supportsLimit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
return getLimitString(sql, offset, Integer.toString(offset), Integer.toString(limit));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
|
||||
* <pre>
|
||||
* 如mysql
|
||||
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
|
||||
* select * from user limit :offset,:limit
|
||||
* </pre>
|
||||
*
|
||||
* @param sql 实际SQL语句
|
||||
* @param offset 分页开始纪录条数
|
||||
* @param offsetPlaceholder 分页开始纪录条数-占位符号
|
||||
* @param limitPlaceholder 分页纪录条数占位符号
|
||||
* @return 包含占位符的分页sql
|
||||
*/
|
||||
public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) {
|
||||
sql = sql.trim();
|
||||
boolean isForUpdate = false;
|
||||
if (sql.toLowerCase().endsWith(" for update")) {
|
||||
sql = sql.substring(0, sql.length() - 11);
|
||||
isForUpdate = true;
|
||||
}
|
||||
StringBuilder pagingSelect = new StringBuilder(sql.length() + 100);
|
||||
|
||||
if (offset > 0) {
|
||||
pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
|
||||
} else {
|
||||
pagingSelect.append("select * from ( ");
|
||||
}
|
||||
pagingSelect.append(sql);
|
||||
if (offset > 0) {
|
||||
String endString = offsetPlaceholder + "+" + limitPlaceholder;
|
||||
pagingSelect.append(" ) row_ where rownum <= "+endString+") where rownum_ > ").append(offsetPlaceholder);
|
||||
} else {
|
||||
pagingSelect.append(" ) where rownum <= "+limitPlaceholder);
|
||||
}
|
||||
|
||||
if (isForUpdate) {
|
||||
pagingSelect.append(" for update");
|
||||
}
|
||||
|
||||
return pagingSelect.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
|
||||
/**
|
||||
* Postgre Sql的方言实现
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class PostgreSQLDialect implements Dialect {
|
||||
|
||||
public boolean supportsLimit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
return getLimitString(sql, offset, Integer.toString(offset),
|
||||
Integer.toString(limit));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
|
||||
* <pre>
|
||||
* 如mysql
|
||||
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
|
||||
* select * from user limit :offset,:limit
|
||||
* </pre>
|
||||
*
|
||||
* @param sql 实际SQL语句
|
||||
* @param offset 分页开始纪录条数
|
||||
* @param offsetPlaceholder 分页开始纪录条数-占位符号
|
||||
* @param limitPlaceholder 分页纪录条数占位符号
|
||||
* @return 包含占位符的分页sql
|
||||
*/
|
||||
public String getLimitString(String sql, int offset,
|
||||
String offsetPlaceholder, String limitPlaceholder) {
|
||||
StringBuilder pageSql = new StringBuilder().append(sql);
|
||||
pageSql = offset <= 0
|
||||
? pageSql.append(" limit ").append(limitPlaceholder) :
|
||||
pageSql.append(" limit ").append(limitPlaceholder).append(" offset ").append(offsetPlaceholder);
|
||||
return pageSql.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Sql 2005的方言实现
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class SQLServer2005Dialect implements Dialect {
|
||||
|
||||
@Override
|
||||
public boolean supportsLimit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
return getLimitString(sql, offset,
|
||||
limit, Integer.toString(limit));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a LIMIT clause to the given SQL SELECT
|
||||
* <p/>
|
||||
* The LIMIT SQL will look like:
|
||||
* <p/>
|
||||
* WITH query AS
|
||||
* (SELECT TOP 100 percent ROW_NUMBER() OVER (ORDER BY CURRENT_TIMESTAMP) as __row_number__, * from table_name)
|
||||
* SELECT *
|
||||
* FROM query
|
||||
* WHERE __row_number__ BETWEEN :offset and :lastRows
|
||||
* ORDER BY __row_number__
|
||||
*
|
||||
* @param querySqlString The SQL statement to base the limit query off of.
|
||||
* @param offset Offset of the first row to be returned by the query (zero-based)
|
||||
* @param limit Maximum number of rows to be returned by the query
|
||||
* @param limitPlaceholder limitPlaceholder
|
||||
* @return A new SQL statement with the LIMIT clause applied.
|
||||
*/
|
||||
private String getLimitString(String querySqlString, int offset, int limit, String limitPlaceholder) {
|
||||
StringBuilder pagingBuilder = new StringBuilder();
|
||||
String orderby = getOrderByPart(querySqlString);
|
||||
String distinctStr = "";
|
||||
|
||||
String loweredString = querySqlString.toLowerCase();
|
||||
String sqlPartString = querySqlString;
|
||||
if (loweredString.trim().startsWith("select")) {
|
||||
int index = 6;
|
||||
if (loweredString.startsWith("select distinct")) {
|
||||
distinctStr = "DISTINCT ";
|
||||
index = 15;
|
||||
}
|
||||
sqlPartString = sqlPartString.substring(index);
|
||||
}
|
||||
pagingBuilder.append(sqlPartString);
|
||||
|
||||
// if no ORDER BY is specified use fake ORDER BY field to avoid errors
|
||||
if (StringUtils.isEmpty(orderby)) {
|
||||
orderby = "ORDER BY CURRENT_TIMESTAMP";
|
||||
}
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
result.append("WITH query AS (SELECT ")
|
||||
.append(distinctStr)
|
||||
.append("TOP 100 PERCENT ")
|
||||
.append(" ROW_NUMBER() OVER (")
|
||||
.append(orderby)
|
||||
.append(") as __row_number__, ")
|
||||
.append(pagingBuilder)
|
||||
.append(") SELECT * FROM query WHERE __row_number__ BETWEEN ")
|
||||
.append(offset).append(" AND ").append(offset + limit)
|
||||
.append(" ORDER BY __row_number__");
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
static String getOrderByPart(String sql) {
|
||||
String loweredString = sql.toLowerCase();
|
||||
int orderByIndex = loweredString.indexOf("order by");
|
||||
if (orderByIndex != -1) {
|
||||
// if we find a new "order by" then we need to ignore
|
||||
// the previous one since it was probably used for a subquery
|
||||
return sql.substring(orderByIndex);
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
|
||||
/**
|
||||
* MSSQLServer 数据库实现分页方言
|
||||
*
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class SQLServerDialect implements Dialect {
|
||||
|
||||
public boolean supportsLimit() {
|
||||
return true;
|
||||
}
|
||||
|
||||
static int getAfterSelectInsertPoint(String sql) {
|
||||
int selectIndex = sql.toLowerCase().indexOf("select");
|
||||
final int selectDistinctIndex = sql.toLowerCase().indexOf("select distinct");
|
||||
return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6);
|
||||
}
|
||||
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
return getLimit(sql, offset, limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
|
||||
* <pre>
|
||||
* 如mysql
|
||||
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
|
||||
* select * from user limit :offset,:limit
|
||||
* </pre>
|
||||
*
|
||||
* @param sql 实际SQL语句
|
||||
* @param offset 分页开始纪录条数
|
||||
* @param limit 分页每页显示纪录条数
|
||||
* @return 包含占位符的分页sql
|
||||
*/
|
||||
public String getLimit(String sql, int offset, int limit) {
|
||||
if (offset > 0) {
|
||||
throw new UnsupportedOperationException("sql server has no offset");
|
||||
}
|
||||
return new StringBuffer(sql.length() + 8)
|
||||
.append(sql)
|
||||
.insert(getAfterSelectInsertPoint(sql), " top " + limit)
|
||||
.toString();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
46
src/main/java/com/nis/persistence/dialect/SybaseDialect.java
Normal file
46
src/main/java/com/nis/persistence/dialect/SybaseDialect.java
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.dialect;
|
||||
|
||||
|
||||
/**
|
||||
* Sybase数据库分页方言实现。
|
||||
* 还未实现
|
||||
*
|
||||
* @author poplar.yfyang
|
||||
* @version 1.0 2010-10-10 下午12:31
|
||||
* @since JDK 1.5
|
||||
*/
|
||||
public class SybaseDialect implements Dialect {
|
||||
|
||||
public boolean supportsLimit() {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getLimitString(String sql, int offset, int limit) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
|
||||
* <pre>
|
||||
* 如mysql
|
||||
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
|
||||
* select * from user limit :offset,:limit
|
||||
* </pre>
|
||||
*
|
||||
* @param sql 实际SQL语句
|
||||
* @param offset 分页开始纪录条数
|
||||
* @param offsetPlaceholder 分页开始纪录条数-占位符号
|
||||
* @param limit 分页每页显示纪录条数
|
||||
* @param limitPlaceholder 分页纪录条数占位符号
|
||||
* @return 包含占位符的分页sql
|
||||
*/
|
||||
public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
|
||||
throw new UnsupportedOperationException("paged queries not supported");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.interceptor;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.apache.ibatis.logging.Log;
|
||||
import org.apache.ibatis.logging.LogFactory;
|
||||
import org.apache.ibatis.plugin.Interceptor;
|
||||
|
||||
import com.nis.domain.Page;
|
||||
import com.nis.util.Reflections;
|
||||
|
||||
/**
|
||||
* Mybatis分页拦截器基类
|
||||
* @author poplar.yfyang / thinkgem
|
||||
* @version 2013-8-28
|
||||
*/
|
||||
public abstract class BaseInterceptor implements Interceptor, Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
protected static final String PAGE = "page";
|
||||
|
||||
protected static final String DELEGATE = "delegate";
|
||||
|
||||
protected static final String MAPPED_STATEMENT = "mappedStatement";
|
||||
|
||||
protected Log log = LogFactory.getLog(this.getClass());
|
||||
|
||||
|
||||
// /**
|
||||
// * 拦截的ID,在mapper中的id,可以匹配正则
|
||||
// */
|
||||
// protected String _SQL_PATTERN = "";
|
||||
|
||||
/**
|
||||
* 对参数进行转换和检查
|
||||
* @param parameterObject 参数对象
|
||||
* @param page 分页对象
|
||||
* @return 分页对象
|
||||
* @throws NoSuchFieldException 无法找到参数
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
protected static Page<Object> convertParameter(Object parameterObject, Page<Object> page) {
|
||||
try{
|
||||
if (parameterObject instanceof Page) {
|
||||
return (Page<Object>) parameterObject;
|
||||
} else {
|
||||
return (Page<Object>)Reflections.getFieldValue(parameterObject, PAGE);
|
||||
}
|
||||
}catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.nis.persistence.interceptor;
|
||||
|
||||
import org.apache.ibatis.executor.Executor;
|
||||
import org.apache.ibatis.mapping.BoundSql;
|
||||
import org.apache.ibatis.mapping.MappedStatement;
|
||||
import org.apache.ibatis.mapping.SqlSource;
|
||||
import org.apache.ibatis.plugin.Intercepts;
|
||||
import org.apache.ibatis.plugin.Invocation;
|
||||
import org.apache.ibatis.plugin.Plugin;
|
||||
import org.apache.ibatis.plugin.Signature;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.apache.ibatis.session.ResultHandler;
|
||||
import org.apache.ibatis.session.RowBounds;
|
||||
|
||||
import com.nis.domain.Page;
|
||||
import com.nis.util.Reflections;
|
||||
import com.nis.util.StringUtils;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* 数据库分页插件,只拦截查询语句.
|
||||
* @author poplar.yfyang / thinkgem
|
||||
* @version 2013-8-28
|
||||
*/
|
||||
@Intercepts({@Signature(type = Executor.class, method = "query",
|
||||
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
|
||||
public class PaginationInterceptor extends BaseInterceptor {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public Object intercept(Invocation invocation) throws Throwable {
|
||||
|
||||
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];
|
||||
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
|
||||
Object parameterObject = boundSql.getParameterObject();
|
||||
|
||||
//获取分页参数对象
|
||||
Page<Object> page = null;
|
||||
|
||||
if (parameterObject != null) {
|
||||
page = convertParameter(parameterObject, page);
|
||||
}
|
||||
|
||||
//如果设置了分页对象,则进行分页
|
||||
if (page != null && page.getPageSize() != -1) {
|
||||
|
||||
if (StringUtils.isBlank(boundSql.getSql())){
|
||||
return null;
|
||||
}
|
||||
String originalSql = boundSql.getSql().trim();
|
||||
|
||||
//得到总记录数
|
||||
if(page.getCount() == -1l){
|
||||
page.setCount(0);
|
||||
}else{
|
||||
page.setCount(SQLHelper.getCount(originalSql, null, mappedStatement, parameterObject, boundSql, log));
|
||||
}
|
||||
|
||||
//分页查询 本地化对象 修改数据库注意修改实现
|
||||
String pageSql = SQLHelper.generatePageSql(originalSql, page);
|
||||
// if (log.isDebugEnabled()) {
|
||||
// log.debug("PAGE SQL:" + StringUtils.replace(pageSql, "\n", ""));
|
||||
// }
|
||||
invocation.getArgs()[2] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);
|
||||
BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), pageSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
|
||||
//解决MyBatis 分页foreach 参数失效 start
|
||||
if (Reflections.getFieldValue(boundSql, "metaParameters") != null) {
|
||||
MetaObject mo = (MetaObject) Reflections.getFieldValue(boundSql, "metaParameters");
|
||||
Reflections.setFieldValue(newBoundSql, "metaParameters", mo);
|
||||
}
|
||||
//解决MyBatis 分页foreach 参数失效 end
|
||||
MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
|
||||
|
||||
invocation.getArgs()[0] = newMs;
|
||||
}
|
||||
// }
|
||||
return invocation.proceed();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Object plugin(Object target) {
|
||||
return Plugin.wrap(target, this);
|
||||
}
|
||||
|
||||
|
||||
private MappedStatement copyFromMappedStatement(MappedStatement ms,
|
||||
SqlSource newSqlSource) {
|
||||
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(),
|
||||
ms.getId(), newSqlSource, ms.getSqlCommandType());
|
||||
builder.resource(ms.getResource());
|
||||
builder.fetchSize(ms.getFetchSize());
|
||||
builder.statementType(ms.getStatementType());
|
||||
builder.keyGenerator(ms.getKeyGenerator());
|
||||
if (ms.getKeyProperties() != null) {
|
||||
for (String keyProperty : ms.getKeyProperties()) {
|
||||
builder.keyProperty(keyProperty);
|
||||
}
|
||||
}
|
||||
builder.timeout(ms.getTimeout());
|
||||
builder.parameterMap(ms.getParameterMap());
|
||||
builder.resultMaps(ms.getResultMaps());
|
||||
builder.cache(ms.getCache());
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
public static class BoundSqlSqlSource implements SqlSource {
|
||||
BoundSql boundSql;
|
||||
|
||||
public BoundSqlSqlSource(BoundSql boundSql) {
|
||||
this.boundSql = boundSql;
|
||||
}
|
||||
|
||||
public BoundSql getBoundSql(Object parameterObject) {
|
||||
return boundSql;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setProperties(Properties properties) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.persistence.interceptor;
|
||||
|
||||
import org.apache.ibatis.executor.statement.BaseStatementHandler;
|
||||
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
|
||||
import org.apache.ibatis.executor.statement.StatementHandler;
|
||||
import org.apache.ibatis.mapping.BoundSql;
|
||||
import org.apache.ibatis.mapping.MappedStatement;
|
||||
import org.apache.ibatis.plugin.Intercepts;
|
||||
import org.apache.ibatis.plugin.Invocation;
|
||||
import org.apache.ibatis.plugin.Plugin;
|
||||
import org.apache.ibatis.plugin.Signature;
|
||||
|
||||
import com.nis.domain.Page;
|
||||
import com.nis.util.Reflections;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* Mybatis数据库分页插件,拦截StatementHandler的prepare方法
|
||||
* @author poplar.yfyang / thinkgem
|
||||
* @version 2013-8-28
|
||||
*/
|
||||
@Intercepts({
|
||||
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})
|
||||
})
|
||||
public class PreparePaginationInterceptor extends BaseInterceptor {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public PreparePaginationInterceptor() {
|
||||
super();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object intercept(Invocation ivk) throws Throwable {
|
||||
if (ivk.getTarget().getClass().isAssignableFrom(RoutingStatementHandler.class)) {
|
||||
final RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk.getTarget();
|
||||
final BaseStatementHandler delegate = (BaseStatementHandler) Reflections.getFieldValue(statementHandler, DELEGATE);
|
||||
final MappedStatement mappedStatement = (MappedStatement) Reflections.getFieldValue(delegate, MAPPED_STATEMENT);
|
||||
|
||||
// //拦截需要分页的SQL
|
||||
//// if (mappedStatement.getId().matches(_SQL_PATTERN)) {
|
||||
// if (StringUtils.indexOfIgnoreCase(mappedStatement.getId(), _SQL_PATTERN) != -1) {
|
||||
BoundSql boundSql = delegate.getBoundSql();
|
||||
//分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
|
||||
Object parameterObject = boundSql.getParameterObject();
|
||||
if (parameterObject == null) {
|
||||
log.error("参数未实例化");
|
||||
throw new NullPointerException("parameterObject尚未实例化!");
|
||||
} else {
|
||||
final Connection connection = (Connection) ivk.getArgs()[0];
|
||||
final String sql = boundSql.getSql();
|
||||
//记录统计
|
||||
final Long count = SQLHelper.getCount(sql, connection, mappedStatement, parameterObject, boundSql, log);
|
||||
Page<Object> page = null;
|
||||
page = convertParameter(parameterObject, page);
|
||||
page.setCount(count);
|
||||
String pagingSql = SQLHelper.generatePageSql(sql, page);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("PAGE SQL:" + pagingSql);
|
||||
}
|
||||
//将分页sql语句反射回BoundSql.
|
||||
Reflections.setFieldValue(boundSql, "sql", pagingSql);
|
||||
}
|
||||
|
||||
if (boundSql.getSql() == null || "".equals(boundSql.getSql())){
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
// }
|
||||
return ivk.proceed();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Object plugin(Object o) {
|
||||
return Plugin.wrap(o, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setProperties(Properties properties) {
|
||||
}
|
||||
}
|
||||
308
src/main/java/com/nis/persistence/interceptor/SQLHelper.java
Normal file
308
src/main/java/com/nis/persistence/interceptor/SQLHelper.java
Normal file
@@ -0,0 +1,308 @@
|
||||
package com.nis.persistence.interceptor;
|
||||
|
||||
import org.apache.ibatis.executor.ErrorContext;
|
||||
import org.apache.ibatis.executor.ExecutorException;
|
||||
import org.apache.ibatis.logging.Log;
|
||||
import org.apache.ibatis.mapping.BoundSql;
|
||||
import org.apache.ibatis.mapping.MappedStatement;
|
||||
import org.apache.ibatis.mapping.ParameterMapping;
|
||||
import org.apache.ibatis.mapping.ParameterMode;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.apache.ibatis.reflection.property.PropertyTokenizer;
|
||||
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
|
||||
import org.apache.ibatis.session.Configuration;
|
||||
import org.apache.ibatis.type.TypeHandler;
|
||||
import org.apache.ibatis.type.TypeHandlerRegistry;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.nis.datasource.CustomerContextHolder;
|
||||
import com.nis.domain.Page;
|
||||
import com.nis.persistence.dialect.ClusterDialect;
|
||||
import com.nis.persistence.dialect.DB2Dialect;
|
||||
import com.nis.persistence.dialect.DerbyDialect;
|
||||
import com.nis.persistence.dialect.Dialect;
|
||||
import com.nis.persistence.dialect.H2Dialect;
|
||||
import com.nis.persistence.dialect.HSQLDialect;
|
||||
import com.nis.persistence.dialect.MySQLDialect;
|
||||
import com.nis.persistence.dialect.OracleDialect;
|
||||
import com.nis.persistence.dialect.PostgreSQLDialect;
|
||||
import com.nis.persistence.dialect.SQLServer2005Dialect;
|
||||
import com.nis.persistence.dialect.SybaseDialect;
|
||||
import com.nis.util.Configurations;
|
||||
import com.nis.util.Reflections;
|
||||
import com.nis.util.StringUtils;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* SQL工具类
|
||||
*
|
||||
* @author poplar.yfyang / thinkgem
|
||||
* @version 2013-8-28
|
||||
*/
|
||||
public class SQLHelper {
|
||||
static final Logger logger = Logger.getLogger(SQLHelper.class);
|
||||
/**
|
||||
* 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
|
||||
*
|
||||
* @param ps
|
||||
* 表示预编译的 SQL 语句的对象。
|
||||
* @param mappedStatement
|
||||
* MappedStatement
|
||||
* @param boundSql
|
||||
* SQL
|
||||
* @param parameterObject
|
||||
* 参数对象
|
||||
* @throws java.sql.SQLException
|
||||
* 数据库异常
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql,
|
||||
Object parameterObject) throws SQLException {
|
||||
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
|
||||
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
|
||||
if (parameterMappings != null) {
|
||||
Configuration configuration = mappedStatement.getConfiguration();
|
||||
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
|
||||
MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
|
||||
for (int i = 0; i < parameterMappings.size(); i++) {
|
||||
ParameterMapping parameterMapping = parameterMappings.get(i);
|
||||
if (parameterMapping.getMode() != ParameterMode.OUT) {
|
||||
Object value;
|
||||
String propertyName = parameterMapping.getProperty();
|
||||
PropertyTokenizer prop = new PropertyTokenizer(propertyName);
|
||||
if (parameterObject == null) {
|
||||
value = null;
|
||||
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
|
||||
value = parameterObject;
|
||||
} else if (boundSql.hasAdditionalParameter(propertyName)) {
|
||||
value = boundSql.getAdditionalParameter(propertyName);
|
||||
} else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)
|
||||
&& boundSql.hasAdditionalParameter(prop.getName())) {
|
||||
value = boundSql.getAdditionalParameter(prop.getName());
|
||||
if (value != null) {
|
||||
value = configuration.newMetaObject(value)
|
||||
.getValue(propertyName.substring(prop.getName().length()));
|
||||
}
|
||||
} else {
|
||||
value = metaObject == null ? null : metaObject.getValue(propertyName);
|
||||
}
|
||||
@SuppressWarnings("rawtypes")
|
||||
TypeHandler typeHandler = parameterMapping.getTypeHandler();
|
||||
if (typeHandler == null) {
|
||||
throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName
|
||||
+ " of statement " + mappedStatement.getId());
|
||||
}
|
||||
typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title: getDBType
|
||||
* @Description: TODO(根据动态数据塬获取数据库的类型)
|
||||
* @param @return
|
||||
* 入参
|
||||
* @return String 返回类型
|
||||
* @author (darnell)
|
||||
* @throws @date
|
||||
* 2016年8月15日 下午6:35:58
|
||||
* @version V1.0
|
||||
*/
|
||||
public static String getDBType() {
|
||||
String dataSource = CustomerContextHolder.getCustomerType();
|
||||
if (StringUtils.isBlank(dataSource)) {
|
||||
return "mysql";
|
||||
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_A)) {
|
||||
return "mysql";
|
||||
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_B)) {
|
||||
return "oracle";
|
||||
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_C)) {
|
||||
return "oracle";
|
||||
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_D)) {
|
||||
return "oracle";
|
||||
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_F)) {
|
||||
return "oracle";
|
||||
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_G)) {
|
||||
return "oracle";
|
||||
} else if (dataSource.equals(CustomerContextHolder.DATA_SOURCE_H)) {//神通数据库
|
||||
return "cluster";
|
||||
}else {
|
||||
return "mysql";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询总纪录数
|
||||
*
|
||||
* @param sql
|
||||
* SQL语句
|
||||
* @param connection
|
||||
* 数据库连接
|
||||
* @param mappedStatement
|
||||
* mapped
|
||||
* @param parameterObject
|
||||
* 参数
|
||||
* @param boundSql
|
||||
* boundSql
|
||||
* @return 总记录数
|
||||
* @throws SQLException
|
||||
* sql查询错误
|
||||
*/
|
||||
public static Long getCount(final String sql, final Connection connection, final MappedStatement mappedStatement,
|
||||
final Object parameterObject, final BoundSql boundSql, Log log) throws SQLException {
|
||||
logger.info("oracle查询count开始----"+System.currentTimeMillis());
|
||||
String dbName = getDBType();
|
||||
final String countSql;
|
||||
if ("oracle".equals(dbName)) {
|
||||
countSql = "select count(*) from (" + removeOrders(sql) + ") tmp_count";
|
||||
} else {
|
||||
if(sql.toLowerCase().indexOf("limit") >-1){
|
||||
countSql = "select count(*) from (" +sql+ ") tmp_count";
|
||||
}else{
|
||||
countSql = "select count(*) from (" + removeOrders(sql) + ") tmp_count";
|
||||
}
|
||||
}
|
||||
System.out.println("countSql:"+countSql);
|
||||
Connection conn = connection;
|
||||
PreparedStatement ps = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("COUNT SQL: "
|
||||
+ StringUtils.replaceEach(countSql, new String[] { "\n", "\t" }, new String[] { " ", " " }));
|
||||
}
|
||||
if (conn == null) {
|
||||
conn = mappedStatement.getConfiguration().getEnvironment().getDataSource().getConnection();
|
||||
}
|
||||
ps = conn.prepareStatement(countSql);
|
||||
BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql,
|
||||
boundSql.getParameterMappings(), parameterObject);
|
||||
// 解决MyBatis 分页foreach 参数失效 start
|
||||
if (Reflections.getFieldValue(boundSql, "metaParameters") != null) {
|
||||
MetaObject mo = (MetaObject) Reflections.getFieldValue(boundSql, "metaParameters");
|
||||
Reflections.setFieldValue(countBS, "metaParameters", mo);
|
||||
}
|
||||
// 解决MyBatis 分页foreach 参数失效 end
|
||||
SQLHelper.setParameters(ps, mappedStatement, countBS, parameterObject);
|
||||
rs = ps.executeQuery();
|
||||
Long count = 0l;
|
||||
if (rs.next()) {
|
||||
count = rs.getLong(1);
|
||||
}
|
||||
return count;
|
||||
} finally {
|
||||
logger.info("oracle查询count结束----"+System.currentTimeMillis());
|
||||
if (rs != null) {
|
||||
rs.close();
|
||||
}
|
||||
if (ps != null) {
|
||||
ps.close();
|
||||
}
|
||||
if (conn != null) {
|
||||
conn.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据数据库方言,生成特定的分页sql
|
||||
*
|
||||
* @param sql
|
||||
* Mapper中的Sql语句
|
||||
* @param page
|
||||
* 分页对象
|
||||
* @param dialect
|
||||
* 方言类型
|
||||
* @return 分页SQL
|
||||
*/
|
||||
public static String generatePageSql(String sql, Page<Object> page) {
|
||||
|
||||
Dialect dialect = getDBDialect();
|
||||
if (dialect.supportsLimit()) {
|
||||
return dialect.getLimitString(sql, page.getFirstResult(), page.getMaxResults());
|
||||
} else {
|
||||
return sql;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置属性,支持自定义方言类和制定数据库的方式 <code>dialectClass</code>,自定义方言类。可以不配置这项
|
||||
* <ode>dbms</ode> 数据库类型,插件支持的数据库 <code>sqlPattern</code> 需要拦截的SQL ID
|
||||
*
|
||||
* @param p
|
||||
* 属性
|
||||
*/
|
||||
public static Dialect getDBDialect() {
|
||||
Dialect dialect = null;
|
||||
String dbType = getDBType();
|
||||
if ("db2".equals(dbType)) {
|
||||
dialect = new DB2Dialect();
|
||||
} else if ("derby".equals(dbType)) {
|
||||
dialect = new DerbyDialect();
|
||||
} else if ("h2".equals(dbType)) {
|
||||
dialect = new H2Dialect();
|
||||
} else if ("hsql".equals(dbType)) {
|
||||
dialect = new HSQLDialect();
|
||||
} else if ("mysql".equals(dbType)) {
|
||||
dialect = new MySQLDialect();
|
||||
} else if ("oracle".equals(dbType)) {
|
||||
dialect = new OracleDialect();
|
||||
} else if ("postgre".equals(dbType)) {
|
||||
dialect = new PostgreSQLDialect();
|
||||
} else if ("mssql".equals(dbType) || "sqlserver".equals(dbType)) {
|
||||
dialect = new SQLServer2005Dialect();
|
||||
} else if ("sybase".equals(dbType)) {
|
||||
dialect = new SybaseDialect();
|
||||
}else if ("cluster".equals(dbType)) {
|
||||
dialect = new ClusterDialect();
|
||||
}
|
||||
if (dialect == null) {
|
||||
throw new RuntimeException("mybatis dialect error.");
|
||||
}
|
||||
|
||||
return dialect;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 去除qlString的select子句。
|
||||
*
|
||||
* @param hql
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
private static String removeSelect(String qlString) {
|
||||
int beginPos = qlString.toLowerCase().indexOf("from");
|
||||
return qlString.substring(beginPos);
|
||||
}
|
||||
|
||||
/**
|
||||
* 去除hql的orderBy子句。
|
||||
*
|
||||
* @param hql
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
private static String removeOrders(String qlString) {
|
||||
Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
|
||||
Matcher m = p.matcher(qlString);
|
||||
StringBuffer sb = new StringBuffer();
|
||||
while (m.find()) {
|
||||
m.appendReplacement(sb, "");
|
||||
}
|
||||
m.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
45
src/main/java/com/nis/supcan/Background.java
Normal file
45
src/main/java/com/nis/supcan/Background.java
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import com.nis.util.ObjectUtils;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAlias;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
|
||||
|
||||
/**
|
||||
* 硕正TreeList Properties Background
|
||||
* @author WangZhen
|
||||
* @version 2013-11-04
|
||||
*/
|
||||
@XStreamAlias("Background")
|
||||
public class Background {
|
||||
|
||||
/**
|
||||
* 背景颜色
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String bgColor = "#FDFDFD";
|
||||
|
||||
public Background() {
|
||||
|
||||
}
|
||||
|
||||
public Background(SupBackground supBackground) {
|
||||
this();
|
||||
ObjectUtils.annotationToObject(supBackground, this);
|
||||
}
|
||||
|
||||
public Background(String bgColor) {
|
||||
this();
|
||||
this.bgColor = bgColor;
|
||||
}
|
||||
|
||||
public String getBgColor() {
|
||||
return bgColor;
|
||||
}
|
||||
|
||||
public void setBgColor(String bgColor) {
|
||||
this.bgColor = bgColor;
|
||||
}
|
||||
}
|
||||
542
src/main/java/com/nis/supcan/Col.java
Normal file
542
src/main/java/com/nis/supcan/Col.java
Normal file
@@ -0,0 +1,542 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import com.nis.util.ObjectUtils;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAlias;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
|
||||
import com.thoughtworks.xstream.annotations.XStreamConverter;
|
||||
import com.thoughtworks.xstream.annotations.XStreamOmitField;
|
||||
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;
|
||||
|
||||
/**
|
||||
* 硕正TreeList Cols Col
|
||||
* @author WangZhen
|
||||
* @version 2013-11-04
|
||||
*/
|
||||
@XStreamAlias("Col")
|
||||
@XStreamConverter(value = ToAttributedValueConverter.class, strings = {"text"})
|
||||
public class Col {
|
||||
|
||||
///////////////////////////////////// 主要 //////////////////////////////////////
|
||||
/**
|
||||
* 列名 串, 相当于字段名
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 内容是否允许重复 true/false
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String isUnique = "false";
|
||||
|
||||
/**
|
||||
* 是否允许为空 true/false
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String nullAble = "true";
|
||||
|
||||
/**
|
||||
* 默认值 串, 用于新插入行操作时的初始, 支持以 "=" 开头的表达式,例如 defaultValue="=now( )", 表示将日期型默认值设为当天 (无)
|
||||
* 注: 仅对新插入的行有效
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String defaultValue;
|
||||
|
||||
/**
|
||||
* 数据类型 有 string / int / double / bool / date / datetime 这几种
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String dataType;
|
||||
|
||||
/**
|
||||
* 小数位数 -1至8, 仅用于 double 型。 -1表示小数位数不确定, 可以在0位和8位之间可以任意输入, 默认: 2
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String decimal;
|
||||
|
||||
/**
|
||||
* 是否超链接列 true/false false
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String isHyperlink;
|
||||
|
||||
/**
|
||||
* 是否隐藏, true - 隐藏;
|
||||
* false - 显示;
|
||||
* absHide 或 absTrue - 绝对隐藏,不会被鼠标右键菜单选择;
|
||||
* absShow 或 absFalse - 绝对显示,不会被鼠标右键菜单选择;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String isHide;
|
||||
|
||||
/**
|
||||
* 点击列标题是否执行排序 true/false ,默认:true
|
||||
* 注: 如果<Properties>中的sortAble设为false, 则本sortAble无效(false)
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String sortAble;
|
||||
|
||||
/**
|
||||
* 是否允许列的拖动操作 ,默认:true
|
||||
* 注: 如果<Properties>中的moveAble设为false, 则本moveAble无效(false)
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String moveAble;
|
||||
|
||||
/**
|
||||
* 是否允许被粘贴 ,默认:supcan.xml
|
||||
* true - 允许;
|
||||
* false - 不允许;
|
||||
* supcan.xml - 通常是允许,但是当列不可编辑时(包括隐藏时),将以supcan.xml中的 <pasteAbleWhenUnEditAble> 的设定为准;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String pasteAble;
|
||||
|
||||
/**
|
||||
* 指向另一列的列名,显示的内容存放在该列中,是另类 key-value对 的简易字典解决方案
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String textId;
|
||||
|
||||
///////////////////////////////////// 外观 //////////////////////////////////////
|
||||
|
||||
/**
|
||||
* 是否以千位符分隔显示 true/false 默认:true
|
||||
* 注: 仅用于 datatype 为 int 或 double 时
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String isThousandSeparat;
|
||||
|
||||
/**
|
||||
* 列宽 整数 - 绝对宽度 (单位:像素数);
|
||||
* 百分比 - 窗口宽度的百分比, 如:20%;
|
||||
* 为小于1的分数 - 比例因子,用于分配剩余的宽度, 如0.2;
|
||||
* fitHeader 或 header - 自动伸展到能使表头标题能够完整显示;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String width;
|
||||
|
||||
/**
|
||||
* 列的最小宽度 像素数 10
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String minWidth;
|
||||
|
||||
/**
|
||||
* 水平对齐 left / center / right
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String align;
|
||||
|
||||
/**
|
||||
* 垂直对齐 top / vcenter(或middle) / bottom vcenter
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String vAlign;
|
||||
|
||||
/**
|
||||
* 列标题文字的对齐 left / center / right center
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String alignHeader;
|
||||
|
||||
/**
|
||||
* 采用的字体 数字,指向在<Fonts>中定义的字体的顺序号, 从0开始计数, 等级高于<Properties>中的同名属性 -1
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String fontIndex;
|
||||
|
||||
/**
|
||||
* 列标题采用的字体 数字,指向在<Fonts>中定义的字体的顺序号, 从0开始计数, 等级高于<Properties>中的同名属性 -1
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String headerFontIndex;
|
||||
|
||||
/**
|
||||
* 列标题文字颜色 颜色串 #000000
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String headerTextColor;
|
||||
|
||||
/**
|
||||
* 列标题旁边的小图标 可以是图标的URL, 也可以是如下格式的串:
|
||||
* url=[?];pos=[?]
|
||||
* pos用于指定图标的位置, 是水平(left/right)、 垂直(top/middle/bottom)方向的组合. 举例如下:
|
||||
* url=../ac.png;pos=right,bottom
|
||||
* 建议采用png或ico这类透明的图片
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String headerIcon;
|
||||
|
||||
/**
|
||||
* 鼠标点击上述小图标时弹出的提示文字 文字串, 如果不定义这个串,鼠标点击小图标时将触发Clicked事件
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String headerIconTip;
|
||||
|
||||
/**
|
||||
* 用于显示的格式掩码表达式 表达式的内容包括显示内容、 背景色、 文字色、 左图、 右图. 请详见Treelist帮助文档的"3.几个重要的属性"
|
||||
* formatDate(data,'YYYY-MM-DD')
|
||||
* =if(data=='1','关闭',if(data=='2','已完成',if(data=='3','未接收','进行中')))
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String displayMask;
|
||||
|
||||
/**
|
||||
* 位于多层表头的层位置 数字,从0开始
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String atLayer;
|
||||
|
||||
/**
|
||||
* 位于多层表头的层位置 数字,从0开始
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String extentRows;
|
||||
|
||||
/**
|
||||
* 下拉列(droplis, droptreelist)单元格的文字显示方式 0 - 仅显示文字部分;
|
||||
* 1 - 仅显示键值(即key)部分;
|
||||
* 2 - 键值+" - "+文字;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String dropDisplayType;
|
||||
|
||||
/**
|
||||
* 虚拟列的数据分隔符 串,比如"/", 如果设了这个串,在加载数据后,程序将按这个分隔符自动对各行数据进行处理,使其看上去呈现多列的效果。此外, 各个段中纵向、横向如果有连续相同的数据,将自动呈现纵、横的合并效果 (无)
|
||||
* 注1: 仅改变显示效果,并不改变数据;
|
||||
* 注2: VColSep列有诸多限制,例如只能用于string型、不能作为树的排序列等等;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String VColSep;
|
||||
|
||||
/**
|
||||
* VColSepStyle 虚拟列的合并方式 row - 只允许跨行的垂直合并;
|
||||
* col - 只允许跨列的横向合并;
|
||||
* row,col - 跨行、跨列自动合并;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String VColSepStyle;
|
||||
|
||||
/**
|
||||
* 合计表达式
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String totalExpress;
|
||||
|
||||
/**
|
||||
* 小计表达式
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String subTotalExpress;
|
||||
|
||||
/**
|
||||
* 列的显示名称
|
||||
*/
|
||||
private String text;
|
||||
|
||||
/**
|
||||
* 归属组ID
|
||||
*/
|
||||
@XStreamOmitField
|
||||
private String groupId;
|
||||
|
||||
/**
|
||||
* 字段排序,注解定义时有效
|
||||
*/
|
||||
@XStreamOmitField
|
||||
private int sort;
|
||||
|
||||
public Col() {
|
||||
|
||||
}
|
||||
|
||||
public Col(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Col(String name, String text) {
|
||||
this(name);
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public Col(SupCol supCol){
|
||||
ObjectUtils.annotationToObject(supCol, this);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getIsUnique() {
|
||||
return isUnique;
|
||||
}
|
||||
|
||||
public void setIsUnique(String isUnique) {
|
||||
this.isUnique = isUnique;
|
||||
}
|
||||
|
||||
public String getNullAble() {
|
||||
return nullAble;
|
||||
}
|
||||
|
||||
public void setNullAble(String nullAble) {
|
||||
this.nullAble = nullAble;
|
||||
}
|
||||
|
||||
public String getDefaultValue() {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
public void setDefaultValue(String defaultValue) {
|
||||
this.defaultValue = defaultValue;
|
||||
}
|
||||
|
||||
public String getDataType() {
|
||||
return dataType;
|
||||
}
|
||||
|
||||
public void setDataType(String dataType) {
|
||||
this.dataType = dataType;
|
||||
}
|
||||
|
||||
public String getDecimal() {
|
||||
return decimal;
|
||||
}
|
||||
|
||||
public void setDecimal(String decimal) {
|
||||
this.decimal = decimal;
|
||||
}
|
||||
|
||||
public String getIsHyperlink() {
|
||||
return isHyperlink;
|
||||
}
|
||||
|
||||
public void setIsHyperlink(String isHyperlink) {
|
||||
this.isHyperlink = isHyperlink;
|
||||
}
|
||||
|
||||
public String getIsHide() {
|
||||
return isHide;
|
||||
}
|
||||
|
||||
public void setIsHide(String isHide) {
|
||||
this.isHide = isHide;
|
||||
}
|
||||
|
||||
public String getSortAble() {
|
||||
return sortAble;
|
||||
}
|
||||
|
||||
public void setSortAble(String sortAble) {
|
||||
this.sortAble = sortAble;
|
||||
}
|
||||
|
||||
public String getMoveAble() {
|
||||
return moveAble;
|
||||
}
|
||||
|
||||
public void setMoveAble(String moveAble) {
|
||||
this.moveAble = moveAble;
|
||||
}
|
||||
|
||||
public String getPasteAble() {
|
||||
return pasteAble;
|
||||
}
|
||||
|
||||
public void setPasteAble(String pasteAble) {
|
||||
this.pasteAble = pasteAble;
|
||||
}
|
||||
|
||||
public String getTextId() {
|
||||
return textId;
|
||||
}
|
||||
|
||||
public void setTextId(String textId) {
|
||||
this.textId = textId;
|
||||
}
|
||||
|
||||
public String getIsThousandSeparat() {
|
||||
return isThousandSeparat;
|
||||
}
|
||||
|
||||
public void setIsThousandSeparat(String isThousandSeparat) {
|
||||
this.isThousandSeparat = isThousandSeparat;
|
||||
}
|
||||
|
||||
public String getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public void setWidth(String width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public String getMinWidth() {
|
||||
return minWidth;
|
||||
}
|
||||
|
||||
public void setMinWidth(String minWidth) {
|
||||
this.minWidth = minWidth;
|
||||
}
|
||||
|
||||
public String getAlign() {
|
||||
return align;
|
||||
}
|
||||
|
||||
public void setAlign(String align) {
|
||||
this.align = align;
|
||||
}
|
||||
|
||||
public String getvAlign() {
|
||||
return vAlign;
|
||||
}
|
||||
|
||||
public void setvAlign(String vAlign) {
|
||||
this.vAlign = vAlign;
|
||||
}
|
||||
|
||||
public String getAlignHeader() {
|
||||
return alignHeader;
|
||||
}
|
||||
|
||||
public void setAlignHeader(String alignHeader) {
|
||||
this.alignHeader = alignHeader;
|
||||
}
|
||||
|
||||
public String getFontIndex() {
|
||||
return fontIndex;
|
||||
}
|
||||
|
||||
public void setFontIndex(String fontIndex) {
|
||||
this.fontIndex = fontIndex;
|
||||
}
|
||||
|
||||
public String getHeaderFontIndex() {
|
||||
return headerFontIndex;
|
||||
}
|
||||
|
||||
public void setHeaderFontIndex(String headerFontIndex) {
|
||||
this.headerFontIndex = headerFontIndex;
|
||||
}
|
||||
|
||||
public String getHeaderTextColor() {
|
||||
return headerTextColor;
|
||||
}
|
||||
|
||||
public void setHeaderTextColor(String headerTextColor) {
|
||||
this.headerTextColor = headerTextColor;
|
||||
}
|
||||
|
||||
public String getHeaderIcon() {
|
||||
return headerIcon;
|
||||
}
|
||||
|
||||
public void setHeaderIcon(String headerIcon) {
|
||||
this.headerIcon = headerIcon;
|
||||
}
|
||||
|
||||
public String getHeaderIconTip() {
|
||||
return headerIconTip;
|
||||
}
|
||||
|
||||
public void setHeaderIconTip(String headerIconTip) {
|
||||
this.headerIconTip = headerIconTip;
|
||||
}
|
||||
|
||||
public String getDisplayMask() {
|
||||
return displayMask;
|
||||
}
|
||||
|
||||
public void setDisplayMask(String displayMask) {
|
||||
this.displayMask = displayMask;
|
||||
}
|
||||
|
||||
public String getAtLayer() {
|
||||
return atLayer;
|
||||
}
|
||||
|
||||
public void setAtLayer(String atLayer) {
|
||||
this.atLayer = atLayer;
|
||||
}
|
||||
|
||||
public String getExtentRows() {
|
||||
return extentRows;
|
||||
}
|
||||
|
||||
public void setExtentRows(String extentRows) {
|
||||
this.extentRows = extentRows;
|
||||
}
|
||||
|
||||
public String getDropDisplayType() {
|
||||
return dropDisplayType;
|
||||
}
|
||||
|
||||
public void setDropDisplayType(String dropDisplayType) {
|
||||
this.dropDisplayType = dropDisplayType;
|
||||
}
|
||||
|
||||
public String getVColSep() {
|
||||
return VColSep;
|
||||
}
|
||||
|
||||
public void setVColSep(String vColSep) {
|
||||
VColSep = vColSep;
|
||||
}
|
||||
|
||||
public String getVColSepStyle() {
|
||||
return VColSepStyle;
|
||||
}
|
||||
|
||||
public void setVColSepStyle(String vColSepStyle) {
|
||||
VColSepStyle = vColSepStyle;
|
||||
}
|
||||
|
||||
public String getTotalExpress() {
|
||||
return totalExpress;
|
||||
}
|
||||
|
||||
public void setTotalExpress(String totalExpress) {
|
||||
this.totalExpress = totalExpress;
|
||||
}
|
||||
|
||||
public String getSubTotalExpress() {
|
||||
return subTotalExpress;
|
||||
}
|
||||
|
||||
public void setSubTotalExpress(String subTotalExpress) {
|
||||
this.subTotalExpress = subTotalExpress;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public int getSort() {
|
||||
return sort;
|
||||
}
|
||||
|
||||
public void setSort(int sort) {
|
||||
this.sort = sort;
|
||||
}
|
||||
|
||||
public String getGroupId() {
|
||||
return groupId;
|
||||
}
|
||||
|
||||
public void setGroupId(String groupId) {
|
||||
this.groupId = groupId;
|
||||
}
|
||||
|
||||
}
|
||||
59
src/main/java/com/nis/supcan/Common.java
Normal file
59
src/main/java/com/nis/supcan/Common.java
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.web.security.IdGen;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAlias;
|
||||
|
||||
/**
|
||||
* 硕正Common
|
||||
* @author WangZhen
|
||||
* @version 2013-11-04
|
||||
*/
|
||||
public class Common {
|
||||
|
||||
/**
|
||||
* 属性对象
|
||||
*/
|
||||
@XStreamAlias("Properties")
|
||||
protected Properties properties;
|
||||
|
||||
/**
|
||||
* 字体对象
|
||||
*/
|
||||
@XStreamAlias("Fonts")
|
||||
protected List<Font> fonts;
|
||||
|
||||
public Common() {
|
||||
properties = new Properties(IdGen.uuid());
|
||||
fonts = Lists.newArrayList(
|
||||
new Font("宋体", "134", "-12"),
|
||||
new Font("宋体", "134", "-13", "700"));
|
||||
}
|
||||
|
||||
public Common(Properties properties) {
|
||||
this();
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public Properties getProperties() {
|
||||
return properties;
|
||||
}
|
||||
|
||||
public void setProperties(Properties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public List<Font> getFonts() {
|
||||
return fonts;
|
||||
}
|
||||
|
||||
public void setFonts(List<Font> fonts) {
|
||||
this.fonts = fonts;
|
||||
}
|
||||
|
||||
}
|
||||
66
src/main/java/com/nis/supcan/Express.java
Normal file
66
src/main/java/com/nis/supcan/Express.java
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import com.nis.util.ObjectUtils;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAlias;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
|
||||
import com.thoughtworks.xstream.annotations.XStreamConverter;
|
||||
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;
|
||||
|
||||
/**
|
||||
* 硕正TreeList Properties Express
|
||||
* @author WangZhen
|
||||
* @version 2013-11-04
|
||||
*/
|
||||
@XStreamAlias("Express")
|
||||
@XStreamConverter(value = ToAttributedValueConverter.class, strings = {"text"})
|
||||
public class Express {
|
||||
|
||||
/**
|
||||
* 是否自动按列的引用关系优化计算顺序 默认值true
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String isOpt;
|
||||
|
||||
/**
|
||||
* 文本
|
||||
*/
|
||||
private String text;
|
||||
|
||||
public Express() {
|
||||
|
||||
}
|
||||
|
||||
public Express(SupExpress supExpress) {
|
||||
this();
|
||||
ObjectUtils.annotationToObject(supExpress, this);
|
||||
}
|
||||
|
||||
public Express(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public Express(String name, String text) {
|
||||
this(name);
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public String getIsOpt() {
|
||||
return isOpt;
|
||||
}
|
||||
|
||||
public void setIsOpt(String isOpt) {
|
||||
this.isOpt = isOpt;
|
||||
}
|
||||
|
||||
}
|
||||
143
src/main/java/com/nis/supcan/Font.java
Normal file
143
src/main/java/com/nis/supcan/Font.java
Normal file
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import com.nis.util.ObjectUtils;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAlias;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
|
||||
|
||||
/**
|
||||
* 硕正TreeList Properties
|
||||
* @author WangZhen
|
||||
* @version 2013-11-04
|
||||
*/
|
||||
@XStreamAlias("Font")
|
||||
public class Font {
|
||||
|
||||
/**
|
||||
* 字体名称 微软雅黑 宋体
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String faceName;
|
||||
|
||||
/**
|
||||
* 字符集 134
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String charSet;
|
||||
|
||||
/**
|
||||
* Height(或size)是字体的尺寸,单位是字体的逻辑单位,通常采用小于0的数字,
|
||||
* 如果大于0,则高度不包含文字的内部行距(internal-leading)。
|
||||
* 常用的尺寸是-8, -9, -10, -11, -12, -14, -16, -18, -20, -22, -24, -26, -28, -36, -48, -72;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String height;
|
||||
|
||||
/**
|
||||
* 字体加粗 weight=400/700 对应 非粗体/粗体;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String weight;
|
||||
|
||||
/**
|
||||
* 字体宽度
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String width;
|
||||
|
||||
/**
|
||||
* 字体斜体
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String italic;
|
||||
|
||||
/**
|
||||
* 字体下划线
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String underline;
|
||||
|
||||
public Font() {
|
||||
|
||||
}
|
||||
|
||||
public Font(SupFont supFont) {
|
||||
this();
|
||||
ObjectUtils.annotationToObject(supFont, this);
|
||||
}
|
||||
|
||||
public Font(String faceName) {
|
||||
this();
|
||||
this.faceName = faceName;
|
||||
}
|
||||
|
||||
public Font(String faceName, String charSet, String height) {
|
||||
this(faceName);
|
||||
this.charSet = charSet;
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public Font(String faceName, String charSet, String height, String weight) {
|
||||
this(faceName, charSet, height);
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public String getFaceName() {
|
||||
return faceName;
|
||||
}
|
||||
|
||||
public void setFaceName(String faceName) {
|
||||
this.faceName = faceName;
|
||||
}
|
||||
|
||||
public String getCharSet() {
|
||||
return charSet;
|
||||
}
|
||||
|
||||
public void setCharSet(String charSet) {
|
||||
this.charSet = charSet;
|
||||
}
|
||||
|
||||
public String getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public void setHeight(String height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public String getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public void setWeight(String weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public String getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public void setWidth(String width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public String getItalic() {
|
||||
return italic;
|
||||
}
|
||||
|
||||
public void setItalic(String italic) {
|
||||
this.italic = italic;
|
||||
}
|
||||
|
||||
public String getUnderline() {
|
||||
return underline;
|
||||
}
|
||||
|
||||
public void setUnderline(String underline) {
|
||||
this.underline = underline;
|
||||
}
|
||||
|
||||
}
|
||||
25
src/main/java/com/nis/supcan/FreeForm.java
Normal file
25
src/main/java/com/nis/supcan/FreeForm.java
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import com.thoughtworks.xstream.annotations.XStreamAlias;
|
||||
|
||||
/**
|
||||
* 硕正FreeForm
|
||||
* @author WangZhen
|
||||
* @version 2013-11-04
|
||||
*/
|
||||
@XStreamAlias("FreeForm")
|
||||
public class FreeForm extends Common {
|
||||
|
||||
public FreeForm() {
|
||||
super();
|
||||
}
|
||||
|
||||
public FreeForm(Properties properties) {
|
||||
this();
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
}
|
||||
157
src/main/java/com/nis/supcan/Group.java
Normal file
157
src/main/java/com/nis/supcan/Group.java
Normal file
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.util.ObjectUtils;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAlias;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
|
||||
import com.thoughtworks.xstream.annotations.XStreamImplicit;
|
||||
import com.thoughtworks.xstream.annotations.XStreamOmitField;
|
||||
|
||||
/**
|
||||
* 硕正TreeList Cols Group
|
||||
* @author WangZhen
|
||||
* @version 2013-11-04
|
||||
*/
|
||||
@XStreamAlias("Group")
|
||||
public class Group {
|
||||
|
||||
/**
|
||||
* 分组的id,仅用于加载采用该id代替列名的XML/JSON数据
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 显示的文字 串
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 采用的字体, 前面定义的<Font>的序号 数字 指向在<Fonts>中定义的字体的顺序号, 从0开始计数, 等级高于<Properties>中的同名属性
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String headerFontIndex;
|
||||
|
||||
/**
|
||||
* 文字颜色 颜色串 #000000
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String textColor;
|
||||
|
||||
/**
|
||||
* 文字对齐 left/center/right center
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String align;
|
||||
|
||||
/**
|
||||
* 分组下的列集合
|
||||
*/
|
||||
@XStreamAlias("Cols")
|
||||
@XStreamImplicit
|
||||
private List<Object> cols;
|
||||
|
||||
/**
|
||||
* 父级组ID,注解定义时有效
|
||||
*/
|
||||
@XStreamOmitField
|
||||
private String parentId;
|
||||
|
||||
/**
|
||||
* 字段排序,注解定义时有效
|
||||
*/
|
||||
@XStreamOmitField
|
||||
private int sort;
|
||||
|
||||
public Group() {
|
||||
|
||||
}
|
||||
|
||||
public Group(String name) {
|
||||
this();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Group(String name, List<Object> cols) {
|
||||
this(name);
|
||||
this.cols = cols;
|
||||
}
|
||||
|
||||
public Group(SupGroup supGroup){
|
||||
ObjectUtils.annotationToObject(supGroup, this);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Object> getCols() {
|
||||
if (cols == null){
|
||||
cols = Lists.newArrayList();
|
||||
}
|
||||
return cols;
|
||||
}
|
||||
|
||||
public void setCols(List<Object> cols) {
|
||||
this.cols = cols;
|
||||
}
|
||||
|
||||
public String getHeaderFontIndex() {
|
||||
return headerFontIndex;
|
||||
}
|
||||
|
||||
public void setHeaderFontIndex(String headerFontIndex) {
|
||||
this.headerFontIndex = headerFontIndex;
|
||||
}
|
||||
|
||||
public String getTextColor() {
|
||||
return textColor;
|
||||
}
|
||||
|
||||
public void setTextColor(String textColor) {
|
||||
this.textColor = textColor;
|
||||
}
|
||||
|
||||
public String getAlign() {
|
||||
return align;
|
||||
}
|
||||
|
||||
public void setAlign(String align) {
|
||||
this.align = align;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getParentId() {
|
||||
return parentId;
|
||||
}
|
||||
|
||||
public void setParentId(String parentId) {
|
||||
this.parentId = parentId;
|
||||
}
|
||||
|
||||
public int getSort() {
|
||||
return sort;
|
||||
}
|
||||
|
||||
public void setSort(int sort) {
|
||||
this.sort = sort;
|
||||
}
|
||||
|
||||
}
|
||||
385
src/main/java/com/nis/supcan/Properties.java
Normal file
385
src/main/java/com/nis/supcan/Properties.java
Normal file
@@ -0,0 +1,385 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.util.ObjectUtils;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAlias;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
|
||||
|
||||
/**
|
||||
* 硕正TreeList Properties
|
||||
* @author WangZhen
|
||||
* @version 2013-11-04
|
||||
*/
|
||||
@XStreamAlias("Properties")
|
||||
public class Properties {
|
||||
|
||||
/**
|
||||
* Treelist的ID 串
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 主键 串, 下面<col>的列名,复合主键须以逗号分隔
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String key;
|
||||
|
||||
/**
|
||||
* 是否以树展现 true/false
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String isTree = "false";
|
||||
|
||||
/**
|
||||
* 是否显示左标尺 true/false
|
||||
* editAble=true时,isShowRuler的默认值是true,否则是false;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String isShowRuler = "false";
|
||||
|
||||
/**
|
||||
* 合计行是否固定在底部、始终显示 true/false
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String isFixTotalRow = "false";
|
||||
|
||||
/**
|
||||
* 合计行的背景色 颜色串
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String totalBgColor = "#FFFFCC";
|
||||
|
||||
/**
|
||||
* 小计行的背景色 颜色串
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String subTotalBgColor = "#FFFFCC";
|
||||
|
||||
/**
|
||||
* 是否允许增删改操作 true/false
|
||||
* editAble=true时,isShowRuler的默认值是true,否则是false;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String editAble = "false";
|
||||
|
||||
/**
|
||||
* 是否允许用户增行操作 true/false
|
||||
* 注1: 仅在editAble=true时生效; 注2: 不影响增删改的API;
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String addRowAble = "true";
|
||||
|
||||
/**
|
||||
* 分屏方式
|
||||
* true - 始终显示分隔条;
|
||||
* false - 始终不显示分隔条;
|
||||
* auto - 自动(超宽时会在左侧浮现分隔条);
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String separateBarStyle = "false";
|
||||
|
||||
/**
|
||||
* 点击列标题是否执行排序 true/false
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String sortAble = "true";
|
||||
|
||||
/**
|
||||
* 是否允许多层表头 true/false
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String multiLayerAble = "false";
|
||||
|
||||
/**
|
||||
* 执行 Load() 函数时的淡入淡出效果 0 - 255, 数值越小效果越明显, 而 0 表示关闭此效果
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String fadeInStep = "0";
|
||||
|
||||
/**
|
||||
* 顶部标题条的背景色 颜色串,可以是以逗号分隔的多个颜色(渐变)
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String headerBgColor = "#FDFDFD,#F0F1EF";
|
||||
|
||||
/**
|
||||
* 顶部标题条的高度 像素数
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String headerHeight = "28";
|
||||
|
||||
/**
|
||||
* 左标尺的背景色,颜色串,可以是以逗号分隔的多个颜色(渐变)
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String leftColor = "#F0F1EF,#FDFDFD";
|
||||
|
||||
/**
|
||||
* 行高像素数
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String rowHeight = "28";
|
||||
|
||||
/**
|
||||
* 当前行的颜色,允许多个颜色渐变
|
||||
* 颜色串, 支持ARGB格式,例如: "#10C0D0E0", 其中 "10" 是 alpha(透明度), "C0D0E0" 是 RGB, 此外, 还支持包含如下边框属性:
|
||||
* borderWidth - 边框线宽
|
||||
* borderColor - 边框线色
|
||||
* borderRound - 边框线的圆角直径
|
||||
* 示例: "#12FFFFFF,#22EEFFEE; borderWidth=1; borderColor=red; borderRound=8"
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String curSelBgColor = "#F5F5F5,#EDEDED"; // #F5F5F5 #FFE88D
|
||||
|
||||
/**
|
||||
* 整行的背景色、文字色表达式 表达式, 如:
|
||||
* displayMask = "bgColor=if(price=0, red, transparent); textColor=if(price>2,#000022, blue)"
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String displayMask;
|
||||
|
||||
/**
|
||||
* 指定标题栏默认字体 <Fonts>中的字体顺序号
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String headerFontIndex;
|
||||
|
||||
/**
|
||||
* 设置背景
|
||||
*/
|
||||
@XStreamAlias("Background")
|
||||
private Background packground = new Background();
|
||||
|
||||
/**
|
||||
* 计算列表达式
|
||||
*/
|
||||
@XStreamAlias("Expresses")
|
||||
private List<Express> expresses;
|
||||
|
||||
/**
|
||||
* 打印简易配置 标题
|
||||
*/
|
||||
@XStreamAsAttribute
|
||||
private String title;
|
||||
|
||||
public Properties() {
|
||||
|
||||
}
|
||||
|
||||
public Properties(SupProperties supProperties) {
|
||||
this();
|
||||
ObjectUtils.annotationToObject(supProperties, this);
|
||||
if (supProperties.packground() != null){
|
||||
this.packground = new Background(supProperties.packground());
|
||||
}
|
||||
if (supProperties.expresses() != null){
|
||||
for (SupExpress supExpress : supProperties.expresses()){
|
||||
if (this.expresses == null){
|
||||
this.expresses = Lists.newArrayList();
|
||||
}
|
||||
this.expresses.add(new Express(supExpress));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Properties(String id) {
|
||||
this();
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Properties(String id, String key) {
|
||||
this(id);
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public void setKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public String getIsTree() {
|
||||
return isTree;
|
||||
}
|
||||
|
||||
public void setIsTree(String isTree) {
|
||||
this.isTree = isTree;
|
||||
}
|
||||
|
||||
public String getIsShowRuler() {
|
||||
return isShowRuler;
|
||||
}
|
||||
|
||||
public void setIsShowRuler(String isShowRuler) {
|
||||
this.isShowRuler = isShowRuler;
|
||||
}
|
||||
|
||||
public String getIsFixTotalRow() {
|
||||
return isFixTotalRow;
|
||||
}
|
||||
|
||||
public void setIsFixTotalRow(String isFixTotalRow) {
|
||||
this.isFixTotalRow = isFixTotalRow;
|
||||
}
|
||||
|
||||
public String getTotalBgColor() {
|
||||
return totalBgColor;
|
||||
}
|
||||
|
||||
public void setTotalBgColor(String totalBgColor) {
|
||||
this.totalBgColor = totalBgColor;
|
||||
}
|
||||
|
||||
public String getSubTotalBgColor() {
|
||||
return subTotalBgColor;
|
||||
}
|
||||
|
||||
public void setSubTotalBgColor(String subTotalBgColor) {
|
||||
this.subTotalBgColor = subTotalBgColor;
|
||||
}
|
||||
|
||||
public String getEditAble() {
|
||||
return editAble;
|
||||
}
|
||||
|
||||
public void setEditAble(String editAble) {
|
||||
this.editAble = editAble;
|
||||
}
|
||||
|
||||
public String getSeparateBarStyle() {
|
||||
return separateBarStyle;
|
||||
}
|
||||
|
||||
public void setSeparateBarStyle(String separateBarStyle) {
|
||||
this.separateBarStyle = separateBarStyle;
|
||||
}
|
||||
|
||||
public String getSortAble() {
|
||||
return sortAble;
|
||||
}
|
||||
|
||||
public void setSortAble(String sortAble) {
|
||||
this.sortAble = sortAble;
|
||||
}
|
||||
|
||||
public String getMultiLayerAble() {
|
||||
return multiLayerAble;
|
||||
}
|
||||
|
||||
public void setMultiLayerAble(String multiLayerAble) {
|
||||
this.multiLayerAble = multiLayerAble;
|
||||
}
|
||||
|
||||
public String getFadeInStep() {
|
||||
return fadeInStep;
|
||||
}
|
||||
|
||||
public void setFadeInStep(String fadeInStep) {
|
||||
this.fadeInStep = fadeInStep;
|
||||
}
|
||||
|
||||
public String getHeaderBgColor() {
|
||||
return headerBgColor;
|
||||
}
|
||||
|
||||
public void setHeaderBgColor(String headerBgColor) {
|
||||
this.headerBgColor = headerBgColor;
|
||||
}
|
||||
|
||||
public String getHeaderHeight() {
|
||||
return headerHeight;
|
||||
}
|
||||
|
||||
public void setHeaderHeight(String headerHeight) {
|
||||
this.headerHeight = headerHeight;
|
||||
}
|
||||
|
||||
public String getLeftColor() {
|
||||
return leftColor;
|
||||
}
|
||||
|
||||
public void setLeftColor(String leftColor) {
|
||||
this.leftColor = leftColor;
|
||||
}
|
||||
|
||||
public String getRowHeight() {
|
||||
return rowHeight;
|
||||
}
|
||||
|
||||
public void setRowHeight(String rowHeight) {
|
||||
this.rowHeight = rowHeight;
|
||||
}
|
||||
|
||||
public String getCurSelBgColor() {
|
||||
return curSelBgColor;
|
||||
}
|
||||
|
||||
public void setCurSelBgColor(String curSelBgColor) {
|
||||
this.curSelBgColor = curSelBgColor;
|
||||
}
|
||||
|
||||
public String getHeaderFontIndex() {
|
||||
return headerFontIndex;
|
||||
}
|
||||
|
||||
public void setHeaderFontIndex(String headerFontIndex) {
|
||||
this.headerFontIndex = headerFontIndex;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Background getPackground() {
|
||||
return packground;
|
||||
}
|
||||
|
||||
public void setPackground(Background packground) {
|
||||
this.packground = packground;
|
||||
}
|
||||
|
||||
public List<Express> getExpresses() {
|
||||
return expresses;
|
||||
}
|
||||
|
||||
public void setExpresses(List<Express> expresses) {
|
||||
this.expresses = expresses;
|
||||
}
|
||||
|
||||
public String getDisplayMask() {
|
||||
return displayMask;
|
||||
}
|
||||
|
||||
public void setDisplayMask(String displayMask) {
|
||||
this.displayMask = displayMask;
|
||||
}
|
||||
|
||||
public String getAddRowAble() {
|
||||
return addRowAble;
|
||||
}
|
||||
|
||||
public void setAddRowAble(String addRowAble) {
|
||||
this.addRowAble = addRowAble;
|
||||
}
|
||||
|
||||
}
|
||||
28
src/main/java/com/nis/supcan/SupBackground.java
Normal file
28
src/main/java/com/nis/supcan/SupBackground.java
Normal file
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 硕正Background注解
|
||||
* @author WangZhen
|
||||
* @version 2013-11-12
|
||||
*/
|
||||
@Target({ ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
public @interface SupBackground {
|
||||
|
||||
/**
|
||||
* 背景颜色
|
||||
* @return
|
||||
*/
|
||||
String bgColor() default "";
|
||||
|
||||
}
|
||||
223
src/main/java/com/nis/supcan/SupCol.java
Normal file
223
src/main/java/com/nis/supcan/SupCol.java
Normal file
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 硕正Col注解
|
||||
* @author WangZhen
|
||||
* @version 2013-11-12
|
||||
* @see 在get方法上添加注解,应用实例:
|
||||
*
|
||||
* @SupCol(text="归属公司", sort = 10)
|
||||
*/
|
||||
@Target({ ElementType.METHOD })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
public @interface SupCol {
|
||||
|
||||
///////////////////////////////////// 主要 //////////////////////////////////////
|
||||
|
||||
/**
|
||||
* 列名(默认当前字段名)
|
||||
*/
|
||||
String name() default "";
|
||||
|
||||
/**
|
||||
* 内容是否允许重复 true/false
|
||||
*/
|
||||
String isUnique() default "";
|
||||
|
||||
/**
|
||||
* 是否允许为空 true/false
|
||||
*/
|
||||
String nullAble() default "";
|
||||
|
||||
/**
|
||||
* 默认值 串, 用于新插入行操作时的初始, 支持以 "=" 开头的表达式,例如 defaultValue="=now( )", 表示将日期型默认值设为当天 (无)
|
||||
* 注: 仅对新插入的行有效
|
||||
*/
|
||||
String defaultValue() default "";
|
||||
|
||||
/**
|
||||
* 数据类型 有 string / int / double / bool / date / datetime 这几种
|
||||
*/
|
||||
String dataType() default "";
|
||||
|
||||
/**
|
||||
* 小数位数 -1至8, 仅用于 double 型。 -1表示小数位数不确定, 可以在0位和8位之间可以任意输入, 默认: 2
|
||||
*/
|
||||
String decimal() default "";
|
||||
|
||||
/**
|
||||
* 是否超链接列 true/false false
|
||||
*/
|
||||
String isHyperlink() default "";
|
||||
|
||||
/**
|
||||
* 是否隐藏, true - 隐藏() default "";
|
||||
* false - 显示() default "";
|
||||
* absHide 或 absTrue - 绝对隐藏,不会被鼠标右键菜单选择() default "";
|
||||
* absShow 或 absFalse - 绝对显示,不会被鼠标右键菜单选择() default "";
|
||||
*/
|
||||
String isHide() default "";
|
||||
|
||||
/**
|
||||
* 点击列标题是否执行排序 true/false ,默认:true
|
||||
* 注: 如果<Properties>中的sortAble设为false, 则本sortAble无效(false)
|
||||
*/
|
||||
String sortAble() default "";
|
||||
|
||||
/**
|
||||
* 是否允许列的拖动操作 ,默认:true
|
||||
* 注: 如果<Properties>中的moveAble设为false, 则本moveAble无效(false)
|
||||
*/
|
||||
String moveAble() default "";
|
||||
|
||||
/**
|
||||
* 是否允许被粘贴 ,默认:supcan.xml
|
||||
* true - 允许() default "";
|
||||
* false - 不允许() default "";
|
||||
* supcan.xml - 通常是允许,但是当列不可编辑时(包括隐藏时),将以supcan.xml中的 <pasteAbleWhenUnEditAble> 的设定为准() default "";
|
||||
*/
|
||||
String pasteAble() default "";
|
||||
|
||||
/**
|
||||
* 指向另一列的列名,显示的内容存放在该列中,是另类 key-value对 的简易字典解决方案
|
||||
*/
|
||||
String textId() default "";
|
||||
|
||||
///////////////////////////////////// 外观 //////////////////////////////////////
|
||||
|
||||
/**
|
||||
* 是否以千位符分隔显示 true/false 默认:true
|
||||
* 注: 仅用于 datatype 为 int 或 double 时
|
||||
*/
|
||||
String isThousandSeparat() default "";
|
||||
|
||||
/**
|
||||
* 列宽 整数 - 绝对宽度 (单位:像素数)() default "";
|
||||
* 百分比 - 窗口宽度的百分比, 如:20%() default "";
|
||||
* 为小于1的分数 - 比例因子,用于分配剩余的宽度, 如0.2() default "";
|
||||
* fitHeader 或 header - 自动伸展到能使表头标题能够完整显示() default "";
|
||||
*/
|
||||
String width() default "";
|
||||
|
||||
/**
|
||||
* 列的最小宽度 像素数 10
|
||||
*/
|
||||
String minWidth() default "";
|
||||
|
||||
/**
|
||||
* 水平对齐 left / center / right
|
||||
*/
|
||||
String align() default "";
|
||||
|
||||
/**
|
||||
* 垂直对齐 top / vcenter(或middle) / bottom vcenter
|
||||
*/
|
||||
String vAlign() default "";
|
||||
|
||||
/**
|
||||
* 列标题文字的对齐 left / center / right center
|
||||
*/
|
||||
String alignHeader() default "";
|
||||
|
||||
/**
|
||||
* 采用的字体 数字,指向在<Fonts>中定义的字体的顺序号, 从0开始计数, 等级高于<Properties>中的同名属性 -1
|
||||
*/
|
||||
String fontIndex() default "";
|
||||
|
||||
/**
|
||||
* 列标题采用的字体 数字,指向在<Fonts>中定义的字体的顺序号, 从0开始计数, 等级高于<Properties>中的同名属性 -1
|
||||
*/
|
||||
String headerFontIndex() default "";
|
||||
|
||||
/**
|
||||
* 列标题文字颜色 颜色串 #000000
|
||||
*/
|
||||
String headerTextColor() default "";
|
||||
|
||||
/**
|
||||
* 列标题旁边的小图标 可以是图标的URL, 也可以是如下格式的串:
|
||||
* url=[?]() default "";pos=[?]
|
||||
* pos用于指定图标的位置, 是水平(left/right)、 垂直(top/middle/bottom)方向的组合. 举例如下:
|
||||
* url=../ac.png() default "";pos=right,bottom
|
||||
* 建议采用png或ico这类透明的图片
|
||||
*/
|
||||
String headerIcon() default "";
|
||||
|
||||
/**
|
||||
* 鼠标点击上述小图标时弹出的提示文字 文字串, 如果不定义这个串,鼠标点击小图标时将触发Clicked事件
|
||||
*/
|
||||
String headerIconTip() default "";
|
||||
|
||||
/**
|
||||
* 用于显示的格式掩码表达式 表达式的内容包括显示内容、 背景色、 文字色、 左图、 右图. 请详见Treelist帮助文档的"3.几个重要的属性"
|
||||
* formatDate(data,'YYYY-MM-DD')
|
||||
* =if(data=='1','关闭',if(data=='2','已完成',if(data=='3','未接收','进行中')))
|
||||
*/
|
||||
String displayMask() default "";
|
||||
|
||||
/**
|
||||
* 位于多层表头的层位置 数字,从0开始
|
||||
*/
|
||||
String atLayer() default "";
|
||||
|
||||
/**
|
||||
* 位于多层表头的层位置 数字,从0开始
|
||||
*/
|
||||
String extentRows() default "";
|
||||
|
||||
/**
|
||||
* 下拉列(droplis, droptreelist)单元格的文字显示方式 0 - 仅显示文字部分() default "";
|
||||
* 1 - 仅显示键值(即key)部分() default "";
|
||||
* 2 - 键值+" - "+文字() default "";
|
||||
*/
|
||||
String dropDisplayType() default "";
|
||||
|
||||
/**
|
||||
* 虚拟列的数据分隔符 串,比如"/", 如果设了这个串,在加载数据后,程序将按这个分隔符自动对各行数据进行处理,使其看上去呈现多列的效果。此外, 各个段中纵向、横向如果有连续相同的数据,将自动呈现纵、横的合并效果 (无)
|
||||
* 注1: 仅改变显示效果,并不改变数据() default "";
|
||||
* 注2: VColSep列有诸多限制,例如只能用于string型、不能作为树的排序列等等() default "";
|
||||
*/
|
||||
String VColSep() default "";
|
||||
|
||||
/**
|
||||
* VColSepStyle 虚拟列的合并方式 row - 只允许跨行的垂直合并() default "";
|
||||
* col - 只允许跨列的横向合并() default "";
|
||||
* row,col - 跨行、跨列自动合并() default "";
|
||||
*/
|
||||
String VColSepStyle() default "";
|
||||
|
||||
/**
|
||||
* 合计表达式
|
||||
*/
|
||||
String totalExpress() default "";
|
||||
|
||||
/**
|
||||
* 小计表达式
|
||||
*/
|
||||
String subTotalExpress() default "";
|
||||
|
||||
/**
|
||||
* 列的显示名称
|
||||
*/
|
||||
String text() default "";
|
||||
|
||||
/**
|
||||
* 归属组ID
|
||||
*/
|
||||
String groupId() default "";
|
||||
|
||||
/**
|
||||
* 排序(升序)
|
||||
*/
|
||||
int sort() default 0;
|
||||
}
|
||||
32
src/main/java/com/nis/supcan/SupExpress.java
Normal file
32
src/main/java/com/nis/supcan/SupExpress.java
Normal file
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 硕正Express注解
|
||||
* @author WangZhen
|
||||
* @version 2013-11-12
|
||||
*/
|
||||
@Target({ ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
public @interface SupExpress {
|
||||
|
||||
/**
|
||||
* 是否自动按列的引用关系优化计算顺序 默认值true
|
||||
*/
|
||||
String isOpt() default "";
|
||||
|
||||
/**
|
||||
* 文本
|
||||
*/
|
||||
String text() default "";
|
||||
|
||||
}
|
||||
59
src/main/java/com/nis/supcan/SupFont.java
Normal file
59
src/main/java/com/nis/supcan/SupFont.java
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 硕正Font注解
|
||||
* @author WangZhen
|
||||
* @version 2013-11-12
|
||||
*/
|
||||
@Target({ ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
public @interface SupFont {
|
||||
|
||||
/**
|
||||
* 字体名称 微软雅黑 宋体
|
||||
*/
|
||||
String faceName() default "";
|
||||
|
||||
/**
|
||||
* 字符集 134
|
||||
*/
|
||||
String charSet() default "";
|
||||
|
||||
/**
|
||||
* Height(或size)是字体的尺寸,单位是字体的逻辑单位,通常采用小于0的数字,
|
||||
* 如果大于0,则高度不包含文字的内部行距(internal-leading)。
|
||||
* 常用的尺寸是-8, -9, -10, -11, -12, -14, -16, -18, -20, -22, -24, -26, -28, -36, -48, -72() ;
|
||||
*/
|
||||
String height() default "";
|
||||
|
||||
/**
|
||||
* 字体加粗 weight=400/700 对应 非粗体/粗体;
|
||||
*/
|
||||
String weight() default "";
|
||||
|
||||
/**
|
||||
* 字体宽度
|
||||
*/
|
||||
String width() default "";
|
||||
|
||||
/**
|
||||
* 字体斜体
|
||||
*/
|
||||
String italic() default "";
|
||||
|
||||
/**
|
||||
* 字体下划线
|
||||
*/
|
||||
String underline() default "";
|
||||
|
||||
}
|
||||
56
src/main/java/com/nis/supcan/SupGroup.java
Normal file
56
src/main/java/com/nis/supcan/SupGroup.java
Normal file
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 硕正Group注解
|
||||
* @author WangZhen
|
||||
* @version 2013-11-12
|
||||
*/
|
||||
@Target({ ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
public @interface SupGroup {
|
||||
|
||||
/**
|
||||
* 分组的id,仅用于加载采用该id代替列名的XML/JSON数据
|
||||
*/
|
||||
String id();
|
||||
|
||||
/**
|
||||
* 显示的文字 串
|
||||
*/
|
||||
String name() default "";
|
||||
|
||||
/**
|
||||
* 采用的字体, 前面定义的<Font>的序号 数字 指向在<Fonts>中定义的字体的顺序号, 从0开始计数, 等级高于<Properties>中的同名属性
|
||||
*/
|
||||
String headerFontIndex() default "";
|
||||
|
||||
/**
|
||||
* 文字颜色 颜色串 #000000
|
||||
*/
|
||||
String textColor() default "";
|
||||
|
||||
/**
|
||||
* 文字对齐 left/center/right center
|
||||
*/
|
||||
String align() default "";
|
||||
|
||||
/**
|
||||
* 父级组ID
|
||||
*/
|
||||
String parentId() default "";
|
||||
|
||||
/**
|
||||
* 排序(升序)
|
||||
*/
|
||||
int sort() default 0;
|
||||
}
|
||||
149
src/main/java/com/nis/supcan/SupProperties.java
Normal file
149
src/main/java/com/nis/supcan/SupProperties.java
Normal file
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 硕正Properties注解
|
||||
* @author WangZhen
|
||||
* @version 2013-11-12
|
||||
*/
|
||||
@Target({ ElementType.ANNOTATION_TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
public @interface SupProperties {
|
||||
|
||||
/**
|
||||
* Treelist的ID 串
|
||||
*/
|
||||
String id() default "";
|
||||
|
||||
/**
|
||||
* 主键 串, 下面<col>的列名,复合主键须以逗号分隔
|
||||
*/
|
||||
String key() default "";
|
||||
|
||||
/**
|
||||
* 是否以树展现 true/false
|
||||
*/
|
||||
String isTree() default "";
|
||||
|
||||
/**
|
||||
* 是否显示左标尺 true/false
|
||||
* editAble=true时,isShowRuler的默认值是true,否则是false;
|
||||
*/
|
||||
String isShowRuler() default "";
|
||||
|
||||
/**
|
||||
* 合计行是否固定在底部、始终显示 true/false
|
||||
*/
|
||||
String isFixTotalRow() default "";
|
||||
|
||||
/**
|
||||
* 合计行的背景色 颜色串
|
||||
*/
|
||||
String totalBgColor() default "";
|
||||
|
||||
/**
|
||||
* 小计行的背景色 颜色串
|
||||
*/
|
||||
String subTotalBgColor() default "";
|
||||
|
||||
/**
|
||||
* 是否允许增删改操作 true/false
|
||||
* editAble=true时,isShowRuler的默认值是true,否则是false;
|
||||
*/
|
||||
String editAble() default "";
|
||||
|
||||
/**
|
||||
* 是否允许用户增行操作 true/false
|
||||
* 注1: 仅在editAble=true时生效; 注2: 不影响增删改的API;
|
||||
*/
|
||||
String addRowAble() default "";
|
||||
|
||||
/**
|
||||
* 分屏方式
|
||||
* true - 始终显示分隔条;
|
||||
* false - 始终不显示分隔条;
|
||||
* auto - 自动(超宽时会在左侧浮现分隔条);
|
||||
*/
|
||||
String separateBarStyle() default "";
|
||||
|
||||
/**
|
||||
* 点击列标题是否执行排序 true/false
|
||||
*/
|
||||
String sortAble() default "";
|
||||
|
||||
/**
|
||||
* 是否允许多层表头 true/false
|
||||
*/
|
||||
String multiLayerAble() default "";
|
||||
|
||||
/**
|
||||
* 执行 Load() 函数时的淡入淡出效果 0 - 255, 数值越小效果越明显, 而 0 表示关闭此效果
|
||||
*/
|
||||
String fadeInStep() default "";
|
||||
|
||||
/**
|
||||
* 顶部标题条的背景色 颜色串,可以是以逗号分隔的多个颜色(渐变)
|
||||
*/
|
||||
String headerBgColor() default "";
|
||||
|
||||
/**
|
||||
* 顶部标题条的高度 像素数
|
||||
*/
|
||||
String headerHeight() default "";
|
||||
|
||||
/**
|
||||
* 左标尺的背景色,颜色串,可以是以逗号分隔的多个颜色(渐变)
|
||||
*/
|
||||
String leftColor() default "";
|
||||
|
||||
/**
|
||||
* 行高像素数
|
||||
*/
|
||||
String rowHeight() default "";
|
||||
|
||||
/**
|
||||
* 当前行的颜色,允许多个颜色渐变
|
||||
* 颜色串, 支持ARGB格式,例如: "#10C0D0E0", 其中 "10" 是 alpha(透明度), "C0D0E0" 是 RGB, 此外, 还支持包含如下边框属性:
|
||||
* borderWidth - 边框线宽
|
||||
* borderColor - 边框线色
|
||||
* borderRound - 边框线的圆角直径
|
||||
* 示例: "#12FFFFFF,#22EEFFEE; borderWidth=1; borderColor=red; borderRound=8"
|
||||
*/
|
||||
String curSelBgColor() default ""; // #F5F5F5 #FFE88D
|
||||
|
||||
/**
|
||||
* 整行的背景色、文字色表达式 表达式, 如:
|
||||
* displayMask = "bgColor=if(price=0, red, transparent); textColor=if(price>2,#000022, blue)"
|
||||
*/
|
||||
String displayMask() default "";
|
||||
|
||||
/**
|
||||
* 指定标题栏默认字体 <Fonts>中的字体顺序号 指向在<Fonts>中定义的字体的顺序号, 从0开始计数, 等级高于<Properties>中的同名属性
|
||||
*/
|
||||
String headerFontIndex() default "";
|
||||
|
||||
/**
|
||||
* 设置背景
|
||||
*/
|
||||
SupBackground packground() default @SupBackground;
|
||||
|
||||
/**
|
||||
* 计算列表达式
|
||||
*/
|
||||
SupExpress[] expresses() default {};
|
||||
|
||||
/**
|
||||
* 打印简易配置 标题
|
||||
*/
|
||||
String title() default "";
|
||||
|
||||
}
|
||||
55
src/main/java/com/nis/supcan/SupTreeList.java
Normal file
55
src/main/java/com/nis/supcan/SupTreeList.java
Normal file
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
/**
|
||||
* 硕正TreeList注解
|
||||
* @author WangZhen
|
||||
* @version 2013-11-12
|
||||
* @see 在类上添加注解,应用实例:
|
||||
|
||||
@SupTreeList(
|
||||
properties=@SupProperties(headerFontIndex="2", curSelBgColor="#ccddcc",
|
||||
displayMask="backColor=if(name='管理员', '#ff0000', transparent)",
|
||||
expresses={
|
||||
@SupExpress(text="total=round(price*num, 2)"),
|
||||
@SupExpress(text="price=round(total/num, 4)")
|
||||
}),
|
||||
fonts={
|
||||
@SupFont(faceName="宋体", weight="400"),
|
||||
@SupFont(faceName="楷体", weight="700", height="-12"),
|
||||
@SupFont(faceName="楷体", weight="400", height="-12")},
|
||||
groups={
|
||||
@SupGroup(id="date", name="日期", headerFontIndex="1", sort=50),
|
||||
@SupGroup(id="date2", name="日期2", headerFontIndex="2", sort=60, parentId="date"),
|
||||
@SupGroup(id="date3", name="日期3", headerFontIndex="2", sort=70, parentId="date")
|
||||
})
|
||||
|
||||
*/
|
||||
@Target({ ElementType.TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Inherited
|
||||
public @interface SupTreeList {
|
||||
|
||||
/**
|
||||
* 属性对象
|
||||
*/
|
||||
SupProperties properties() default @SupProperties;
|
||||
|
||||
/**
|
||||
* 字体对象
|
||||
*/
|
||||
SupFont[] fonts() default {};
|
||||
|
||||
/**
|
||||
* 列表头组
|
||||
*/
|
||||
SupGroup[] groups() default {};
|
||||
|
||||
}
|
||||
213
src/main/java/com/nis/supcan/SupcanController.java
Normal file
213
src/main/java/com/nis/supcan/SupcanController.java
Normal file
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.util.CacheUtils;
|
||||
import com.nis.util.Configurations;
|
||||
import com.nis.util.StringUtils;
|
||||
import com.nis.web.controller.BaseController;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
/**
|
||||
* 硕正Controller
|
||||
* @author ThinkGem
|
||||
* @version 2013-11-13
|
||||
*/
|
||||
@Controller
|
||||
@RequestMapping(value = "${adminPath}/supcan")
|
||||
public class SupcanController extends BaseController {
|
||||
|
||||
private static final String SUPCAN_CACHE = "supcanCache";
|
||||
|
||||
/**
|
||||
* 获取硕正树列表描述(根据注解获取XML)
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = "treeList/{typeAlias}.xml")
|
||||
@ResponseBody
|
||||
public TreeList treeList(@PathVariable("typeAlias") String typeAlias) {
|
||||
|
||||
// 如果使用Cache,并且在Cache里存在,则直接返回。
|
||||
boolean useCache = Configurations.getBooleanProperty("supcan.useCache", false);
|
||||
if (useCache){
|
||||
Object object = CacheUtils.get(SUPCAN_CACHE, typeAlias);
|
||||
if (object != null){
|
||||
return (TreeList)object;
|
||||
}
|
||||
}
|
||||
|
||||
// 实体类型
|
||||
Class<?> clazz;
|
||||
|
||||
try{
|
||||
// 根据别名获取MyBaits注册类型。
|
||||
SqlSessionFactory sqlSessionFactory = SpringContextHolder.getBean(SqlSessionFactory.class);
|
||||
clazz = sqlSessionFactory.getConfiguration().getTypeAliasRegistry().resolveAlias(typeAlias);
|
||||
}catch (Exception e) {
|
||||
// 取不到类型,返回空。
|
||||
return null;
|
||||
}
|
||||
|
||||
// 获取硕正注解配置
|
||||
SupTreeList supTreeList = clazz.getAnnotation(SupTreeList.class);
|
||||
|
||||
// 没有硕正注解配置,则返回空
|
||||
if (supTreeList == null){
|
||||
return null;
|
||||
}
|
||||
|
||||
// 实例化硕正树列表对象
|
||||
TreeList treeList = new TreeList(supTreeList);
|
||||
|
||||
// 获取表头分组
|
||||
Map<String, Group> groupMap = Maps.newHashMap();
|
||||
if (supTreeList !=null && supTreeList.groups() != null){
|
||||
for (SupGroup supGroup : supTreeList.groups()){
|
||||
groupMap.put(supGroup.id(), new Group(supGroup));
|
||||
}
|
||||
}
|
||||
|
||||
// 获取表头列
|
||||
List<Object> cols = treeList.getCols();
|
||||
for (Method m : clazz.getMethods()){
|
||||
SupCol supCol = m.getAnnotation(SupCol.class);
|
||||
if (supCol != null){
|
||||
|
||||
// 转为为Col对象
|
||||
Col col = new Col(supCol);
|
||||
if (StringUtils.isBlank(col.getName())){
|
||||
col.setName(StringUtils.uncapitalize(StringUtils.substring(m.getName(), 3)));
|
||||
}
|
||||
|
||||
// 无分组
|
||||
if (StringUtils.isBlank(supCol.groupId())){
|
||||
cols.add(col);
|
||||
}
|
||||
// 有分组
|
||||
else{
|
||||
Group group = groupMap.get(supCol.groupId());
|
||||
if (group != null){
|
||||
group.getCols().add(col);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 创建字段排序类
|
||||
Comparator<Object> comparator = new Comparator<Object>() {
|
||||
@Override
|
||||
public int compare(Object o1, Object o2) {
|
||||
int sort1 = 0, sort2 = 0;
|
||||
if (o1 instanceof Group){
|
||||
sort1 = ((Group)o1).getSort();
|
||||
}else if (o1 instanceof Col){
|
||||
sort1 = ((Col)o1).getSort();
|
||||
}
|
||||
if (o2 instanceof Group){
|
||||
sort2 = ((Group)o2).getSort();
|
||||
}else if (o2 instanceof Col){
|
||||
sort2 = ((Col)o2).getSort();
|
||||
}
|
||||
return new Integer(sort1).compareTo(new Integer(sort2));
|
||||
}
|
||||
};
|
||||
|
||||
// 将列表转换为树结构并排序
|
||||
listToTree(cols, groupMap, null, comparator);
|
||||
|
||||
// 整体排序
|
||||
Collections.sort(cols, comparator);
|
||||
|
||||
// 如果使用Cache,则保存到Cache
|
||||
if (useCache){
|
||||
CacheUtils.put(SUPCAN_CACHE, typeAlias, treeList);
|
||||
}
|
||||
|
||||
return treeList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将分组转换为树结构
|
||||
* @param list
|
||||
* @param groupMap
|
||||
* @param parentId
|
||||
*/
|
||||
private void listToTree(List<Object> colList, Map<String, Group> groupMap, String parentId, Comparator<Object> comparator){
|
||||
for (Map.Entry<String, Group> e : groupMap.entrySet()){
|
||||
Group g = e.getValue();
|
||||
if (StringUtils.equals(parentId, g.getParentId())){
|
||||
colList.add(g);
|
||||
// 判断是否有子节点,有的话则加进去
|
||||
for (Map.Entry<String, Group> ec : groupMap.entrySet()){
|
||||
Group gc = ec.getValue();
|
||||
if (g.getId() != null && g.getId().equals(gc.getParentId())){
|
||||
List<Object> childrenList = Lists.newArrayList();
|
||||
listToTree(childrenList, groupMap, gc.getParentId(), comparator);
|
||||
g.getCols().addAll(childrenList);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 排序
|
||||
Collections.sort(g.getCols(), comparator);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取硕正树列表描述(注册对象方法获取XML) 测试实例
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = "treeList/test/test.xml")
|
||||
@ResponseBody
|
||||
public TreeList treeListTest() {
|
||||
|
||||
// 创建树列表描述对象
|
||||
TreeList treeList = new TreeList();
|
||||
|
||||
// 设置树列表,表头
|
||||
List<Object> cols = treeList.getCols();
|
||||
cols.add(new Col("id", "编号"));
|
||||
cols.add(new Col("office", "归属部门"));
|
||||
cols.add(new Col("loginName", "登录名"));
|
||||
cols.add(new Col("name", "名称"));
|
||||
cols.add(new Col("remarks", "备注"));
|
||||
|
||||
// 设置树列表,多层表头
|
||||
|
||||
// 分组1
|
||||
Group group = new Group("时间");
|
||||
List<Object> groupCol = group.getCols();
|
||||
groupCol.add(new Col("createDate", "创建时间"));
|
||||
groupCol.add(new Col("updateDate", "更新时间"));
|
||||
|
||||
// 分组2
|
||||
Group group2 = new Group("时间2");
|
||||
List<Object> group2Col = group2.getCols();
|
||||
group2Col.add(new Col("createDate2", "创建时间2"));
|
||||
group2Col.add(new Col("updateDate2", "更新时间2"));
|
||||
|
||||
// 将分组2添加到,分组1的表头
|
||||
groupCol.add(group2);
|
||||
|
||||
// 将分组1添加到,主表头
|
||||
cols.add(group);
|
||||
|
||||
// 返回TreeList描述对象
|
||||
return treeList;
|
||||
}
|
||||
}
|
||||
62
src/main/java/com/nis/supcan/TreeList.java
Normal file
62
src/main/java/com/nis/supcan/TreeList.java
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.supcan;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.thoughtworks.xstream.annotations.XStreamAlias;
|
||||
|
||||
/**
|
||||
* 硕正TreeList
|
||||
* @author WangZhen
|
||||
* @version 2013-11-04
|
||||
*/
|
||||
@XStreamAlias("TreeList")
|
||||
public class TreeList extends Common {
|
||||
|
||||
/**
|
||||
* 列集合
|
||||
*/
|
||||
@XStreamAlias("Cols")
|
||||
private List<Object> cols;
|
||||
|
||||
public TreeList() {
|
||||
super();
|
||||
}
|
||||
|
||||
public TreeList(Properties properties) {
|
||||
this();
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public TreeList(SupTreeList supTreeList) {
|
||||
this();
|
||||
if (supTreeList != null){
|
||||
if (supTreeList.properties() != null){
|
||||
this.properties = new Properties(supTreeList.properties());
|
||||
}
|
||||
if (supTreeList.fonts() != null){
|
||||
for (SupFont supFont : supTreeList.fonts()){
|
||||
if (this.fonts == null){
|
||||
this.fonts = Lists.newArrayList();
|
||||
}
|
||||
this.fonts.add(new Font(supFont));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<Object> getCols() {
|
||||
if (cols == null){
|
||||
cols = Lists.newArrayList();
|
||||
}
|
||||
return cols;
|
||||
}
|
||||
|
||||
public void setCols(List<Object> cols) {
|
||||
this.cols = cols;
|
||||
}
|
||||
|
||||
}
|
||||
45
src/main/java/com/nis/util/AsciiJudge.java
Normal file
45
src/main/java/com/nis/util/AsciiJudge.java
Normal file
@@ -0,0 +1,45 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 判断关键字的内容不能包含空格、tab、回车等不可见字符,即ANSII范围0x00至0x1F(0-31)及0x7F(127)。
|
||||
*
|
||||
* @author RenKaiGe-Office
|
||||
*
|
||||
*/
|
||||
public class AsciiJudge {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String str = "fdsf你说说你发的是佛山东方啥的飞sdf 啥打法是否(\\&)";
|
||||
boolean bool = asciiControlChar(str);
|
||||
System.out.println(bool);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串是否包含控制字符
|
||||
*
|
||||
* @param str
|
||||
* 需要验证的字符串,可以为空字符串但是不能为null
|
||||
* @return true代表包含控制字符,false代表不是控制字符或为null
|
||||
*/
|
||||
public static boolean asciiControlChar(String str) {
|
||||
if (null != str) {
|
||||
List<String> list = new ArrayList<String>();
|
||||
for (int i = 0; i < 32; i++) {
|
||||
list.add(String.valueOf(i));
|
||||
}
|
||||
list.add("127");
|
||||
char[] charArr = str.toCharArray();
|
||||
for (char c : charArr) {
|
||||
String num = Integer.valueOf(c).toString();
|
||||
if (list.contains(num)) {
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
199
src/main/java/com/nis/util/BasicProvingUtil.java
Normal file
199
src/main/java/com/nis/util/BasicProvingUtil.java
Normal file
@@ -0,0 +1,199 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class BasicProvingUtil {
|
||||
public static void main(String[] args) {
|
||||
// String ip = "::";
|
||||
String ip = " fe80::d025:864c:3151:daa0";
|
||||
System.out.println(ip + "=" + isIpv6(ip));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是Integer类型
|
||||
*
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public static boolean isIntType(Object obj) {
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
String num = obj.toString().trim();
|
||||
if (num.length() == 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Integer.parseInt(num);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是Long类型
|
||||
*
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public static boolean isLongType(Object obj) {
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
String num = obj.toString().trim();
|
||||
if (num.length() == 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Long.parseLong(num);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是Double类型
|
||||
*
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public static boolean isDoubleType(Object obj) {
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
String num = obj.toString().trim();
|
||||
if (num.length() == 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Double.parseDouble(num);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断ip或ip掩码格式是否正确(ipv4或ipv6) true代表格式正确 false代表格式不正确
|
||||
*
|
||||
* @param ip
|
||||
* @param ipType
|
||||
* ipv4还是ipv6(4,6)
|
||||
* @return
|
||||
*/
|
||||
public static boolean isIpOrIpMask(String ip, Integer ipType) {
|
||||
// boolean ipv4Bool = val_ipv4(ip);
|
||||
// boolean ipv6Bool = val_ipv6(ip);
|
||||
// if (ipv6Bool) {
|
||||
|
||||
if (null != ip && !ip.equals("")) {
|
||||
if (null != ipType && ipType == 4) {
|
||||
boolean ipv4 = isIpv4(ip.trim());
|
||||
if (ipv4) {
|
||||
return true;
|
||||
}
|
||||
} else if (null != ipType && ipType == 6) {
|
||||
boolean ipv6 = isIpv6(ip.trim());
|
||||
if (ipv6) {
|
||||
return true;
|
||||
}
|
||||
|
||||
} else {// ipType不等于4或6时不验证与ipType是否一致,仅验证是否是ip格式
|
||||
boolean ipv6 = isIpv6(ip.trim());
|
||||
boolean ipv4 = isIpv4(ip.trim());
|
||||
if (ipv6 || ipv4) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断端口或端口掩码格式是否正确(0-65535) true代表格式正确 false代表格式不正确
|
||||
*
|
||||
* @param ip
|
||||
* @return
|
||||
*/
|
||||
public static boolean isPortOrPortMask(String port) {
|
||||
try {
|
||||
if (null != port && !port.equals("")) {
|
||||
int parseInt = Integer.parseInt(port.trim());
|
||||
if (parseInt >= 0 && parseInt <= 65535) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isIpv4(String ipAddress) {
|
||||
try {
|
||||
String ipv4 = "^(0|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
|
||||
+ "(0|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(0|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
|
||||
+ "(0|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
|
||||
return Pattern.compile(ipv4).matcher(ipAddress).matches();
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isIpv6(String ipAddress) {
|
||||
try {
|
||||
|
||||
String ipv6 = "^((::)|(([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:)|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}(:[0-9A-Fa-f]{1,4}){1,2})|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){1,3})|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){1,4})|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){1,5})|([0-9A-Fa-f]{1,4}:(:[0-9A-Fa-f]{1,4}){1,6})|(:(:[0-9A-Fa-f]{1,4}){1,7})|(([0-9A-Fa-f]{1,4}:){6}(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){5}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|([0-9A-Fa-f]{1,4}:(:[0-9A-Fa-f]{1,4}){0,4}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(:(:[0-9A-Fa-f]{1,4}){0,5}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}))$";
|
||||
return Pattern.compile(ipv6).matcher(ipAddress).matches();
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean val_ipv4(String host) {
|
||||
InetAddress addressIpv4 = null;
|
||||
|
||||
try {
|
||||
addressIpv4 = InetAddress.getByName(host);
|
||||
} catch (UnknownHostException e) {
|
||||
return false;
|
||||
}
|
||||
if (addressIpv4 instanceof Inet6Address) {
|
||||
return false;
|
||||
}
|
||||
if (addressIpv4 instanceof Inet4Address) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean val_ipv6(String host) {
|
||||
InetAddress addressIpv6 = null;
|
||||
try {
|
||||
addressIpv6 = InetAddress.getByName(host);
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
if (addressIpv6 instanceof Inet6Address) {
|
||||
return true;
|
||||
}
|
||||
if (addressIpv6 instanceof Inet4Address) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
154
src/main/java/com/nis/util/BeanHelper.java
Normal file
154
src/main/java/com/nis/util/BeanHelper.java
Normal file
@@ -0,0 +1,154 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
/**
|
||||
*
|
||||
* <p>Title:BeanHelper</p>
|
||||
* <p>Description:去除Bean中String类型字段的前后空格</p>
|
||||
*
|
||||
* @author:RKG
|
||||
* @Date:2016-4-29
|
||||
*/
|
||||
public class BeanHelper {
|
||||
|
||||
/**
|
||||
* 去掉bean中所有属性为字符串的前后空格
|
||||
*
|
||||
* @param bean
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void beanAttributeValueTrim(Object bean) throws Exception {
|
||||
if (bean != null) {
|
||||
// 获取所有的字段包括public,private,protected,private
|
||||
Field[] fields = bean.getClass().getDeclaredFields();
|
||||
for (int i = 0; i < fields.length; i++) {
|
||||
Field f = fields[i];
|
||||
if (f.getType().getName().equals("java.lang.String")) {
|
||||
String key = f.getName();// 获取字段名
|
||||
Object value = getFieldValue(bean, key);
|
||||
|
||||
if (value == null)
|
||||
continue;
|
||||
setFieldValue(bean, key, value.toString().trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 利用反射通过get方法获取bean中字段fieldName的值
|
||||
*
|
||||
* @param bean
|
||||
* @param fieldName
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
private static Object getFieldValue(Object bean, String fieldName)
|
||||
throws Exception {
|
||||
StringBuffer result = new StringBuffer();
|
||||
String methodName = result.append("get")
|
||||
.append(fieldName.substring(0, 1).toUpperCase())
|
||||
.append(fieldName.substring(1)).toString();
|
||||
|
||||
Object rObject = null;
|
||||
Method method = null;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
Class[] classArr = new Class[0];
|
||||
method = bean.getClass().getMethod(methodName, classArr);
|
||||
rObject = method.invoke(bean, new Object[0]);
|
||||
|
||||
return rObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* 利用发射调用bean.set方法将value设置到字段
|
||||
*
|
||||
* @param bean
|
||||
* @param fieldName
|
||||
* @param value
|
||||
* @throws Exception
|
||||
*/
|
||||
private static void setFieldValue(Object bean, String fieldName,
|
||||
Object value) throws Exception {
|
||||
StringBuffer result = new StringBuffer();
|
||||
String methodName = result.append("set")
|
||||
.append(fieldName.substring(0, 1).toUpperCase())
|
||||
.append(fieldName.substring(1)).toString();
|
||||
|
||||
/**
|
||||
* 利用发射调用bean.set方法将value设置到字段
|
||||
*/
|
||||
Class[] classArr = new Class[1];
|
||||
classArr[0] = "java.lang.String".getClass();
|
||||
Method method = bean.getClass().getMethod(methodName, classArr);
|
||||
method.invoke(bean, value);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* transportBean2Map(将Java bean转换为Map)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param clazz
|
||||
* @param obj
|
||||
* @return
|
||||
* @throws IntrospectionException
|
||||
*Map<String,String>
|
||||
* @throws InvocationTargetException
|
||||
* @throws IllegalArgumentException
|
||||
* @throws IllegalAccessException
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public static Map<String,String> transportBean2Map(Class clazz,Object obj) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
|
||||
Map<String,String> bean=new LinkedHashMap<>();
|
||||
BeanInfo beanInfo=Introspector.getBeanInfo(clazz);
|
||||
PropertyDescriptor[] propertyDescriptors=beanInfo.getPropertyDescriptors();
|
||||
for(PropertyDescriptor propertyDescriptor:propertyDescriptors){
|
||||
String key =propertyDescriptor.getName();
|
||||
if(!key.equals("class")){
|
||||
String _value=null;
|
||||
Method getter=propertyDescriptor.getReadMethod();
|
||||
Object value =getter.invoke(obj);
|
||||
if(value==null) continue;
|
||||
else if(value instanceof java.util.Date)//时间类型转换成long
|
||||
_value=String.valueOf(((java.util.Date)value).getTime());
|
||||
else if(value instanceof Boolean||value instanceof Integer||value instanceof Long){
|
||||
_value=String.valueOf(value);
|
||||
}else if(value instanceof String){
|
||||
_value=(String)value;
|
||||
}else if(value instanceof Collection){
|
||||
throw new RuntimeException("不支持对象中嵌套的对象集合");
|
||||
}else{
|
||||
|
||||
}
|
||||
if(_value!=null)
|
||||
bean.put(key, _value);
|
||||
}
|
||||
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
// SrcIp ip=new SrcIp();
|
||||
// ip.setAreaId(1l);
|
||||
// try {
|
||||
// Map<String,String> transportBean2Map=transportBean2Map(SrcIp.class,ip);
|
||||
// System.out.println(transportBean2Map.size());
|
||||
// for(Entry<String, String> e:transportBean2Map.entrySet()){
|
||||
// System.out.println(e.getKey()+" "+e.getValue());
|
||||
// }
|
||||
// } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
|
||||
// // TODO Auto-generated catch block
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
}
|
||||
}
|
||||
97
src/main/java/com/nis/util/CacheUtils.java
Normal file
97
src/main/java/com/nis/util/CacheUtils.java
Normal file
@@ -0,0 +1,97 @@
|
||||
package com.nis.util;
|
||||
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
import net.sf.ehcache.Cache;
|
||||
import net.sf.ehcache.CacheManager;
|
||||
import net.sf.ehcache.Element;
|
||||
|
||||
/**
|
||||
* Cache工具类
|
||||
* @author darnell
|
||||
*
|
||||
*/
|
||||
public class CacheUtils {
|
||||
|
||||
private static CacheManager cacheManager = ((CacheManager)SpringContextHolder.getBean("cacheManager"));
|
||||
|
||||
private static final String SYS_CACHE = "sysCache";
|
||||
|
||||
/**
|
||||
* 获取SYS_CACHE缓存
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Object get(String key) {
|
||||
return get(SYS_CACHE, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入SYS_CACHE缓存
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static void put(String key, Object value) {
|
||||
put(SYS_CACHE, key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从SYS_CACHE缓存中移除
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static void remove(String key) {
|
||||
remove(SYS_CACHE, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存
|
||||
* @param cacheName
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Object get(String cacheName, String key) {
|
||||
Element element = getCache(cacheName).get(key);
|
||||
return element==null?null:element.getObjectValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入缓存
|
||||
* @param cacheName
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
public static void put(String cacheName, String key, Object value) {
|
||||
Element element = new Element(key, value);
|
||||
getCache(cacheName).put(element);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从缓存中移除
|
||||
* @param cacheName
|
||||
* @param key
|
||||
*/
|
||||
public static void remove(String cacheName, String key) {
|
||||
getCache(cacheName).remove(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个Cache,没有则创建一个。
|
||||
* @param cacheName
|
||||
* @return
|
||||
*/
|
||||
private static Cache getCache(String cacheName){
|
||||
Cache cache = cacheManager.getCache(cacheName);
|
||||
if (cache == null){
|
||||
cacheManager.addCache(cacheName);
|
||||
cache = cacheManager.getCache(cacheName);
|
||||
cache.getCacheConfiguration().setEternal(true);
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
|
||||
public static CacheManager getCacheManager() {
|
||||
return cacheManager;
|
||||
}
|
||||
|
||||
}
|
||||
176
src/main/java/com/nis/util/Collections3.java
Normal file
176
src/main/java/com/nis/util/Collections3.java
Normal file
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.beanutils.PropertyUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
/**
|
||||
* Collections工具集.
|
||||
* 在JDK的Collections和Guava的Collections2后, 命名为Collections3.
|
||||
* @author calvin
|
||||
* @version 2013-01-15
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public class Collections3 {
|
||||
|
||||
/**
|
||||
* 提取集合中的对象的两个属性(通过Getter函数), 组合成Map.
|
||||
*
|
||||
* @param collection 来源集合.
|
||||
* @param keyPropertyName 要提取为Map中的Key值的属性名.
|
||||
* @param valuePropertyName 要提取为Map中的Value值的属性名.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Map extractToMap(final Collection collection, final String keyPropertyName,
|
||||
final String valuePropertyName) {
|
||||
Map map = new HashMap(collection.size());
|
||||
|
||||
try {
|
||||
for (Object obj : collection) {
|
||||
map.put(PropertyUtils.getProperty(obj, keyPropertyName),
|
||||
PropertyUtils.getProperty(obj, valuePropertyName));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw Reflections.convertReflectionExceptionToUnchecked(e);
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
|
||||
*
|
||||
* @param collection 来源集合.
|
||||
* @param propertyName 要提取的属性名.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static List extractToList(final Collection collection, final String propertyName) {
|
||||
List list = new ArrayList(collection.size());
|
||||
|
||||
try {
|
||||
for (Object obj : collection) {
|
||||
list.add(PropertyUtils.getProperty(obj, propertyName));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw Reflections.convertReflectionExceptionToUnchecked(e);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取集合中的对象的一个属性(通过Getter函数), 组合成由分割符分隔的字符串.
|
||||
*
|
||||
* @param collection 来源集合.
|
||||
* @param propertyName 要提取的属性名.
|
||||
* @param separator 分隔符.
|
||||
*/
|
||||
public static String extractToString(final Collection collection, final String propertyName, final String separator) {
|
||||
List list = extractToList(collection, propertyName);
|
||||
return StringUtils.join(list, separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换Collection所有元素(通过toString())为String, 中间以 separator分隔。
|
||||
*/
|
||||
public static String convertToString(final Collection collection, final String separator) {
|
||||
return StringUtils.join(collection, separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换Collection所有元素(通过toString())为String, 每个元素的前面加入prefix,后面加入postfix,如<div>mymessage</div>。
|
||||
*/
|
||||
public static String convertToString(final Collection collection, final String prefix, final String postfix) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (Object o : collection) {
|
||||
builder.append(prefix).append(o).append(postfix);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为空.
|
||||
*/
|
||||
public static boolean isEmpty(Collection collection) {
|
||||
return (collection == null || collection.isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* 取得Collection的第一个元素,如果collection为空返回null.
|
||||
*/
|
||||
public static <T> T getFirst(Collection<T> collection) {
|
||||
if (isEmpty(collection)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return collection.iterator().next();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Collection的最后一个元素 ,如果collection为空返回null.
|
||||
*/
|
||||
public static <T> T getLast(Collection<T> collection) {
|
||||
if (isEmpty(collection)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//当类型为List时,直接取得最后一个元素 。
|
||||
if (collection instanceof List) {
|
||||
List<T> list = (List<T>) collection;
|
||||
return list.get(list.size() - 1);
|
||||
}
|
||||
|
||||
//其他类型通过iterator滚动到最后一个元素.
|
||||
Iterator<T> iterator = collection.iterator();
|
||||
while (true) {
|
||||
T current = iterator.next();
|
||||
if (!iterator.hasNext()) {
|
||||
return current;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回a+b的新List.
|
||||
*/
|
||||
public static <T> List<T> union(final Collection<T> a, final Collection<T> b) {
|
||||
List<T> result = new ArrayList<T>(a);
|
||||
result.addAll(b);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回a-b的新List.
|
||||
*/
|
||||
public static <T> List<T> subtract(final Collection<T> a, final Collection<T> b) {
|
||||
List<T> list = new ArrayList<T>(a);
|
||||
for (T element : b) {
|
||||
list.remove(element);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回a与b的交集的新List.
|
||||
*/
|
||||
public static <T> List<T> intersection(Collection<T> a, Collection<T> b) {
|
||||
List<T> list = new ArrayList<T>();
|
||||
|
||||
for (T element : a) {
|
||||
if (b.contains(element)) {
|
||||
list.add(element);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
84
src/main/java/com/nis/util/Configurations.java
Normal file
84
src/main/java/com/nis/util/Configurations.java
Normal file
@@ -0,0 +1,84 @@
|
||||
package com.nis.util;
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import com.nis.util.StringUtil;
|
||||
|
||||
|
||||
|
||||
|
||||
public final class Configurations {
|
||||
private static Properties prop = new Properties();
|
||||
|
||||
static {
|
||||
try {
|
||||
prop.load(Configurations.class.getResourceAsStream("/nis.properties"));
|
||||
prop.load(Configurations.class.getResourceAsStream("/table.properties"));
|
||||
prop.load(Configurations.class.getResourceAsStream("/matt.properties"));
|
||||
|
||||
} catch (Exception e) {
|
||||
prop = null;
|
||||
System.err.println("未知nis.properties,请确定文件是否存在!");
|
||||
}
|
||||
}
|
||||
|
||||
public static String getStringProperty(String key, String defaultValue) {
|
||||
if (prop==null||StringUtil.isBlank(prop.getProperty(key))) {
|
||||
return defaultValue;
|
||||
}
|
||||
return prop.getProperty(key).trim();
|
||||
}
|
||||
|
||||
public static int getIntProperty(String key, int defaultValue) {
|
||||
if (prop==null||StringUtil.isBlank(prop.getProperty(key))) {
|
||||
return defaultValue;
|
||||
}
|
||||
return Integer.parseInt(prop.getProperty(key).trim());
|
||||
}
|
||||
|
||||
public static long getLongProperty(String key, long defaultValue) {
|
||||
if (prop==null||StringUtil.isBlank(prop.getProperty(key))) {
|
||||
return defaultValue;
|
||||
}
|
||||
return Long.parseLong(prop.getProperty(key).trim());
|
||||
}
|
||||
|
||||
public static boolean getBooleanProperty(String key, boolean defaultValue) {
|
||||
if (prop==null||StringUtil.isBlank(prop.getProperty(key))) {
|
||||
return defaultValue;
|
||||
}
|
||||
return prop.getProperty(key).toLowerCase().trim().equals("true");
|
||||
}
|
||||
|
||||
public static String getFileDirPathProperty(String key,
|
||||
String defaultValue) {
|
||||
if (prop==null||StringUtil.isBlank(prop.getProperty(key))) {
|
||||
return defaultValue;
|
||||
}
|
||||
String path = prop.getProperty(key).trim();
|
||||
File file = new File(path);
|
||||
if (!file.exists()) {
|
||||
file.mkdir();
|
||||
}
|
||||
return file.getAbsolutePath();
|
||||
}
|
||||
|
||||
public static boolean configPropertyIsFound() {
|
||||
if (prop == null) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public static Map getProp() {
|
||||
return prop;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
187
src/main/java/com/nis/util/Constants.java
Normal file
187
src/main/java/com/nis/util/Constants.java
Normal file
@@ -0,0 +1,187 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
public final class Constants {
|
||||
|
||||
public static final String DEFAULT_CAPTCHA_PARAM = "captcha";
|
||||
public static final String DEFAULT_MOBILE_PARAM = "mobileLogin";
|
||||
public static final String DEFAULT_MESSAGE_PARAM = "message";
|
||||
|
||||
/**
|
||||
* 词典数据key
|
||||
*/
|
||||
public static final String CACHE_DICT_MAP = "dictMap";
|
||||
|
||||
/**
|
||||
* 上传文件基础虚拟路径
|
||||
*/
|
||||
public static final String USERFILES_BASE_URL = "/userfiles/";
|
||||
|
||||
public static final String HASH_ALGORITHM = "SHA-1";
|
||||
public static final int HASH_INTERATIONS = 1024;
|
||||
public static final int SALT_SIZE = 8;
|
||||
|
||||
public static final int LOG_ACCESS_SUCCESS = 1;
|
||||
public static final int LOG_ACCESS_EXCEPTION = 0;
|
||||
/**
|
||||
* 默认未知方法(未添加词典或未识别)操作类型值为:unknown(8000)
|
||||
*/
|
||||
public static final int DEFAULT_METHOD_TYPE = 8000;
|
||||
|
||||
public static final String SYS_BUSINESS_MENU_NAME = "信访管理";
|
||||
|
||||
public static final String LABEL_DEFAULT = "label";
|
||||
public static final String LABEL_SUCCESS = "label label-success";
|
||||
public static final String LABEL_WARNING = "label label-warning";
|
||||
public static final String LABEL_IMPORTANT = "label label-important";
|
||||
public static final String LABEL_INFO = "label label-info";
|
||||
public static final String LABEL_INVERSE = "label label-inverse";
|
||||
/**
|
||||
* 生效系统
|
||||
*/
|
||||
public static final String ACTIVESYS_A = "4";
|
||||
public static final String ACTIVESYS_B = "2";
|
||||
public static final String ACTIVESYS_C = "1";
|
||||
public static final String ACTIVESYS_ALL = "7";
|
||||
//A+B版
|
||||
public static final String ACTIVESYS_AB = "6";
|
||||
/**
|
||||
* 数据库操作
|
||||
*/
|
||||
public static final String INSERT = "I";
|
||||
public static final String UPDATE = "U";
|
||||
public static final String DELETE = "D";
|
||||
/**
|
||||
* 接口的操作行为opAction
|
||||
*/
|
||||
public static final int OPACTION_POST = 1;
|
||||
public static final int OPACTION_PUT = 2;
|
||||
public static final int OPACTION_DELETE = 3;
|
||||
public static final int OPACTION_GET = 4;
|
||||
/**
|
||||
* 是/否
|
||||
*/
|
||||
public static final String YES = "1";
|
||||
public static final String NO = "0";
|
||||
/**
|
||||
* 每页最大显示数
|
||||
*/
|
||||
public static final int MAX_PAGE_SIZE = Configurations.getIntProperty("maxPageSize", 100000);
|
||||
|
||||
/**
|
||||
* 对/错
|
||||
*/
|
||||
public static final String TRUE = "true";
|
||||
public static final String FALSE = "false";
|
||||
/**
|
||||
* 服务器ip
|
||||
*/
|
||||
public static String SERVCER_HOST = null;
|
||||
/**
|
||||
* oracle redis数据 存储时间
|
||||
*/
|
||||
public static final int ORACLE_EXPIRE = Configurations.getIntProperty("oracleExpire", 180);
|
||||
/**
|
||||
* hive redis数据 存储时间
|
||||
*/
|
||||
public static final int HIVE_EXPIRE = Configurations.getIntProperty("hiveExpire", 180);
|
||||
/**
|
||||
* redis开关
|
||||
*/
|
||||
public static final boolean IS_OPEN_REDIS = Configurations.getBooleanProperty("isOpenRedis", false);
|
||||
/**
|
||||
* es开关
|
||||
*/
|
||||
public static final boolean IS_USE_ES = Configurations.getBooleanProperty("isUseES", false);
|
||||
|
||||
/**
|
||||
* 数据中心日志redis开关
|
||||
*/
|
||||
public static final boolean DATACENTER_OPEN_REDIS = Configurations.getBooleanProperty("dataCenterOpenRedis", false);
|
||||
/**
|
||||
* 是否使用use soq_log命令
|
||||
*/
|
||||
// public static final boolean IS_USE_HIVE_DB =
|
||||
// Configurations.getBooleanProperty("isUseHiveDb", true);
|
||||
|
||||
/**
|
||||
* 是否获取数据中心查询记录的总条数
|
||||
*/
|
||||
|
||||
public static final boolean IS_GET_HIVECOUNT = Configurations.getBooleanProperty("isGetHiveCount", true);
|
||||
/**
|
||||
* 是否获取数据中心[神通]查询记录的总条数
|
||||
*/
|
||||
|
||||
public static final boolean IS_SELECT_CLUSTER = Configurations.getBooleanProperty("isSelectCluster", false);
|
||||
|
||||
/**
|
||||
* 神通数据库A的数据最早时间
|
||||
*/
|
||||
public static final Long CLUSTER_A_START_TIME = Configurations.getLongProperty("clusterAStartTime", new Date().getTime());
|
||||
|
||||
/**
|
||||
* 神通数据库B的数据最早时间
|
||||
*/
|
||||
public static final Long CLUSTER_B_START_TIME = Configurations.getLongProperty("clusterBStartTime", new Date().getTime());
|
||||
|
||||
/**
|
||||
* 每次获取数据中心多少条数据,咱们在对获取的数据进行分页处理
|
||||
*/
|
||||
public static final Long EVERY_GETHIVEDATANUM = Configurations.getLongProperty("everyGetHiveDataNum", 10000);
|
||||
|
||||
/**
|
||||
* 是否开启基础校验
|
||||
*/
|
||||
public static final boolean BASE_VALIDATE = Configurations.getBooleanProperty("baseValidate", true);
|
||||
|
||||
public static final Long DATACENTER_TIME = Configurations.getLongProperty("dataCenterTime", 48);
|
||||
|
||||
/**
|
||||
* 是否开启业务校验
|
||||
*/
|
||||
public static final boolean SERVICE_VALIDATE = Configurations.getBooleanProperty("serviceValidate", true);
|
||||
/**
|
||||
* 日志本地存储时间
|
||||
*/
|
||||
public static final Long LOG_LOCAL_TIME = Configurations.getLongProperty("logLocalTime", 48);
|
||||
/**
|
||||
* 实时统计默认时间
|
||||
*/
|
||||
public static final Long REPORT_LOCAL_TIME = Configurations.getLongProperty("reportLocalTime", 1);
|
||||
|
||||
/**
|
||||
* 日志是否从hive中查询
|
||||
*/
|
||||
public static final boolean SEL_FROM_HIVE = Configurations.getBooleanProperty("selFromHive", true);
|
||||
public static final boolean ONLY_SEL_FROM_HIVE = Configurations.getBooleanProperty("onlySelFromHive", true);
|
||||
|
||||
/**
|
||||
* 跨域问题解决,允许跨域的url
|
||||
*/
|
||||
public static final String TARGET_URL = Configurations.getStringProperty("target_url", "*");
|
||||
public static final String ACCESS_CONTROL_MAX_AGE = Configurations.getStringProperty("ACCESS_CONTROL_MAX_AGE",
|
||||
"3600");
|
||||
/**
|
||||
* elasticsearch 检索相关
|
||||
*/
|
||||
public static final String SEARCH_DATEFORMAT = Configurations.getStringProperty("search.dateformat",
|
||||
"yyyy-MM-dd HH:mm:ss");
|
||||
public static final String SEARCH_ES_HOSTANDPORT_A = Configurations.getStringProperty("search.eshostandport_A",
|
||||
null);
|
||||
public static final String SEARCH_ES_HOSTANDPORT_B = Configurations.getStringProperty("search.eshostandport_B",
|
||||
null);
|
||||
public static final String SEARCH_ES_HOSTANDPORT_C = Configurations.getStringProperty("search.eshostandport_C",
|
||||
null);
|
||||
/**
|
||||
* 数据中心A版数据库名称,程序中每次查询时使用的数据库名称 use HIVEADBNAME
|
||||
*/
|
||||
public static final String HIVEADBNAME = Configurations.getStringProperty("jdbc.hive.AName", "xa_dfbhit_hive");
|
||||
/**
|
||||
* 数据中心B版数据库名称,程序中每次查询时使用的数据库名称 use HIVEBDBNAME
|
||||
*/
|
||||
public static final String HIVEBDBNAME = Configurations.getStringProperty("jdbc.hive.BName", "xa_z2_mesalog_hive");
|
||||
|
||||
}
|
||||
257
src/main/java/com/nis/util/Cryptos.java
Normal file
257
src/main/java/com/nis/util/Cryptos.java
Normal file
@@ -0,0 +1,257 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* 支持HMAC-SHA1消息签名 及 DES/AES对称加密的工具类.
|
||||
*
|
||||
* 支持Hex与Base64两种编码方式.
|
||||
*
|
||||
* @author calvin
|
||||
*/
|
||||
public class Cryptos {
|
||||
|
||||
private static final String AES = "AES";
|
||||
private static final String AES_CBC = "AES/CBC/PKCS5Padding";
|
||||
private static final String HMACSHA1 = "HmacSHA1";
|
||||
|
||||
private static final String DEFAULT_URL_ENCODING = "UTF-8";
|
||||
private static final int DEFAULT_HMACSHA1_KEYSIZE = 160; //RFC2401
|
||||
private static final int DEFAULT_AES_KEYSIZE = 128;
|
||||
private static final int DEFAULT_IVSIZE = 16;
|
||||
|
||||
private static final byte[] DEFAULT_KEY = new byte[]{-97,88,-94,9,70,-76,126,25,0,3,-20,113,108,28,69,125};
|
||||
|
||||
private static SecureRandom random = new SecureRandom();
|
||||
|
||||
//-- HMAC-SHA1 funciton --//
|
||||
/**
|
||||
* 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
|
||||
*
|
||||
* @param input 原始输入字符数组
|
||||
* @param key HMAC-SHA1密钥
|
||||
*/
|
||||
public static byte[] hmacSha1(byte[] input, byte[] key) {
|
||||
try {
|
||||
SecretKey secretKey = new SecretKeySpec(key, HMACSHA1);
|
||||
Mac mac = Mac.getInstance(HMACSHA1);
|
||||
mac.init(secretKey);
|
||||
return mac.doFinal(input);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验HMAC-SHA1签名是否正确.
|
||||
*
|
||||
* @param expected 已存在的签名
|
||||
* @param input 原始输入字符串
|
||||
* @param key 密钥
|
||||
*/
|
||||
public static boolean isMacValid(byte[] expected, byte[] input, byte[] key) {
|
||||
byte[] actual = hmacSha1(input, key);
|
||||
return Arrays.equals(expected, actual);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节).
|
||||
* HMAC-SHA1算法对密钥无特殊要求, RFC2401建议最少长度为160位(20字节).
|
||||
*/
|
||||
public static byte[] generateHmacSha1Key() {
|
||||
try {
|
||||
KeyGenerator keyGenerator = KeyGenerator.getInstance(HMACSHA1);
|
||||
keyGenerator.init(DEFAULT_HMACSHA1_KEYSIZE);
|
||||
SecretKey secretKey = keyGenerator.generateKey();
|
||||
return secretKey.getEncoded();
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
//-- AES funciton --//
|
||||
|
||||
/**
|
||||
* 使用AES加密原始字符串.
|
||||
*
|
||||
* @param input 原始输入字符数组
|
||||
*/
|
||||
public static String aesEncrypt(String input) {
|
||||
try {
|
||||
return Encodes.encodeHex(aesEncrypt(input.getBytes(DEFAULT_URL_ENCODING), DEFAULT_KEY));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密原始字符串.
|
||||
*
|
||||
* @param input 原始输入字符数组
|
||||
* @param key 符合AES要求的密钥
|
||||
*/
|
||||
public static String aesEncrypt(String input, String key) {
|
||||
try {
|
||||
return Encodes.encodeHex(aesEncrypt(input.getBytes(DEFAULT_URL_ENCODING), Encodes.decodeHex(key)));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密原始字符串.
|
||||
*
|
||||
* @param input 原始输入字符数组
|
||||
* @param key 符合AES要求的密钥
|
||||
*/
|
||||
public static byte[] aesEncrypt(byte[] input, byte[] key) {
|
||||
return aes(input, key, Cipher.ENCRYPT_MODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密原始字符串.
|
||||
*
|
||||
* @param input 原始输入字符数组
|
||||
* @param key 符合AES要求的密钥
|
||||
* @param iv 初始向量
|
||||
*/
|
||||
public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) {
|
||||
return aes(input, key, iv, Cipher.ENCRYPT_MODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES解密字符串, 返回原始字符串.
|
||||
*
|
||||
* @param input Hex编码的加密字符串
|
||||
*/
|
||||
public static String aesDecrypt(String input) {
|
||||
try {
|
||||
return new String(aesDecrypt(Encodes.decodeHex(input), DEFAULT_KEY), DEFAULT_URL_ENCODING);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES解密字符串, 返回原始字符串.
|
||||
*
|
||||
* @param input Hex编码的加密字符串
|
||||
* @param key 符合AES要求的密钥
|
||||
*/
|
||||
public static String aesDecrypt(String input, String key) {
|
||||
try {
|
||||
return new String(aesDecrypt(Encodes.decodeHex(input), Encodes.decodeHex(key)), DEFAULT_URL_ENCODING);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES解密字符串, 返回原始字符串.
|
||||
*
|
||||
* @param input Hex编码的加密字符串
|
||||
* @param key 符合AES要求的密钥
|
||||
*/
|
||||
public static byte[] aesDecrypt(byte[] input, byte[] key) {
|
||||
return aes(input, key, Cipher.DECRYPT_MODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES解密字符串, 返回原始字符串.
|
||||
*
|
||||
* @param input Hex编码的加密字符串
|
||||
* @param key 符合AES要求的密钥
|
||||
* @param iv 初始向量
|
||||
*/
|
||||
public static byte[] aesDecrypt(byte[] input, byte[] key, byte[] iv) {
|
||||
return aes(input, key, iv, Cipher.DECRYPT_MODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
|
||||
*
|
||||
* @param input 原始字节数组
|
||||
* @param key 符合AES要求的密钥
|
||||
* @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
|
||||
*/
|
||||
private static byte[] aes(byte[] input, byte[] key, int mode) {
|
||||
try {
|
||||
SecretKey secretKey = new SecretKeySpec(key, AES);
|
||||
Cipher cipher = Cipher.getInstance(AES);
|
||||
cipher.init(mode, secretKey);
|
||||
return cipher.doFinal(input);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
|
||||
*
|
||||
* @param input 原始字节数组
|
||||
* @param key 符合AES要求的密钥
|
||||
* @param iv 初始向量
|
||||
* @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
|
||||
*/
|
||||
private static byte[] aes(byte[] input, byte[] key, byte[] iv, int mode) {
|
||||
try {
|
||||
SecretKey secretKey = new SecretKeySpec(key, AES);
|
||||
IvParameterSpec ivSpec = new IvParameterSpec(iv);
|
||||
Cipher cipher = Cipher.getInstance(AES_CBC);
|
||||
cipher.init(mode, secretKey, ivSpec);
|
||||
return cipher.doFinal(input);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
|
||||
*/
|
||||
public static String generateAesKeyString() {
|
||||
return Encodes.encodeHex(generateAesKey(DEFAULT_AES_KEYSIZE));
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
|
||||
*/
|
||||
public static byte[] generateAesKey() {
|
||||
return generateAesKey(DEFAULT_AES_KEYSIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成AES密钥,可选长度为128,192,256位.
|
||||
*/
|
||||
public static byte[] generateAesKey(int keysize) {
|
||||
try {
|
||||
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
|
||||
keyGenerator.init(keysize);
|
||||
SecretKey secretKey = keyGenerator.generateKey();
|
||||
return secretKey.getEncoded();
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机向量,默认大小为cipher.getBlockSize(), 16字节.
|
||||
*/
|
||||
public static byte[] generateIV() {
|
||||
byte[] bytes = new byte[DEFAULT_IVSIZE];
|
||||
random.nextBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
260
src/main/java/com/nis/util/DateUtils.java
Normal file
260
src/main/java/com/nis/util/DateUtils.java
Normal file
@@ -0,0 +1,260 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.time.DateFormatUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
/**
|
||||
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
|
||||
* @author ThinkGem
|
||||
* @version 2014-4-15
|
||||
*/
|
||||
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
|
||||
public static final Logger logger = Logger.getLogger(DateUtils.class);
|
||||
private static String[] parsePatterns = {
|
||||
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
|
||||
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
|
||||
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
|
||||
|
||||
/**
|
||||
* 得到当前日期字符串 格式(yyyy-MM-dd)
|
||||
*/
|
||||
public static String getDate() {
|
||||
return getDate("yyyy-MM-dd");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
|
||||
*/
|
||||
public static String getDate(String pattern) {
|
||||
return DateFormatUtils.format(new Date(), pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
|
||||
*/
|
||||
public static String formatDate(Date date, Object... pattern) {
|
||||
String formatDate = null;
|
||||
if (pattern != null && pattern.length > 0) {
|
||||
formatDate = DateFormatUtils.format(date, pattern[0].toString());
|
||||
} else {
|
||||
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
|
||||
}
|
||||
return formatDate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
|
||||
*/
|
||||
public static String formatDateTime(Date date) {
|
||||
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前时间字符串 格式(HH:mm:ss)
|
||||
*/
|
||||
public static String getTime() {
|
||||
return formatDate(new Date(), "HH:mm:ss");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
|
||||
*/
|
||||
public static String getDateTime() {
|
||||
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前年份字符串 格式(yyyy)
|
||||
*/
|
||||
public static String getYear() {
|
||||
return formatDate(new Date(), "yyyy");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前月份字符串 格式(MM)
|
||||
*/
|
||||
public static String getMonth() {
|
||||
return formatDate(new Date(), "MM");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当天字符串 格式(dd)
|
||||
*/
|
||||
public static String getDay() {
|
||||
return formatDate(new Date(), "dd");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前星期字符串 格式(E)星期几
|
||||
*/
|
||||
public static String getWeek() {
|
||||
return formatDate(new Date(), "E");
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期型字符串转化为日期 格式
|
||||
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
|
||||
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
|
||||
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
|
||||
*/
|
||||
public static Date parseDate(Object str) {
|
||||
if (str == null){
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return parseDate(str.toString(), parsePatterns);
|
||||
} catch (ParseException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取过去的天数
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static long pastDays(Date date) {
|
||||
long t = new Date().getTime()-date.getTime();
|
||||
return t/(24*60*60*1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取过去的小时
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static long pastHour(Date date) {
|
||||
long t = new Date().getTime()-date.getTime();
|
||||
return t/(60*60*1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取过去的分钟
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static long pastMinutes(Date date) {
|
||||
long t = new Date().getTime()-date.getTime();
|
||||
return t/(60*1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为时间(天,时:分:秒.毫秒)
|
||||
* @param timeMillis
|
||||
* @return
|
||||
*/
|
||||
public static String formatDateTime(long timeMillis){
|
||||
long day = timeMillis/(24*60*60*1000);
|
||||
long hour = (timeMillis/(60*60*1000)-day*24);
|
||||
long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
|
||||
long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
|
||||
long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
|
||||
return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取两个日期之间的天数
|
||||
*
|
||||
* @param before
|
||||
* @param after
|
||||
* @return
|
||||
*/
|
||||
public static double getDistanceOfTwoDate(Date before, Date after) {
|
||||
long beforeTime = before.getTime();
|
||||
long afterTime = after.getTime();
|
||||
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
|
||||
}
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @Title: getLocalTime
|
||||
* @Description: (各种业务查询的时间条件默认值)
|
||||
* @param @param startTime
|
||||
* @param @param endTime
|
||||
* @param @param 本地存储时间长度(小时)
|
||||
* @param @return
|
||||
* @return Map 返回类型
|
||||
* @author (DDM)
|
||||
* @version V1.0
|
||||
*/
|
||||
public static Map<String, String> getLocalTime(String startTime,String endTime,Long localLen,String type)throws Exception {
|
||||
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
|
||||
Map<String, String> timeMap=new HashMap<String, String>();
|
||||
Date date=new Date();
|
||||
//日报表默认查询前一天的数据
|
||||
if("daily".equals(type) && startTime == null && endTime == null){
|
||||
Calendar cal=Calendar.getInstance();
|
||||
cal.add(Calendar.DAY_OF_YEAR, -1);
|
||||
cal.set(Calendar.HOUR_OF_DAY, 0);
|
||||
cal.set(Calendar.MINUTE, 0);
|
||||
cal.set(Calendar.SECOND, 0);
|
||||
timeMap.put("startTime", sdf.format(cal.getTime()));
|
||||
timeMap.put("endTime", sdf.format(sdf.parse(sdf2.format(cal.getTime())+" 23:59:59")));
|
||||
logger.info("日报默认开始时间条件:"+sdf.format(cal.getTime()));
|
||||
logger.info("日报默认结束时间条件:"+sdf.format(sdf.parse(sdf2.format(cal.getTime())+" 23:59:59")));
|
||||
return timeMap;
|
||||
}
|
||||
//月报表默认查询前一天的数据
|
||||
if("month".equals(type) && startTime == null && endTime == null){
|
||||
Calendar cal=Calendar.getInstance();
|
||||
cal.add(Calendar.MONTH, date.getMonth()-2);
|
||||
cal.set(Calendar.DAY_OF_MONTH, 1);
|
||||
cal.set(Calendar.HOUR_OF_DAY, 0);
|
||||
cal.set(Calendar.MINUTE, 0);
|
||||
cal.set(Calendar.SECOND, 0);
|
||||
timeMap.put("startTime", sdf.format(cal.getTime()));
|
||||
timeMap.put("endTime", sdf.format(date));
|
||||
logger.info("月报默认开始时间条件:"+sdf.format(cal.getTime()));
|
||||
logger.info("月报默认结束时间条件:"+sdf.format(date));
|
||||
return timeMap;
|
||||
}
|
||||
|
||||
if(startTime == null && endTime == null && localLen != null){
|
||||
Calendar cal=Calendar.getInstance();
|
||||
cal.add(Calendar.HOUR, -localLen.intValue());
|
||||
timeMap.put("startTime", sdf.format(cal.getTime()));
|
||||
timeMap.put("endTime", sdf.format(date));
|
||||
logger.info("默认开始时间条件:"+sdf.format(cal.getTime()));
|
||||
logger.info("默认结束时间条件:"+sdf.format(date));
|
||||
return timeMap;
|
||||
}else {
|
||||
timeMap.put("startTime", startTime);
|
||||
timeMap.put("endTime", endTime);
|
||||
logger.info("开始时间条件:"+startTime);
|
||||
logger.info("结束时间条件:"+endTime);
|
||||
return timeMap;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param args
|
||||
* @throws ParseException
|
||||
*/
|
||||
public static void main(String[] args) throws ParseException {
|
||||
// System.out.println(formatDate(parseDate("2010/3/6")));
|
||||
// System.out.println(getDate("yyyy年MM月dd日 E"));
|
||||
// long time = new Date().getTime()-parseDate("2012-11-19").getTime();
|
||||
// System.out.println(time/(24*60*60*1000));
|
||||
Date date=new Date();
|
||||
Calendar cal=Calendar.getInstance();
|
||||
cal.add(Calendar.MONTH, date.getMonth()-2);
|
||||
cal.set(Calendar.DAY_OF_MONTH, 1);
|
||||
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
//timeMap.put("startTime", sdf.format(cal2.getTime()));
|
||||
//timeMap.put("endTime", sdf.format(cal.getTime()));
|
||||
logger.info("月报默认开始时间条件:"+sdf.format(cal.getTime()));
|
||||
}
|
||||
}
|
||||
146
src/main/java/com/nis/util/DictUtils.java
Normal file
146
src/main/java/com/nis/util/DictUtils.java
Normal file
@@ -0,0 +1,146 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.domain.SysDataDictionaryItem;
|
||||
import com.nis.domain.SysDataDictionaryName;
|
||||
import com.nis.web.dao.SysDictDao;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 系统数据字典工具类
|
||||
* @author Administrator
|
||||
*
|
||||
*/
|
||||
public class DictUtils {
|
||||
|
||||
private final static SysDictDao dictDao = SpringContextHolder.getBean(SysDictDao.class);
|
||||
|
||||
|
||||
public static Map<String, List<SysDataDictionaryItem>> getDictData() {
|
||||
|
||||
Map<String, List<SysDataDictionaryItem>> dictMap = (Map<String, List<SysDataDictionaryItem>>)CacheUtils.get(Constants.CACHE_DICT_MAP);
|
||||
|
||||
if (StringUtil.isEmpty(dictMap)) {
|
||||
dictMap = Maps.newHashMap();
|
||||
List<SysDataDictionaryName> dicList = dictDao.findAllList(new SysDataDictionaryName());
|
||||
for (SysDataDictionaryName dict : dicList) {
|
||||
dictMap.put(dict.getMark(), dict.getDictItemList());
|
||||
}
|
||||
CacheUtils.put(Constants.CACHE_DICT_MAP, dictMap);
|
||||
}
|
||||
|
||||
return dictMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取词典对应key的所有词条,code:value
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Map<String,String> getDictOption(String key) {
|
||||
List<SysDataDictionaryItem> itemList = getDictData().get(key);
|
||||
Map<String, String> itemMap = Maps.newHashMap();
|
||||
for (SysDataDictionaryItem item : itemList) {
|
||||
itemMap.put(item.getItemCode(), item.getItemValue());
|
||||
}
|
||||
|
||||
return itemMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取词典对应key的所有词条,value:code
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Map<String,String> getDictOptionInReversion(String key) {
|
||||
List<SysDataDictionaryItem> itemList = getDictData().get(key);
|
||||
Map<String, String> itemMap = Maps.newHashMap();
|
||||
for (SysDataDictionaryItem item : itemList) {
|
||||
itemMap.put(item.getItemValue(), item.getItemCode());
|
||||
}
|
||||
|
||||
return itemMap;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static List<SysDataDictionaryItem> getDictList(String key){
|
||||
List<SysDataDictionaryItem> itemList = getDictData().get(key);
|
||||
if (StringUtil.isEmpty(itemList)) {
|
||||
itemList = Lists.newArrayList();
|
||||
}
|
||||
return itemList;
|
||||
}
|
||||
|
||||
public static String getDictLabels(String dictKey, String itemCodes, String defaultValue){
|
||||
|
||||
Map<String, String> itemMap = getDictOption(dictKey);
|
||||
|
||||
if (!StringUtil.isEmpty(itemMap)) {
|
||||
List<String> valueList = Lists.newArrayList();
|
||||
for (String itemCode : StringUtils.split(itemCodes, ",")){
|
||||
valueList.add(itemMap.get(itemCode));
|
||||
}
|
||||
return StringUtils.join(valueList, ",");
|
||||
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取字典词条标签
|
||||
* @param value
|
||||
* @param type
|
||||
* @param defaultValue
|
||||
* @return
|
||||
*/
|
||||
public static String getDictLabel(String dictKey, String itemCode, String defaultValue){
|
||||
String itemLabel = getDictOption(dictKey).get(itemCode);
|
||||
|
||||
return StringUtil.isBlank(itemLabel) ? defaultValue : itemLabel;
|
||||
}
|
||||
|
||||
public static String getDictLabel(String dictKey, String itemCode){
|
||||
|
||||
return getDictLabel(dictKey, itemCode, "默认");
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static String getDictCode(String dictKey, String itemValue, String defaultValue){
|
||||
String itemCode = getDictOptionInReversion(dictKey).get(itemValue);
|
||||
|
||||
return StringUtil.isBlank(itemCode) ? defaultValue : itemCode;
|
||||
}
|
||||
|
||||
|
||||
public static String getDictCode(String dictKey, String itemValue){
|
||||
return getDictCode(dictKey, itemValue, "默认");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 返回字典列表(JSON)
|
||||
* @param type
|
||||
* @return
|
||||
*/
|
||||
public static String getDictListJson(String key){
|
||||
return JsonMapper.toJsonString(getDictList(key));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
122
src/main/java/com/nis/util/Digests.java
Normal file
122
src/main/java/com/nis/util/Digests.java
Normal file
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
import org.apache.commons.lang3.Validate;
|
||||
|
||||
|
||||
/**
|
||||
* 支持SHA-1/MD5消息摘要的工具类.
|
||||
*
|
||||
* 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64
|
||||
*
|
||||
* @author calvin
|
||||
*/
|
||||
public class Digests {
|
||||
|
||||
private static final String SHA1 = "SHA-1";
|
||||
private static final String MD5 = "MD5";
|
||||
|
||||
private static SecureRandom random = new SecureRandom();
|
||||
|
||||
/**
|
||||
* 对输入字符串进行md5散列.
|
||||
*/
|
||||
public static byte[] md5(byte[] input) {
|
||||
return digest(input, MD5, null, 1);
|
||||
}
|
||||
public static byte[] md5(byte[] input, int iterations) {
|
||||
return digest(input, MD5, null, iterations);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对输入字符串进行sha1散列.
|
||||
*/
|
||||
public static byte[] sha1(byte[] input) {
|
||||
return digest(input, SHA1, null, 1);
|
||||
}
|
||||
|
||||
public static byte[] sha1(byte[] input, byte[] salt) {
|
||||
return digest(input, SHA1, salt, 1);
|
||||
}
|
||||
|
||||
public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
|
||||
return digest(input, SHA1, salt, iterations);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对字符串进行散列, 支持md5与sha1算法.
|
||||
*/
|
||||
private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance(algorithm);
|
||||
|
||||
if (salt != null) {
|
||||
digest.update(salt);
|
||||
}
|
||||
|
||||
byte[] result = digest.digest(input);
|
||||
|
||||
for (int i = 1; i < iterations; i++) {
|
||||
digest.reset();
|
||||
result = digest.digest(result);
|
||||
}
|
||||
return result;
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机的Byte[]作为salt.
|
||||
*
|
||||
* @param numBytes byte数组的大小
|
||||
*/
|
||||
public static byte[] generateSalt(int numBytes) {
|
||||
Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
|
||||
|
||||
byte[] bytes = new byte[numBytes];
|
||||
random.nextBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对文件进行md5散列.
|
||||
*/
|
||||
public static byte[] md5(InputStream input) throws IOException {
|
||||
return digest(input, MD5);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对文件进行sha1散列.
|
||||
*/
|
||||
public static byte[] sha1(InputStream input) throws IOException {
|
||||
return digest(input, SHA1);
|
||||
}
|
||||
|
||||
private static byte[] digest(InputStream input, String algorithm) throws IOException {
|
||||
try {
|
||||
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
|
||||
int bufferLength = 8 * 1024;
|
||||
byte[] buffer = new byte[bufferLength];
|
||||
int read = input.read(buffer, 0, bufferLength);
|
||||
|
||||
while (read > -1) {
|
||||
messageDigest.update(buffer, 0, read);
|
||||
read = input.read(buffer, 0, bufferLength);
|
||||
}
|
||||
|
||||
return messageDigest.digest();
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
151
src/main/java/com/nis/util/Encodes.java
Normal file
151
src/main/java/com/nis/util/Encodes.java
Normal file
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
import org.apache.commons.lang3.StringEscapeUtils;
|
||||
|
||||
/**
|
||||
* 封装各种格式的编码解码工具类.
|
||||
* 1.Commons-Codec的 hex/base64 编码
|
||||
* 2.自制的base62 编码
|
||||
* 3.Commons-Lang的xml/html escape
|
||||
* 4.JDK提供的URLEncoder
|
||||
* @author calvin
|
||||
* @version 2013-01-15
|
||||
*/
|
||||
public class Encodes {
|
||||
|
||||
private static final String DEFAULT_URL_ENCODING = "UTF-8";
|
||||
private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
|
||||
|
||||
/**
|
||||
* Hex编码.
|
||||
*/
|
||||
public static String encodeHex(byte[] input) {
|
||||
return new String(Hex.encodeHex(input));
|
||||
}
|
||||
|
||||
/**
|
||||
* Hex解码.
|
||||
*/
|
||||
public static byte[] decodeHex(String input) {
|
||||
try {
|
||||
return Hex.decodeHex(input.toCharArray());
|
||||
} catch (DecoderException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64编码.
|
||||
*/
|
||||
public static String encodeBase64(byte[] input) {
|
||||
return new String(Base64.encodeBase64(input));
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64编码.
|
||||
*/
|
||||
public static String encodeBase64(String input) {
|
||||
try {
|
||||
return new String(Base64.encodeBase64(input.getBytes(DEFAULT_URL_ENCODING)));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
|
||||
// */
|
||||
// public static String encodeUrlSafeBase64(byte[] input) {
|
||||
// return Base64.encodeBase64URLSafe(input);
|
||||
// }
|
||||
|
||||
/**
|
||||
* Base64解码.
|
||||
*/
|
||||
public static byte[] decodeBase64(String input) {
|
||||
return Base64.decodeBase64(input.getBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64解码.
|
||||
*/
|
||||
public static String decodeBase64String(String input) {
|
||||
try {
|
||||
return new String(Base64.decodeBase64(input.getBytes()), DEFAULT_URL_ENCODING);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Base62编码。
|
||||
*/
|
||||
public static String encodeBase62(byte[] input) {
|
||||
char[] chars = new char[input.length];
|
||||
for (int i = 0; i < input.length; i++) {
|
||||
chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];
|
||||
}
|
||||
return new String(chars);
|
||||
}
|
||||
|
||||
/**
|
||||
* Html 转码.
|
||||
*/
|
||||
public static String escapeHtml(String html) {
|
||||
return StringEscapeUtils.escapeHtml4(html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Html 解码.
|
||||
*/
|
||||
public static String unescapeHtml(String htmlEscaped) {
|
||||
return StringEscapeUtils.unescapeHtml4(htmlEscaped);
|
||||
}
|
||||
|
||||
/**
|
||||
* Xml 转码.
|
||||
*/
|
||||
public static String escapeXml(String xml) {
|
||||
return StringEscapeUtils.escapeXml10(xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* Xml 解码.
|
||||
*/
|
||||
public static String unescapeXml(String xmlEscaped) {
|
||||
return StringEscapeUtils.unescapeXml(xmlEscaped);
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 编码, Encode默认为UTF-8.
|
||||
*/
|
||||
public static String urlEncode(String part) {
|
||||
try {
|
||||
return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 解码, Encode默认为UTF-8.
|
||||
*/
|
||||
public static String urlDecode(String part) {
|
||||
|
||||
try {
|
||||
return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
72
src/main/java/com/nis/util/Exceptions.java
Normal file
72
src/main/java/com/nis/util/Exceptions.java
Normal file
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 关于异常的工具类.
|
||||
* @author calvin
|
||||
* @version 2013-01-15
|
||||
*/
|
||||
public class Exceptions {
|
||||
|
||||
/**
|
||||
* 将CheckedException转换为UncheckedException.
|
||||
*/
|
||||
public static RuntimeException unchecked(Exception e) {
|
||||
if (e instanceof RuntimeException) {
|
||||
return (RuntimeException) e;
|
||||
} else {
|
||||
return new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将ErrorStack转化为String.
|
||||
*/
|
||||
public static String getStackTraceAsString(Throwable e) {
|
||||
if (e == null){
|
||||
return "";
|
||||
}
|
||||
StringWriter stringWriter = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(stringWriter));
|
||||
return stringWriter.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断异常是否由某些底层的异常引起.
|
||||
*/
|
||||
public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
|
||||
Throwable cause = ex.getCause();
|
||||
while (cause != null) {
|
||||
for (Class<? extends Exception> causeClass : causeExceptionClasses) {
|
||||
if (causeClass.isInstance(cause)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
cause = cause.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在request中获取异常类
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public static Throwable getThrowable(HttpServletRequest request){
|
||||
Throwable ex = null;
|
||||
if (request.getAttribute("exception") != null) {
|
||||
ex = (Throwable) request.getAttribute("exception");
|
||||
} else if (request.getAttribute("javax.servlet.error.exception") != null) {
|
||||
ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
|
||||
}
|
||||
return ex;
|
||||
}
|
||||
|
||||
}
|
||||
731
src/main/java/com/nis/util/FileUtils.java
Normal file
731
src/main/java/com/nis/util/FileUtils.java
Normal file
@@ -0,0 +1,731 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Enumeration;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.tools.zip.ZipEntry;
|
||||
import org.apache.tools.zip.ZipFile;
|
||||
import org.apache.tools.zip.ZipOutputStream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.nis.web.security.Servlets;
|
||||
|
||||
/**
|
||||
* 文件操作工具类 实现文件的创建、删除、复制、压缩、解压以及目录的创建、删除、复制、压缩解压等功能
|
||||
*
|
||||
* @author ThinkGem
|
||||
* @version 2013-06-21
|
||||
*/
|
||||
public class FileUtils extends org.apache.commons.io.FileUtils {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(FileUtils.class);
|
||||
|
||||
/**
|
||||
* 复制单个文件,如果目标文件存在,则不覆盖
|
||||
*
|
||||
* @param srcFileName
|
||||
* 待复制的文件名
|
||||
* @param descFileName
|
||||
* 目标文件名
|
||||
* @return 如果复制成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean copyFile(String srcFileName, String descFileName) {
|
||||
return FileUtils.copyFileCover(srcFileName, descFileName, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制单个文件
|
||||
*
|
||||
* @param srcFileName
|
||||
* 待复制的文件名
|
||||
* @param descFileName
|
||||
* 目标文件名
|
||||
* @param coverlay
|
||||
* 如果目标文件已存在,是否覆盖
|
||||
* @return 如果复制成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) {
|
||||
File srcFile = new File(srcFileName);
|
||||
// 判断源文件是否存在
|
||||
if (!srcFile.exists()) {
|
||||
log.debug("复制文件失败,源文件 " + srcFileName + " 不存在!");
|
||||
return false;
|
||||
}
|
||||
// 判断源文件是否是合法的文件
|
||||
else if (!srcFile.isFile()) {
|
||||
log.debug("复制文件失败," + srcFileName + " 不是一个文件!");
|
||||
return false;
|
||||
}
|
||||
File descFile = new File(descFileName);
|
||||
// 判断目标文件是否存在
|
||||
if (descFile.exists()) {
|
||||
// 如果目标文件存在,并且允许覆盖
|
||||
if (coverlay) {
|
||||
log.debug("目标文件已存在,准备删除!");
|
||||
if (!FileUtils.delFile(descFileName)) {
|
||||
log.debug("删除目标文件 " + descFileName + " 失败!");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
log.debug("复制文件失败,目标文件 " + descFileName + " 已存在!");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (!descFile.getParentFile().exists()) {
|
||||
// 如果目标文件所在的目录不存在,则创建目录
|
||||
log.debug("目标文件所在的目录不存在,创建目录!");
|
||||
// 创建目标文件所在的目录
|
||||
if (!descFile.getParentFile().mkdirs()) {
|
||||
log.debug("创建目标文件所在的目录失败!");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 准备复制文件
|
||||
// 读取的位数
|
||||
int readByte = 0;
|
||||
InputStream ins = null;
|
||||
OutputStream outs = null;
|
||||
try {
|
||||
// 打开源文件
|
||||
ins = new FileInputStream(srcFile);
|
||||
// 打开目标文件的输出流
|
||||
outs = new FileOutputStream(descFile);
|
||||
byte[] buf = new byte[1024];
|
||||
// 一次读取1024个字节,当readByte为-1时表示文件已经读取完毕
|
||||
while ((readByte = ins.read(buf)) != -1) {
|
||||
// 将读取的字节流写入到输出流
|
||||
outs.write(buf, 0, readByte);
|
||||
}
|
||||
log.debug("复制单个文件 " + srcFileName + " 到" + descFileName + "成功!");
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.debug("复制文件失败:" + e.getMessage());
|
||||
return false;
|
||||
} finally {
|
||||
// 关闭输入输出流,首先关闭输出流,然后再关闭输入流
|
||||
if (outs != null) {
|
||||
try {
|
||||
outs.close();
|
||||
} catch (IOException oute) {
|
||||
oute.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (ins != null) {
|
||||
try {
|
||||
ins.close();
|
||||
} catch (IOException ine) {
|
||||
ine.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制整个目录的内容,如果目标目录存在,则不覆盖
|
||||
*
|
||||
* @param srcDirName
|
||||
* 源目录名
|
||||
* @param descDirName
|
||||
* 目标目录名
|
||||
* @return 如果复制成功返回true,否则返回false
|
||||
*/
|
||||
public static boolean copyDirectory(String srcDirName, String descDirName) {
|
||||
return FileUtils.copyDirectoryCover(srcDirName, descDirName, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制整个目录的内容
|
||||
*
|
||||
* @param srcDirName
|
||||
* 源目录名
|
||||
* @param descDirName
|
||||
* 目标目录名
|
||||
* @param coverlay
|
||||
* 如果目标目录存在,是否覆盖
|
||||
* @return 如果复制成功返回true,否则返回false
|
||||
*/
|
||||
public static boolean copyDirectoryCover(String srcDirName, String descDirName, boolean coverlay) {
|
||||
File srcDir = new File(srcDirName);
|
||||
// 判断源目录是否存在
|
||||
if (!srcDir.exists()) {
|
||||
log.debug("复制目录失败,源目录 " + srcDirName + " 不存在!");
|
||||
return false;
|
||||
}
|
||||
// 判断源目录是否是目录
|
||||
else if (!srcDir.isDirectory()) {
|
||||
log.debug("复制目录失败," + srcDirName + " 不是一个目录!");
|
||||
return false;
|
||||
}
|
||||
// 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符
|
||||
String descDirNames = descDirName;
|
||||
if (!descDirNames.endsWith(File.separator)) {
|
||||
descDirNames = descDirNames + File.separator;
|
||||
}
|
||||
File descDir = new File(descDirNames);
|
||||
// 如果目标文件夹存在
|
||||
if (descDir.exists()) {
|
||||
if (coverlay) {
|
||||
// 允许覆盖目标目录
|
||||
log.debug("目标目录已存在,准备删除!");
|
||||
if (!FileUtils.delFile(descDirNames)) {
|
||||
log.debug("删除目录 " + descDirNames + " 失败!");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
log.debug("目标目录复制失败,目标目录 " + descDirNames + " 已存在!");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// 创建目标目录
|
||||
log.debug("目标目录不存在,准备创建!");
|
||||
if (!descDir.mkdirs()) {
|
||||
log.debug("创建目标目录失败!");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
boolean flag = true;
|
||||
// 列出源目录下的所有文件名和子目录名
|
||||
File[] files = srcDir.listFiles();
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
// 如果是一个单个文件,则直接复制
|
||||
if (files[i].isFile()) {
|
||||
flag = FileUtils.copyFile(files[i].getAbsolutePath(), descDirName + files[i].getName());
|
||||
// 如果拷贝文件失败,则退出循环
|
||||
if (!flag) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 如果是子目录,则继续复制目录
|
||||
if (files[i].isDirectory()) {
|
||||
flag = FileUtils.copyDirectory(files[i].getAbsolutePath(), descDirName + files[i].getName());
|
||||
// 如果拷贝目录失败,则退出循环
|
||||
if (!flag) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!flag) {
|
||||
log.debug("复制目录 " + srcDirName + " 到 " + descDirName + " 失败!");
|
||||
return false;
|
||||
}
|
||||
log.debug("复制目录 " + srcDirName + " 到 " + descDirName + " 成功!");
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 删除文件,可以删除单个文件或文件夹
|
||||
*
|
||||
* @param fileName
|
||||
* 被删除的文件名
|
||||
* @return 如果删除成功,则返回true,否是返回false
|
||||
*/
|
||||
public static boolean delFile(String fileName) {
|
||||
File file = new File(fileName);
|
||||
if (!file.exists()) {
|
||||
log.debug(fileName + " 文件不存在!");
|
||||
return true;
|
||||
} else {
|
||||
if (file.isFile()) {
|
||||
return FileUtils.deleteFile(fileName);
|
||||
} else {
|
||||
return FileUtils.deleteDirectory(fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 删除单个文件
|
||||
*
|
||||
* @param fileName
|
||||
* 被删除的文件名
|
||||
* @return 如果删除成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean deleteFile(String fileName) {
|
||||
File file = new File(fileName);
|
||||
if (file.exists() && file.isFile()) {
|
||||
if (file.delete()) {
|
||||
log.debug("删除文件 " + fileName + " 成功!");
|
||||
return true;
|
||||
} else {
|
||||
log.debug("删除文件 " + fileName + " 失败!");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
log.debug(fileName + " 文件不存在!");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 删除目录及目录下的文件
|
||||
*
|
||||
* @param dirName
|
||||
* 被删除的目录所在的文件路径
|
||||
* @return 如果目录删除成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean deleteDirectory(String dirName) {
|
||||
String dirNames = dirName;
|
||||
if (!dirNames.endsWith(File.separator)) {
|
||||
dirNames = dirNames + File.separator;
|
||||
}
|
||||
File dirFile = new File(dirNames);
|
||||
if (!dirFile.exists() || !dirFile.isDirectory()) {
|
||||
log.debug(dirNames + " 目录不存在!");
|
||||
return true;
|
||||
}
|
||||
boolean flag = true;
|
||||
// 列出全部文件及子目录
|
||||
File[] files = dirFile.listFiles();
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
// 删除子文件
|
||||
if (files[i].isFile()) {
|
||||
flag = FileUtils.deleteFile(files[i].getAbsolutePath());
|
||||
// 如果删除文件失败,则退出循环
|
||||
if (!flag) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 删除子目录
|
||||
else if (files[i].isDirectory()) {
|
||||
flag = FileUtils.deleteDirectory(files[i].getAbsolutePath());
|
||||
// 如果删除子目录失败,则退出循环
|
||||
if (!flag) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!flag) {
|
||||
log.debug("删除目录失败!");
|
||||
return false;
|
||||
}
|
||||
// 删除当前目录
|
||||
if (dirFile.delete()) {
|
||||
log.debug("删除目录 " + dirName + " 成功!");
|
||||
return true;
|
||||
} else {
|
||||
log.debug("删除目录 " + dirName + " 失败!");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建单个文件
|
||||
*
|
||||
* @param descFileName
|
||||
* 文件名,包含路径
|
||||
* @return 如果创建成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean createFile(String descFileName) {
|
||||
File file = new File(descFileName);
|
||||
if (file.exists()) {
|
||||
log.debug("文件 " + descFileName + " 已存在!");
|
||||
return false;
|
||||
}
|
||||
if (descFileName.endsWith(File.separator)) {
|
||||
log.debug(descFileName + " 为目录,不能创建目录!");
|
||||
return false;
|
||||
}
|
||||
if (!file.getParentFile().exists()) {
|
||||
// 如果文件所在的目录不存在,则创建目录
|
||||
if (!file.getParentFile().mkdirs()) {
|
||||
log.debug("创建文件所在的目录失败!");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 创建文件
|
||||
try {
|
||||
if (file.createNewFile()) {
|
||||
log.debug(descFileName + " 文件创建成功!");
|
||||
return true;
|
||||
} else {
|
||||
log.debug(descFileName + " 文件创建失败!");
|
||||
return false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
log.debug(descFileName + " 文件创建失败!");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建目录
|
||||
*
|
||||
* @param descDirName
|
||||
* 目录名,包含路径
|
||||
* @return 如果创建成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean createDirectory(String descDirName) {
|
||||
String descDirNames = descDirName;
|
||||
if (!descDirNames.endsWith(File.separator)) {
|
||||
descDirNames = descDirNames + File.separator;
|
||||
}
|
||||
File descDir = new File(descDirNames);
|
||||
if (descDir.exists()) {
|
||||
log.debug("目录 " + descDirNames + " 已存在!");
|
||||
return false;
|
||||
}
|
||||
// 创建目录
|
||||
if (descDir.mkdirs()) {
|
||||
log.debug("目录 " + descDirNames + " 创建成功!");
|
||||
return true;
|
||||
} else {
|
||||
log.debug("目录 " + descDirNames + " 创建失败!");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入文件
|
||||
*
|
||||
* @param file
|
||||
* 要写入的文件
|
||||
*/
|
||||
public static void writeToFile(String fileName, String content, boolean append) {
|
||||
try {
|
||||
FileUtils.write(new File(fileName), content, "utf-8", append);
|
||||
log.debug("文件 " + fileName + " 写入成功!");
|
||||
} catch (IOException e) {
|
||||
log.debug("文件 " + fileName + " 写入失败! " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入文件
|
||||
*
|
||||
* @param file
|
||||
* 要写入的文件
|
||||
*/
|
||||
public static void writeToFile(String fileName, String content, String encoding, boolean append) {
|
||||
try {
|
||||
FileUtils.write(new File(fileName), content, encoding, append);
|
||||
log.debug("文件 " + fileName + " 写入成功!");
|
||||
} catch (IOException e) {
|
||||
log.debug("文件 " + fileName + " 写入失败! " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 压缩文件或目录
|
||||
*
|
||||
* @param srcDirName
|
||||
* 压缩的根目录
|
||||
* @param fileName
|
||||
* 根目录下的待压缩的文件名或文件夹名,其中*或""表示跟目录下的全部文件
|
||||
* @param descFileName
|
||||
* 目标zip文件
|
||||
*/
|
||||
public static void zipFiles(String srcDirName, String fileName, String descFileName) {
|
||||
// 判断目录是否存在
|
||||
if (srcDirName == null) {
|
||||
log.debug("文件压缩失败,目录 " + srcDirName + " 不存在!");
|
||||
return;
|
||||
}
|
||||
File fileDir = new File(srcDirName);
|
||||
if (!fileDir.exists() || !fileDir.isDirectory()) {
|
||||
log.debug("文件压缩失败,目录 " + srcDirName + " 不存在!");
|
||||
return;
|
||||
}
|
||||
String dirPath = fileDir.getAbsolutePath();
|
||||
File descFile = new File(descFileName);
|
||||
try {
|
||||
ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(descFile));
|
||||
if ("*".equals(fileName) || "".equals(fileName)) {
|
||||
FileUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts);
|
||||
} else {
|
||||
File file = new File(fileDir, fileName);
|
||||
if (file.isFile()) {
|
||||
FileUtils.zipFilesToZipFile(dirPath, file, zouts);
|
||||
} else {
|
||||
FileUtils.zipDirectoryToZipFile(dirPath, file, zouts);
|
||||
}
|
||||
}
|
||||
zouts.close();
|
||||
log.debug(descFileName + " 文件压缩成功!");
|
||||
} catch (Exception e) {
|
||||
log.debug("文件压缩失败:" + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 解压缩ZIP文件,将ZIP文件里的内容解压到descFileName目录下
|
||||
*
|
||||
* @param zipFileName
|
||||
* 需要解压的ZIP文件
|
||||
* @param descFileName
|
||||
* 目标文件
|
||||
*/
|
||||
public static boolean unZipFiles(String zipFileName, String descFileName) {
|
||||
String descFileNames = descFileName;
|
||||
if (!descFileNames.endsWith(File.separator)) {
|
||||
descFileNames = descFileNames + File.separator;
|
||||
}
|
||||
try {
|
||||
// 根据ZIP文件创建ZipFile对象
|
||||
ZipFile zipFile = new ZipFile(zipFileName);
|
||||
ZipEntry entry = null;
|
||||
String entryName = null;
|
||||
String descFileDir = null;
|
||||
byte[] buf = new byte[4096];
|
||||
int readByte = 0;
|
||||
// 获取ZIP文件里所有的entry
|
||||
@SuppressWarnings("rawtypes")
|
||||
Enumeration enums = zipFile.getEntries();
|
||||
// 遍历所有entry
|
||||
while (enums.hasMoreElements()) {
|
||||
entry = (ZipEntry) enums.nextElement();
|
||||
// 获得entry的名字
|
||||
entryName = entry.getName();
|
||||
descFileDir = descFileNames + entryName;
|
||||
if (entry.isDirectory()) {
|
||||
// 如果entry是一个目录,则创建目录
|
||||
new File(descFileDir).mkdirs();
|
||||
continue;
|
||||
} else {
|
||||
// 如果entry是一个文件,则创建父目录
|
||||
new File(descFileDir).getParentFile().mkdirs();
|
||||
}
|
||||
File file = new File(descFileDir);
|
||||
// 打开文件输出流
|
||||
OutputStream os = new FileOutputStream(file);
|
||||
// 从ZipFile对象中打开entry的输入流
|
||||
InputStream is = zipFile.getInputStream(entry);
|
||||
while ((readByte = is.read(buf)) != -1) {
|
||||
os.write(buf, 0, readByte);
|
||||
}
|
||||
os.close();
|
||||
is.close();
|
||||
}
|
||||
zipFile.close();
|
||||
log.debug("文件解压成功!");
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.debug("文件解压失败:" + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将目录压缩到ZIP输出流
|
||||
*
|
||||
* @param dirPath
|
||||
* 目录路径
|
||||
* @param fileDir
|
||||
* 文件信息
|
||||
* @param zouts
|
||||
* 输出流
|
||||
*/
|
||||
public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) {
|
||||
if (fileDir.isDirectory()) {
|
||||
File[] files = fileDir.listFiles();
|
||||
// 空的文件夹
|
||||
if (files.length == 0) {
|
||||
// 目录信息
|
||||
ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir));
|
||||
try {
|
||||
zouts.putNextEntry(entry);
|
||||
zouts.closeEntry();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
if (files[i].isFile()) {
|
||||
// 如果是文件,则调用文件压缩方法
|
||||
FileUtils.zipFilesToZipFile(dirPath, files[i], zouts);
|
||||
} else {
|
||||
// 如果是目录,则递归调用
|
||||
FileUtils.zipDirectoryToZipFile(dirPath, files[i], zouts);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 将文件压缩到ZIP输出流
|
||||
*
|
||||
* @param dirPath
|
||||
* 目录路径
|
||||
* @param file
|
||||
* 文件
|
||||
* @param zouts
|
||||
* 输出流
|
||||
*/
|
||||
public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) {
|
||||
FileInputStream fin = null;
|
||||
ZipEntry entry = null;
|
||||
// 创建复制缓冲区
|
||||
byte[] buf = new byte[4096];
|
||||
int readByte = 0;
|
||||
if (file.isFile()) {
|
||||
try {
|
||||
// 创建一个文件输入流
|
||||
fin = new FileInputStream(file);
|
||||
// 创建一个ZipEntry
|
||||
entry = new ZipEntry(getEntryName(dirPath, file));
|
||||
// 存储信息到压缩文件
|
||||
zouts.putNextEntry(entry);
|
||||
// 复制字节到压缩文件
|
||||
while ((readByte = fin.read(buf)) != -1) {
|
||||
zouts.write(buf, 0, readByte);
|
||||
}
|
||||
zouts.closeEntry();
|
||||
fin.close();
|
||||
System.out.println("添加文件 " + file.getAbsolutePath() + " 到zip文件中!");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取待压缩文件在ZIP文件中entry的名字,即相对于跟目录的相对路径名
|
||||
*
|
||||
* @param dirPat
|
||||
* 目录名
|
||||
* @param file
|
||||
* entry文件名
|
||||
* @return
|
||||
*/
|
||||
private static String getEntryName(String dirPath, File file) {
|
||||
String dirPaths = dirPath;
|
||||
if (!dirPaths.endsWith(File.separator)) {
|
||||
dirPaths = dirPaths + File.separator;
|
||||
}
|
||||
String filePath = file.getAbsolutePath();
|
||||
// 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储
|
||||
if (file.isDirectory()) {
|
||||
filePath += "/";
|
||||
}
|
||||
int index = filePath.indexOf(dirPaths);
|
||||
|
||||
return filePath.substring(index + dirPaths.length());
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复路径,将 \\ 或 / 等替换为 File.separator
|
||||
*
|
||||
* @param path
|
||||
* @return
|
||||
*/
|
||||
public static String path(String path) {
|
||||
String p = StringUtils.replace(path, "\\", "/");
|
||||
// p = StringUtils.join(StringUtils.split(p, "/"), "/");
|
||||
if (!StringUtils.startsWithAny(p, "/") && StringUtils.startsWithAny(path, "\\", "/")) {
|
||||
p += "/";
|
||||
}
|
||||
if (!StringUtils.endsWithAny(p, "/") && StringUtils.endsWithAny(path, "\\", "/")) {
|
||||
p = p + "/";
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件唯一名称
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static String getFileKey() {
|
||||
String suffixName = DateUtils.getDate("hhmmss");
|
||||
return StringUtil.createUUID() + suffixName;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取文件后缀
|
||||
*
|
||||
* @param filename
|
||||
* @param isDot
|
||||
* true:加“.”
|
||||
* @return
|
||||
*/
|
||||
public static String getSuffix(String filename, Boolean isDot) {
|
||||
String suffix = "";
|
||||
int pos = filename.lastIndexOf('.');
|
||||
if (pos > 0 && pos < filename.length() - 1) {
|
||||
if (!isDot) {
|
||||
pos = pos + 1;
|
||||
}
|
||||
suffix = filename.substring(pos);
|
||||
}
|
||||
return suffix;
|
||||
}
|
||||
|
||||
// 文件下载
|
||||
public static void fileDownload(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
String filename,
|
||||
String filepath) throws IOException{
|
||||
FileInputStream in = null;
|
||||
ServletOutputStream out = null;
|
||||
try {
|
||||
String path = FileUtils.path(Servlets.getRequest().getServletContext().getRealPath(filepath));
|
||||
File src = new File(path);
|
||||
in = new FileInputStream(src);
|
||||
response.reset();
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
|
||||
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
|
||||
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
|
||||
}
|
||||
// IE
|
||||
else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0
|
||||
|| request.getHeader("User-Agent").toUpperCase().indexOf("LIKE GECKO") > 0) {
|
||||
filename = URLEncoder.encode(filename, "UTF-8");
|
||||
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
|
||||
}
|
||||
out = response.getOutputStream();
|
||||
byte[] buffer = new byte[1024];
|
||||
int len = 0;
|
||||
while ((len = in.read(buffer, 0, 1024)) != -1) {
|
||||
out.write(buffer, 0, len);
|
||||
}
|
||||
out.flush();
|
||||
} finally {
|
||||
if (in != null) {
|
||||
in.close();
|
||||
in=null;
|
||||
}
|
||||
if (out != null) {
|
||||
out.close();
|
||||
out=null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
79
src/main/java/com/nis/util/FormatUtils.java
Normal file
79
src/main/java/com/nis/util/FormatUtils.java
Normal file
@@ -0,0 +1,79 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
public class FormatUtils {
|
||||
|
||||
/**
|
||||
* 将List<HashMap<String,Object>>中HashMap的key全部转化为变量形式,<br>
|
||||
* 如{"BRH_ID":"1234","BRH_NAME":"机构"}改为{"brhId":"1234","brhName":"机构"}
|
||||
*
|
||||
* @param list
|
||||
* @return
|
||||
*/
|
||||
public static List<HashMap<String, Object>> formatHashMapKeyInList(
|
||||
List<HashMap<String, Object>> list) {
|
||||
List result = new ArrayList();
|
||||
// 遍历list后进行格式化列表元素
|
||||
if (list!=null){
|
||||
for (HashMap<String, Object> h : list) {
|
||||
// 将hashMap的key转化为驼峰格式,如{"BRH_ID":"1234"}改为{"brhId":"1234"}
|
||||
result.add(formatHashMapKey(h));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将hashMap的key转化为驼峰格式,如{"BRH_ID":"1234","BRH_NAME":"机构"}改为{"brhId":"1234",
|
||||
* "brhName":"机构"}
|
||||
*
|
||||
* @param hashMap
|
||||
* @return
|
||||
*/
|
||||
public static HashMap<String, Object> formatHashMapKey(
|
||||
HashMap<String, Object> hashMap) {
|
||||
HashMap result = new HashMap();
|
||||
String key = null;
|
||||
// 遍历map
|
||||
for (Entry<String, Object> e : (Set<Entry<String, Object>>) hashMap.entrySet()) {
|
||||
key = (String) e.getKey();
|
||||
// 将hashMap的key转化为驼峰格式
|
||||
key = formatDBNameToVarName(key);
|
||||
// 封装为新的map
|
||||
result.put(key, e.getValue());
|
||||
}
|
||||
// 返回格式化后的map
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库列名转化为属性名,如DEAL_ID=dealId; <br>
|
||||
* 不能保证完全正确,如DBUTIL不会智能的转化为DBUtil,而会转化为dbutil, <br>
|
||||
* 规则为全部转化为单词,然后首字母小写
|
||||
*
|
||||
* @param DBName
|
||||
* @return
|
||||
*/
|
||||
public static String formatDBNameToVarName(String DBName) {
|
||||
StringBuilder result = new StringBuilder("");
|
||||
// 以"_"分割
|
||||
String[] DBNameArr = DBName.split("_");
|
||||
for (int i = 0, j = DBNameArr.length; i < j; i++) {
|
||||
// 获取以"_"分割后的字符数组的每个元素的第一个字母,
|
||||
result.append(DBNameArr[i].charAt(0));
|
||||
// 将其他字符转换成小写
|
||||
result.append(DBNameArr[i].substring(1).toLowerCase());
|
||||
}
|
||||
char c0 = result.charAt(0);
|
||||
if (c0 >= 'A' && c0 <= 'Z')
|
||||
c0 = (char) (c0 + 'a' - 'A');
|
||||
result.setCharAt(0, c0);
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
}
|
||||
57
src/main/java/com/nis/util/HiveDataSource.java
Normal file
57
src/main/java/com/nis/util/HiveDataSource.java
Normal file
@@ -0,0 +1,57 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
import com.jolbox.bonecp.BoneCPDataSource;
|
||||
|
||||
public class HiveDataSource {
|
||||
private final static Logger logger = Logger.getLogger(HiveDataSource.class);
|
||||
static Connection conn = null;
|
||||
static ResultSet rsA = null;
|
||||
static Statement stA = null;
|
||||
|
||||
static ResultSet rsB = null;
|
||||
static Statement stB = null;
|
||||
|
||||
public static ResultSet query(String sql, String searchActiveSys) throws Exception {
|
||||
if (null != searchActiveSys && searchActiveSys.equals("4")) {// A版数据库
|
||||
logger.info("开始连接数据中心A版日志库--------------------------");
|
||||
if (conn == null || conn.isClosed()) {
|
||||
ApplicationContext ct = new ClassPathXmlApplicationContext("applicationContext-mybatis.xml");
|
||||
BoneCPDataSource datasource = (BoneCPDataSource) ct.getBean("HiveADataSource");
|
||||
conn = datasource.getConnection();
|
||||
}
|
||||
logger.info("连接数据中心A版日志库成功--------------------------");
|
||||
stA = conn.createStatement();
|
||||
String hiveAName = "use " + Constants.HIVEADBNAME;
|
||||
// stA.execute("use xa_dfbhit_p_hive");
|
||||
stA.execute(hiveAName);
|
||||
logger.info("开始执行查询数据中心A版日志库操作--------------------------" + sql);
|
||||
rsA = stA.executeQuery(sql);
|
||||
logger.info("执行查询数据中心A版日志库成功--------------------------");
|
||||
return rsA;
|
||||
} else {// 目前默认B版数据库,后期增加C版数据库
|
||||
logger.info("开始连接数据中心B版日志库--------------------------");
|
||||
if (conn == null || conn.isClosed()) {
|
||||
ApplicationContext ct = new ClassPathXmlApplicationContext("applicationContext-mybatis.xml");
|
||||
BoneCPDataSource datasource = (BoneCPDataSource) ct.getBean("HiveBDataSource");
|
||||
conn = datasource.getConnection();
|
||||
}
|
||||
logger.info("连接数据中心B版日志库成功--------------------------");
|
||||
stB = conn.createStatement();
|
||||
String hiveBName = "use " + Constants.HIVEBDBNAME;
|
||||
// stB.execute("use xa_z2_mesalog_hive");
|
||||
stB.execute(hiveBName);
|
||||
logger.info("开始执行查询数据中心B版日志库操作--------------------------" + sql);
|
||||
rsB = stB.executeQuery(sql);
|
||||
logger.info("执行查询数据中心B版日志库成功--------------------------");
|
||||
return rsB;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
291
src/main/java/com/nis/util/HiveJDBC.java
Normal file
291
src/main/java/com/nis/util/HiveJDBC.java
Normal file
@@ -0,0 +1,291 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.ibatis.mapping.ResultMap;
|
||||
import org.apache.ibatis.mapping.ResultMapping;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.nis.domain.Page;
|
||||
import com.nis.util.redis.SaveRedisListThread;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
public class HiveJDBC {
|
||||
private final static Logger logger = Logger.getLogger(HiveJDBC.class);
|
||||
static Connection conn = null;
|
||||
static ResultSet rs = null;
|
||||
static Statement st = null;
|
||||
static Properties prop = new Properties();
|
||||
static String driverName = "";
|
||||
static String url = "";
|
||||
static String username = "";
|
||||
static String password = "";
|
||||
static {
|
||||
try {
|
||||
prop.load(Configurations.class.getResourceAsStream("/jdbc.properties"));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void getConn(String searchActiveSys) throws Exception {
|
||||
|
||||
if (null != searchActiveSys && searchActiveSys.equals("4")) {
|
||||
driverName = prop.getProperty("jdbc.hiveA.driver").trim();
|
||||
url = prop.getProperty("jdbc.hiveA.url").trim();
|
||||
username = prop.getProperty("jdbc.hiveA.username").trim();
|
||||
password = prop.getProperty("jdbc.hiveA.password").trim();
|
||||
} else {
|
||||
driverName = prop.getProperty("jdbc.hiveB.driver").trim();
|
||||
url = prop.getProperty("jdbc.hiveB.url").trim();
|
||||
username = prop.getProperty("jdbc.hiveB.username").trim();
|
||||
password = prop.getProperty("jdbc.hiveB.password").trim();
|
||||
}
|
||||
Class.forName(driverName);
|
||||
conn = DriverManager.getConnection(url, username, password);
|
||||
|
||||
}
|
||||
|
||||
public static ResultSet query(String sql, String searchActiveSys) throws Exception {
|
||||
logger.info("开始连接数据中心日志库--------------------------");
|
||||
getConn(searchActiveSys);
|
||||
logger.info("连接数据中心日志库成功--------------------------");
|
||||
st = conn.createStatement();
|
||||
if (null != searchActiveSys && searchActiveSys.equals("4")) {
|
||||
st.execute("use xa_dfbhit_hive");
|
||||
} else {
|
||||
st.execute("use xa_z2_mesalog_hive");
|
||||
}
|
||||
rs = st.executeQuery(sql);
|
||||
return rs;
|
||||
}
|
||||
|
||||
public static void closeConn() {
|
||||
try {
|
||||
if (rs != null) {
|
||||
rs.close();
|
||||
rs = null;
|
||||
}
|
||||
if (st != null) {
|
||||
st.close();
|
||||
st = null;
|
||||
}
|
||||
if (conn != null) {
|
||||
conn.close();
|
||||
conn = null;
|
||||
}
|
||||
logger.info("关闭数据中心连接成功");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("关闭数据中心连接失败,失败原因" + e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws SQLException {
|
||||
try {
|
||||
// System.out.println(sdf.parse("2016-09-10 10:20:22").getTime());
|
||||
// ResultSet rs = query("");
|
||||
Map map = new HashMap();
|
||||
map.put("time", new Date());
|
||||
map.put("index", 1);
|
||||
for (Object key : map.keySet()) {
|
||||
Object obj = map.get(key);
|
||||
System.out.println(obj);
|
||||
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将结果利用反射映射成对象集合
|
||||
*
|
||||
* @param rs
|
||||
* resultSet
|
||||
* @param entityClass
|
||||
* 实体类
|
||||
* @param obj
|
||||
* 那些字段需要转换为date类型(由于数据中心表结构中没有date类型数据,其日期用long型表示,界面中需要显示yyyy-MM-dd
|
||||
* hh:mm:ss形式,所以需要将long转换为date)
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Map<String, List> tableMapping(Page page, String redisKey, ResultSet rs, Class entityClass,
|
||||
Object... obj) throws Exception {
|
||||
Map<String, List> mapList = new HashMap<String, List>();
|
||||
Map<String, String> filedAndColumnMap = getColumn2FiledMap(entityClass);
|
||||
List<String> listString = new ArrayList<String>();
|
||||
List listObject = new ArrayList();
|
||||
List<String> columnList = null;
|
||||
if (null != obj && obj.length > 0) {
|
||||
columnList = new ArrayList<String>();
|
||||
for (int i = 0; i < obj.length; i++) {
|
||||
columnList.add(obj[i].toString().toLowerCase());
|
||||
}
|
||||
}
|
||||
// ResultSet rs = HiveJDBC.query(sql.toString());
|
||||
ResultSetMetaData metaData = rs.getMetaData();
|
||||
while (rs.next()) {
|
||||
Map map = new HashMap();
|
||||
for (int i = 1; i <= metaData.getColumnCount(); i++) {
|
||||
Object value = rs.getObject(i);
|
||||
String filedName = filedAndColumnMap.get(metaData.getColumnName(i).toString().toLowerCase());
|
||||
if (null != value) {
|
||||
if (null != columnList && columnList.contains(filedName.toLowerCase())) {
|
||||
long time = 0l;
|
||||
if (null != value && !value.toString().equals("")) {
|
||||
time = Long.parseLong(value.toString());
|
||||
}
|
||||
map.put(filedName, new Date(time * 1000));
|
||||
// map.put(filedName, new
|
||||
// Date(Long.parseLong("1476583810000")));
|
||||
} else {
|
||||
map.put(filedName, value);
|
||||
}
|
||||
} else {
|
||||
map.put(filedName, null);
|
||||
}
|
||||
}
|
||||
listString.add(JsonMapper.toJsonString(map2Obj(map, entityClass)));
|
||||
listObject.add(map2Obj(map, entityClass));
|
||||
}
|
||||
logger.info("开始关闭数据中心连接");
|
||||
HiveJDBC.closeConn();
|
||||
if (null == listString || listString.size() == 0 || null == listObject || listObject.size() == 0) {
|
||||
return null;
|
||||
} else {
|
||||
if (Constants.IS_OPEN_REDIS && Constants.DATACENTER_OPEN_REDIS) {
|
||||
new SaveRedisListThread(redisKey, listString, Constants.HIVE_EXPIRE).start();
|
||||
}
|
||||
}
|
||||
// sublist包前不包后,0-30实际获取的是0-29的数据
|
||||
Integer startNum = (page.getPageNo() - 1) * page.getPageSize();
|
||||
Integer endNum = startNum - 1 + page.getPageSize() + 1;
|
||||
if (listString.size() >= startNum) {
|
||||
if (listString.size() >= endNum) {
|
||||
mapList.put("str", listString.subList(startNum, endNum));
|
||||
} else {
|
||||
mapList.put("str", listString.subList(startNum, listString.size()));
|
||||
}
|
||||
} else {
|
||||
mapList.put("str", new ArrayList());
|
||||
}
|
||||
if (listObject.size() >= startNum) {
|
||||
if (listObject.size() >= endNum) {
|
||||
mapList.put("obj", listObject.subList(startNum, endNum));
|
||||
} else {
|
||||
mapList.put("obj", listObject.subList(startNum, listObject.size()));
|
||||
}
|
||||
|
||||
} else {
|
||||
mapList.put("obj", new ArrayList());
|
||||
}
|
||||
return mapList;
|
||||
}
|
||||
|
||||
public static Object map2Obj(Map map, Class type) throws Exception {
|
||||
BeanInfo beanInfo = Introspector.getBeanInfo(type);
|
||||
Object obj = type.newInstance();
|
||||
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
|
||||
for (int i = 0; i < propertyDescriptors.length; i++) {
|
||||
PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
|
||||
String name = propertyDescriptor.getName();
|
||||
String fieldTypeName = propertyDescriptor.getPropertyType().getName();
|
||||
if (map.containsKey(name)) {
|
||||
Object value = map.get(name);
|
||||
if (null != value && !value.equals("")) {
|
||||
if (fieldTypeName.equals("java.lang.String")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj, new String[] { value.toString() });
|
||||
} else if (fieldTypeName.equals("java.lang.Integer")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Integer[] { Integer.parseInt(value.toString()) });
|
||||
// propertyDescriptor.getWriteMethod().invoke(obj, new
|
||||
// Integer[] { 0 });
|
||||
} else if (fieldTypeName.equals("java.lang.Long")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Long[] { Long.parseLong(value.toString()) });
|
||||
// propertyDescriptor.getWriteMethod().invoke(obj, new
|
||||
// Long[] { 0l });
|
||||
} else if (fieldTypeName.equals("java.lang.Boolean")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Boolean[] { Boolean.parseBoolean(value.toString()) });
|
||||
} else if (fieldTypeName.equals("java.lang.Character")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj, value.toString().toCharArray());
|
||||
} else if (fieldTypeName.equals("java.lang.Byte")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj, value.toString().getBytes());
|
||||
} else if (fieldTypeName.equals("java.lang.Short")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Short[] { Short.parseShort(value.toString()) });
|
||||
} else if (fieldTypeName.equals("java.lang.Float")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Float[] { Float.parseFloat(value.toString()) });
|
||||
} else if (fieldTypeName.equals("java.lang.Double")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Double[] { Double.parseDouble(value.toString()) });
|
||||
} else if (fieldTypeName.equals("java.math.BigDecimal")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new BigDecimal[] { BigDecimal.valueOf(Long.parseLong(value.toString())) });
|
||||
// propertyDescriptor.getWriteMethod().invoke(obj, new
|
||||
// BigDecimal[] { new BigDecimal(0) });
|
||||
} else if (fieldTypeName.equals("java.util.Date")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj, new Date[] { (Date) value });
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
|
||||
}
|
||||
|
||||
public static Map<String, String> getColumn2FiledMap(Class clazz) {
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
SqlSessionFactory sqlSessionFactory = SpringContextHolder.getBean(SqlSessionFactory.class);
|
||||
ResultMap resultMap = sqlSessionFactory.getConfiguration().getResultMap(clazz.getSimpleName() + "Map");
|
||||
List<ResultMapping> mapping = resultMap.getResultMappings();
|
||||
for (ResultMapping mapp : mapping) {
|
||||
map.put(mapp.getColumn().toLowerCase(), mapp.getProperty());
|
||||
}
|
||||
return map;
|
||||
|
||||
}
|
||||
|
||||
public static void close() {
|
||||
try {
|
||||
if (rs != null) {
|
||||
rs.close();
|
||||
rs = null;
|
||||
}
|
||||
if (st != null) {
|
||||
st.close();
|
||||
st = null;
|
||||
}
|
||||
if (conn != null) {
|
||||
conn.close();
|
||||
conn = null;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
63
src/main/java/com/nis/util/ImageGeo.java
Normal file
63
src/main/java/com/nis/util/ImageGeo.java
Normal file
@@ -0,0 +1,63 @@
|
||||
package com.nis.util;
|
||||
|
||||
import com.drew.metadata.*;
|
||||
import com.drew.metadata.exif.*;
|
||||
import com.drew.imaging.jpeg.*;
|
||||
import com.drew.lang.*;
|
||||
import java.io.*;
|
||||
|
||||
public class ImageGeo {
|
||||
public double lat = 0.0;
|
||||
public double lon = 0.0;
|
||||
public double alt = 0.0;
|
||||
public boolean error = false;
|
||||
|
||||
public ImageGeo(String filename) {
|
||||
try {
|
||||
error = false;
|
||||
File jpegFile = new File(filename);
|
||||
Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
|
||||
|
||||
GpsDirectory gpsdir = (GpsDirectory) metadata
|
||||
.getDirectory(GpsDirectory.class);
|
||||
Rational latpart[] = gpsdir
|
||||
.getRationalArray(GpsDirectory.TAG_GPS_LATITUDE);
|
||||
Rational lonpart[] = gpsdir
|
||||
.getRationalArray(GpsDirectory.TAG_GPS_LONGITUDE);
|
||||
String northing = gpsdir
|
||||
.getString(GpsDirectory.TAG_GPS_LATITUDE_REF);
|
||||
String easting = gpsdir
|
||||
.getString(GpsDirectory.TAG_GPS_LONGITUDE_REF);
|
||||
|
||||
try {
|
||||
alt = gpsdir.getDouble(GpsDirectory.TAG_GPS_ALTITUDE);
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
|
||||
double latsign = 1.0d;
|
||||
if (northing.equalsIgnoreCase("S"))
|
||||
latsign = -1.0d;
|
||||
double lonsign = 1.0d;
|
||||
if (easting.equalsIgnoreCase("W"))
|
||||
lonsign = -1.0d;
|
||||
lat = (Math.abs(latpart[0].doubleValue())
|
||||
+ latpart[1].doubleValue() / 60.0d + latpart[2]
|
||||
.doubleValue() / 3600.0d) * latsign;
|
||||
lon = (Math.abs(lonpart[0].doubleValue())
|
||||
+ lonpart[1].doubleValue() / 60.0d + lonpart[2]
|
||||
.doubleValue() / 3600.0d) * lonsign;
|
||||
|
||||
if (Double.isNaN(lat) || Double.isNaN(lon))
|
||||
error = true;
|
||||
} catch (Exception ex) {
|
||||
error = true;
|
||||
}
|
||||
System.out.println(filename + ": (" + lat + ", " + lon + ")");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ImageGeo imageGeo = new ImageGeo(ImageGeo.class.getResource("IMAG0068.jpg").getFile());
|
||||
System.out.println(imageGeo.lon+","+imageGeo.lat);
|
||||
}
|
||||
|
||||
}
|
||||
42
src/main/java/com/nis/util/JsonDateSerializer.java
Normal file
42
src/main/java/com/nis/util/JsonDateSerializer.java
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
*@Title: JsonDateSerializer.java
|
||||
*@Package com.nis.domain.restful
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年9月9日 下午8:36:59
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.nis.util.DateUtil;
|
||||
|
||||
/**
|
||||
* @ClassName: JsonDateSerializer.java
|
||||
* @Description: TODO 用于非get请求时讲返回结果呈现界面时的Json格式转换,用法 在Date类型的get方法上加上 @JsonSerialize(using=JsonDateSerializer.class)
|
||||
* @author (wx)
|
||||
* @date 2016年9月9日 下午8:36:59
|
||||
* @version V1.0
|
||||
*/
|
||||
public class JsonDateSerializer extends JsonSerializer<Date> {
|
||||
private static final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
|
||||
/* (non-Javadoc)
|
||||
* @see com.fasterxml.jackson.databind.JsonSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
|
||||
*/
|
||||
@Override
|
||||
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
|
||||
throws IOException, JsonProcessingException {
|
||||
// TODO Auto-generated method stub
|
||||
//gen.writeString(sdf.format(date));
|
||||
gen.writeString(DateUtil.getFormatDate(date, DateUtil.YYYY_MM_DD_HH24_MM_SS));
|
||||
}
|
||||
|
||||
}
|
||||
54
src/main/java/com/nis/util/JsonDateValueProcessor.java
Normal file
54
src/main/java/com/nis/util/JsonDateValueProcessor.java
Normal file
@@ -0,0 +1,54 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
import net.sf.json.JsonConfig;
|
||||
import net.sf.json.processors.JsonValueProcessor;
|
||||
|
||||
/**
|
||||
*
|
||||
* @ClassName: JsonDateValueProcessor
|
||||
* @Description: TODO(处理对象中日期类型转换为json时格式问题,后期会删除)
|
||||
* @author (rkg)
|
||||
* @date 2016年9月27日下午3:43:48
|
||||
* @version V1.0
|
||||
*/
|
||||
public class JsonDateValueProcessor implements JsonValueProcessor {
|
||||
private String format = "yyyy-MM-dd'T'HH:mm:ss.SSS";
|
||||
//private String format = "yyyy-MM-dd";
|
||||
|
||||
public JsonDateValueProcessor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public JsonDateValueProcessor(String format) {
|
||||
super();
|
||||
this.format = format;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object processArrayValue(Object parm, JsonConfig arg1) {
|
||||
return process(parm);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object processObjectValue(String key, Object value, JsonConfig arg2) {
|
||||
return process(value);
|
||||
}
|
||||
|
||||
private Object process(Object value) {
|
||||
if (value instanceof Date) {
|
||||
long time= ((Date) value).getTime()-8*60*60*1000;
|
||||
//value=
|
||||
//SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(format);
|
||||
return sdf.format(time);
|
||||
|
||||
}
|
||||
return value == null ? "" : value.toString();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
255
src/main/java/com/nis/util/JsonMapper.java
Normal file
255
src/main/java/com/nis/util/JsonMapper.java
Normal file
@@ -0,0 +1,255 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.apache.commons.lang3.StringEscapeUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.JsonParser.Feature;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JavaType;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.databind.util.JSONPObject;
|
||||
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.domain.Page;
|
||||
|
||||
/**
|
||||
* 简单封装Jackson,实现JSON String<->Java Object的Mapper. 封装不同的输出风格,
|
||||
* 使用不同的builder函数创建实例.
|
||||
*
|
||||
* @author ThinkGem
|
||||
* @version 2013-11-15
|
||||
*/
|
||||
public class JsonMapper extends ObjectMapper {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
|
||||
|
||||
private static JsonMapper mapper;
|
||||
|
||||
public JsonMapper() {
|
||||
this(Include.ALWAYS);
|
||||
}
|
||||
|
||||
public JsonMapper(Include include) {
|
||||
// 设置输出时包含属性的风格
|
||||
if (include != null) {
|
||||
this.setSerializationInclusion(include);
|
||||
}
|
||||
// 允许单引号、允许不带引号的字段名称
|
||||
this.enableSimple();
|
||||
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
|
||||
this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
// 空值
|
||||
/*
|
||||
* this.getSerializerProvider().setNullValueSerializer(new
|
||||
* JsonSerializer<Object>(){
|
||||
*
|
||||
* @Override public void serialize(Object value, JsonGenerator jgen,
|
||||
* SerializerProvider provider) throws IOException,
|
||||
* JsonProcessingException { jgen.writeString(""); } });
|
||||
*/
|
||||
this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
|
||||
// 进行HTML解码。
|
||||
this.registerModule(new SimpleModule().addSerializer(String.class, new JsonSerializer<String>() {
|
||||
@Override
|
||||
public void serialize(String value, JsonGenerator jgen, SerializerProvider provider)
|
||||
throws IOException, JsonProcessingException {
|
||||
jgen.writeString(StringEscapeUtils.unescapeHtml4(value));
|
||||
}
|
||||
}));
|
||||
// 设置时区
|
||||
this.setTimeZone(TimeZone.getDefault());// getTimeZone("GMT+8:00")
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
|
||||
*/
|
||||
public static JsonMapper getInstance() {
|
||||
if (mapper == null) {
|
||||
mapper = new JsonMapper();// .enableSimple();只输出非Null且非Empty
|
||||
}
|
||||
return mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
|
||||
*/
|
||||
public static JsonMapper nonDefaultMapper() {
|
||||
if (mapper == null) {
|
||||
mapper = new JsonMapper(Include.NON_DEFAULT);
|
||||
}
|
||||
return mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Object可以是POJO,也可以是Collection或数组。 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]".
|
||||
*/
|
||||
public String toJson(Object object) {
|
||||
try {
|
||||
return this.writeValueAsString(object);
|
||||
} catch (IOException e) {
|
||||
logger.warn("write to json string error:" + object, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化POJO或简单Collection如List<String>.
|
||||
*
|
||||
* 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
|
||||
*
|
||||
* 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType)
|
||||
*
|
||||
* @see #fromJson(String, JavaType)
|
||||
*/
|
||||
public <T> T fromJson(String jsonString, Class<T> clazz) {
|
||||
if (StringUtils.isEmpty(jsonString)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return this.readValue(jsonString, clazz);
|
||||
} catch (IOException e) {
|
||||
logger.warn("parse json string error:" + jsonString, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调用本函数.
|
||||
*
|
||||
* @see #createCollectionType(Class, Class...)
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T fromJson(String jsonString, JavaType javaType) {
|
||||
if (StringUtils.isEmpty(jsonString)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return (T) this.readValue(jsonString, javaType);
|
||||
} catch (IOException e) {
|
||||
logger.warn("parse json string error:" + jsonString, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 構造泛型的Collection Type如: ArrayList<MyBean>,
|
||||
* 则调用constructCollectionType(ArrayList.class,MyBean.class)
|
||||
* HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class)
|
||||
*/
|
||||
public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
|
||||
return this.getTypeFactory().constructParametricType(collectionClass, elementClasses);
|
||||
}
|
||||
|
||||
/**
|
||||
* 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T update(String jsonString, T object) {
|
||||
try {
|
||||
return (T) this.readerForUpdating(object).readValue(jsonString);
|
||||
} catch (JsonProcessingException e) {
|
||||
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
|
||||
} catch (IOException e) {
|
||||
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 輸出JSONP格式數據.
|
||||
*/
|
||||
public String toJsonP(String functionName, Object object) {
|
||||
return toJson(new JSONPObject(functionName, object));
|
||||
}
|
||||
|
||||
/**
|
||||
* 設定是否使用Enum的toString函數來讀寫Enum, 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
|
||||
* 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
|
||||
*/
|
||||
public JsonMapper enableEnumUseToString() {
|
||||
this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
|
||||
this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
|
||||
* 默认会先查找jaxb的annotation,如果找不到再找jackson的。
|
||||
*/
|
||||
public JsonMapper enableJaxbAnnotation() {
|
||||
JaxbAnnotationModule module = new JaxbAnnotationModule();
|
||||
this.registerModule(module);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 允许单引号 允许不带引号的字段名称
|
||||
*/
|
||||
public JsonMapper enableSimple() {
|
||||
this.configure(Feature.ALLOW_SINGLE_QUOTES, true);
|
||||
this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出Mapper做进一步的设置或使用其他序列化API.
|
||||
*/
|
||||
public ObjectMapper getMapper() {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对象转换为JSON字符串
|
||||
*
|
||||
* @param object
|
||||
* @return
|
||||
*/
|
||||
public static String toJsonString(Object object) {
|
||||
return JsonMapper.getInstance().toJson(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON字符串转换为对象
|
||||
*
|
||||
* @param jsonString
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
public static Object fromJsonString(String jsonString, Class<?> clazz) {
|
||||
return JsonMapper.getInstance().fromJson(jsonString, clazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON字符串转换为对象
|
||||
*
|
||||
* @param jsonString
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
public static Object fromJsonList(String jsonString, Class<?> clazz) {
|
||||
JavaType javaType = JsonMapper.getInstance().createCollectionType(ArrayList.class, clazz);
|
||||
return JsonMapper.getInstance().fromJson(jsonString,javaType );
|
||||
}
|
||||
}
|
||||
192
src/main/java/com/nis/util/LogUtils.java
Normal file
192
src/main/java/com/nis/util/LogUtils.java
Normal file
@@ -0,0 +1,192 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.domain.SysDataDictionaryItem;
|
||||
import com.nis.domain.SysLog;
|
||||
import com.nis.domain.SysMenu;
|
||||
import com.nis.domain.SysUser;
|
||||
import com.nis.web.dao.SysLogDao;
|
||||
import com.nis.web.dao.SysMenuDao;
|
||||
import com.nis.web.security.UserUtils;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
import com.sun.corba.se.impl.orbutil.closure.Constant;
|
||||
|
||||
|
||||
public class LogUtils {
|
||||
|
||||
public static final String CACHE_MENU_NAME_PATH_MAP = "menuNamePathMap";
|
||||
|
||||
private static SysLogDao logDao = SpringContextHolder.getBean(SysLogDao.class);
|
||||
private static SysMenuDao menuDao = SpringContextHolder.getBean(SysMenuDao.class);
|
||||
|
||||
/**
|
||||
* 保存日志
|
||||
*/
|
||||
public static void saveLog(HttpServletRequest request, String title){
|
||||
saveLog(request, null, null, title, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存日志
|
||||
*/
|
||||
public static void saveLog(HttpServletRequest request, Object handler, Exception ex, String title){
|
||||
saveLog(request, handler, ex, title, 0);
|
||||
}
|
||||
|
||||
public static void saveLog(HttpServletRequest request, Object handler, Exception ex, String title, long consumerTime){
|
||||
SysUser user = UserUtils.getUser();
|
||||
if (user != null && user.getId() != null){
|
||||
SysLog log = new SysLog();
|
||||
log.setType(getOperateType(handler));
|
||||
log.setTitle(title);
|
||||
log.setConsumerTime(consumerTime);
|
||||
log.setState(ex == null ? Constants.LOG_ACCESS_SUCCESS : Constants.LOG_ACCESS_EXCEPTION);
|
||||
log.setRemoteAddr(StringUtils.getRemoteAddr(request));
|
||||
log.setUserAgent(request.getHeader("user-agent"));
|
||||
log.setRequestUri(request.getRequestURI());
|
||||
log.setParams(request.getParameterMap());
|
||||
log.setMethod(request.getMethod());
|
||||
log.setCreateBy(user.getName());
|
||||
log.setCreateDate(new Date());
|
||||
// 异步保存日志
|
||||
new SaveLogThread(log, handler, ex).start();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存日志线程
|
||||
*/
|
||||
public static class SaveLogThread extends Thread{
|
||||
|
||||
private SysLog log;
|
||||
private Object handler;
|
||||
private Exception ex;
|
||||
|
||||
public SaveLogThread(SysLog log, Object handler, Exception ex){
|
||||
super(SaveLogThread.class.getSimpleName());
|
||||
this.log = log;
|
||||
this.handler = handler;
|
||||
this.ex = ex;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// 获取日志标题
|
||||
if (StringUtils.isBlank(log.getTitle())){
|
||||
String permission = "";
|
||||
if (handler instanceof HandlerMethod){
|
||||
Method m = ((HandlerMethod)handler).getMethod();
|
||||
RequiresPermissions rp = m.getAnnotation(RequiresPermissions.class);
|
||||
permission = (rp != null ? StringUtils.join(rp.value(), ",") : "");
|
||||
}
|
||||
log.setTitle(getMenuNamePath(log.getRequestUri(), permission));
|
||||
}
|
||||
// 如果有异常,设置异常信息
|
||||
log.setException(Exceptions.getStackTraceAsString(ex));
|
||||
// 如果无标题并无异常日志,则不保存信息
|
||||
if (StringUtils.isBlank(log.getTitle()) && StringUtils.isBlank(log.getException())){
|
||||
return;
|
||||
}
|
||||
// 保存日志信息
|
||||
logDao.insert(log);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static int getOperateType(Object handler) {
|
||||
int type = Constants.DEFAULT_METHOD_TYPE;
|
||||
|
||||
if (!StringUtil.isEmpty(handler)) {
|
||||
if (handler instanceof HandlerMethod) {
|
||||
Method m = ((HandlerMethod)handler).getMethod();
|
||||
String methodName = m.getName();
|
||||
List<SysDataDictionaryItem> dictList = DictUtils.getDictList("SYS_LOG_TYPE");
|
||||
for(SysDataDictionaryItem sysDataDictionaryItem:dictList){
|
||||
if(methodName.toLowerCase().matches(sysDataDictionaryItem.getItemCode().toLowerCase()+".*")){
|
||||
type = Integer.parseInt(sysDataDictionaryItem.getItemValue());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
return type;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 获取菜单名称路径(如:系统设置-机构用户-用户管理-编辑)
|
||||
*/
|
||||
public static String getMenuNamePath(String requestUri, String permission){
|
||||
String href = StringUtils.substringAfter(requestUri, Configurations.getStringProperty("adminPath", "/nis"));
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> menuMap = (Map<String, String>)CacheUtils.get(CACHE_MENU_NAME_PATH_MAP);
|
||||
if (menuMap == null){
|
||||
menuMap = Maps.newHashMap();
|
||||
List<SysMenu> menuList = menuDao.findAllList(new SysMenu());
|
||||
for (SysMenu menu : menuList){
|
||||
// 获取菜单名称路径(如:系统设置-机构用户-用户管理-编辑)
|
||||
String namePath = "";
|
||||
if (menu.getParentIds() != null){
|
||||
List<String> namePathList = Lists.newArrayList();
|
||||
for (String id : StringUtils.split(menu.getParentIds(), ",")){
|
||||
|
||||
|
||||
if (SysMenu.getRootId().equals(Long.valueOf(id))){
|
||||
continue; // 过滤跟节点
|
||||
}
|
||||
for (SysMenu m : menuList){
|
||||
if (m.getId().equals(Long.valueOf(id))){
|
||||
namePathList.add(m.getName());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
namePathList.add(menu.getName());
|
||||
namePath = StringUtils.join(namePathList, "-");
|
||||
}
|
||||
// 设置菜单名称路径
|
||||
if (StringUtils.isNotBlank(menu.getHref())){
|
||||
menuMap.put(menu.getHref(), namePath);
|
||||
}else if (StringUtils.isNotBlank(menu.getPermission())){
|
||||
for (String p : StringUtils.split(menu.getPermission())){
|
||||
menuMap.put(p, namePath);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
CacheUtils.put(CACHE_MENU_NAME_PATH_MAP, menuMap);
|
||||
}
|
||||
String menuNamePath = menuMap.get(href);
|
||||
if (menuNamePath == null){
|
||||
for (String p : StringUtils.split(permission)){
|
||||
menuNamePath = menuMap.get(p);
|
||||
if (StringUtils.isNotBlank(menuNamePath)){
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (menuNamePath == null){
|
||||
return "";
|
||||
}
|
||||
}
|
||||
return menuNamePath;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
83
src/main/java/com/nis/util/MD5Utils.java
Normal file
83
src/main/java/com/nis/util/MD5Utils.java
Normal file
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang3.StringEscapeUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
|
||||
import com.ckfinder.connector.ServletContextFactory;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
/**
|
||||
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
|
||||
* @author ThinkGem
|
||||
* @version 2013-05-22
|
||||
*/
|
||||
public class MD5Utils{
|
||||
|
||||
/**
|
||||
* 字符串转为MD532位小写
|
||||
* @param plain
|
||||
* @return
|
||||
*/
|
||||
public static String md5LowerCase(String plain) throws Exception{
|
||||
String re_md5 = new String();
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
md.update(plain.getBytes());
|
||||
byte b[] = md.digest();
|
||||
|
||||
int i;
|
||||
|
||||
StringBuffer buf = new StringBuffer("");
|
||||
for (int offset = 0; offset < b.length; offset++) {
|
||||
i = b[offset];
|
||||
if (i < 0)
|
||||
i += 256;
|
||||
if (i < 16)
|
||||
buf.append("0");
|
||||
buf.append(Integer.toHexString(i));
|
||||
}
|
||||
|
||||
re_md5 = buf.toString();
|
||||
return re_md5;
|
||||
}
|
||||
public static byte[] createChecksum(String filename) throws IOException, NoSuchAlgorithmException{
|
||||
InputStream fis=new FileInputStream(filename);
|
||||
byte[] buffer=new byte[1024];
|
||||
MessageDigest complete=MessageDigest.getInstance("MD5");
|
||||
int numRead;
|
||||
do{
|
||||
numRead=fis.read(buffer);
|
||||
if(numRead>0){
|
||||
complete.update(buffer,0,numRead);
|
||||
}
|
||||
}while(numRead!=-1);
|
||||
fis.close();
|
||||
return complete.digest();
|
||||
}
|
||||
public static String getMD5Checksum(String filename) throws NoSuchAlgorithmException, IOException{
|
||||
byte[] b=createChecksum(filename);
|
||||
StringBuffer result=new StringBuffer();
|
||||
for(int i=0;i<b.length;i++){
|
||||
result.append(Integer.toString((b[i] & 0xff)+ 0x100,16).substring(1));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
88
src/main/java/com/nis/util/ObjectUtils.java
Normal file
88
src/main/java/com/nis/util/ObjectUtils.java
Normal file
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
/**
|
||||
* 对象操作工具类, 继承org.apache.commons.lang3.ObjectUtils类
|
||||
* @author ThinkGem
|
||||
* @version 2014-6-29
|
||||
*/
|
||||
public class ObjectUtils extends org.apache.commons.lang3.ObjectUtils {
|
||||
|
||||
/**
|
||||
* 注解到对象复制,只复制能匹配上的方法。
|
||||
* @param annotation
|
||||
* @param object
|
||||
*/
|
||||
public static void annotationToObject(Object annotation, Object object){
|
||||
if (annotation != null){
|
||||
Class<?> annotationClass = annotation.getClass();
|
||||
Class<?> objectClass = object.getClass();
|
||||
for (Method m : objectClass.getMethods()){
|
||||
if (StringUtils.startsWith(m.getName(), "set")){
|
||||
try {
|
||||
String s = StringUtils.uncapitalize(StringUtils.substring(m.getName(), 3));
|
||||
Object obj = annotationClass.getMethod(s).invoke(annotation);
|
||||
if (obj != null && !"".equals(obj.toString())){
|
||||
if (object == null){
|
||||
object = objectClass.newInstance();
|
||||
}
|
||||
m.invoke(object, obj);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 忽略所有设置失败方法
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列化对象
|
||||
* @param object
|
||||
* @return
|
||||
*/
|
||||
public static byte[] serialize(Object object) {
|
||||
ObjectOutputStream oos = null;
|
||||
ByteArrayOutputStream baos = null;
|
||||
try {
|
||||
if (object != null){
|
||||
baos = new ByteArrayOutputStream();
|
||||
oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject(object);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化对象
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
public static Object unserialize(byte[] bytes) {
|
||||
ByteArrayInputStream bais = null;
|
||||
try {
|
||||
if (bytes != null && bytes.length > 0){
|
||||
bais = new ByteArrayInputStream(bytes);
|
||||
ObjectInputStream ois = new ObjectInputStream(bais);
|
||||
return ois.readObject();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
28
src/main/java/com/nis/util/OracleErrorCodeUtil.java
Normal file
28
src/main/java/com/nis/util/OracleErrorCodeUtil.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class OracleErrorCodeUtil {
|
||||
/**
|
||||
* 返回异常信息内容
|
||||
*
|
||||
* @param e
|
||||
* @return
|
||||
*/
|
||||
public static String getOraCode(Exception e) {
|
||||
if (e == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
String errorMessage = e.getMessage();
|
||||
if (null != errorMessage && errorMessage.length() > 0) {
|
||||
int index = errorMessage.toUpperCase().indexOf("ORA-");
|
||||
if (index != -1) {
|
||||
return errorMessage.substring(index + 4, index + 9);
|
||||
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
|
||||
|
||||
import com.nis.crypt.AESUtil;
|
||||
|
||||
public class PropertyPlaceholderConfigurerCrypt extends PropertyPlaceholderConfigurer {
|
||||
|
||||
@Override
|
||||
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
|
||||
throws BeansException {
|
||||
|
||||
try {
|
||||
String productPassword = props.getProperty("jdbc.product.password");
|
||||
String productScretKey = props.getProperty("jdbc.product.key");
|
||||
if (null != productPassword) {
|
||||
props.setProperty("jdbc.product.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(productPassword), productScretKey)));
|
||||
}
|
||||
|
||||
String devlopPassword = props.getProperty("jdbc.devlop.password");
|
||||
String devlopScretKey = props.getProperty("jdbc.devlop.key");
|
||||
if (null != devlopPassword) {
|
||||
props.setProperty("jdbc.devlop.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(devlopPassword), devlopScretKey)));
|
||||
}
|
||||
|
||||
String logPassword = props.getProperty("jdbc.log.password");
|
||||
String logScretKey = props.getProperty("jdbc.log.key");
|
||||
if (null != logPassword) {
|
||||
props.setProperty("jdbc.log.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(logPassword), logScretKey)));
|
||||
}
|
||||
|
||||
// 日志A版
|
||||
String logAPassword = props.getProperty("jdbc.logA.password");
|
||||
String logAScretKey = props.getProperty("jdbc.logA.key");
|
||||
if (null != logAPassword) {
|
||||
props.setProperty("jdbc.logA.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(logAPassword), logAScretKey)));
|
||||
}
|
||||
// 日志A版
|
||||
String logCPassword = props.getProperty("jdbc.logC.password");
|
||||
String logCScretKey = props.getProperty("jdbc.logC.key");
|
||||
if (null != logAPassword) {
|
||||
props.setProperty("jdbc.logC.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(logCPassword), logCScretKey)));
|
||||
}
|
||||
|
||||
|
||||
// 测试使用,后期会删除
|
||||
String testPassword = props.getProperty("jdbc.test.password");
|
||||
String testScretKey = props.getProperty("jdbc.test.key");
|
||||
if (null != testPassword) {
|
||||
props.setProperty("jdbc.test.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(testPassword), testScretKey)));
|
||||
}
|
||||
|
||||
String jkPzPassword = props.getProperty("jdbc.jk.password");
|
||||
String jkPzScretKey = props.getProperty("jdbc.jk.key");
|
||||
if (null != jkPzPassword) {
|
||||
props.setProperty("jdbc.jk.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(jkPzPassword), jkPzScretKey)));
|
||||
}
|
||||
//A版hive库
|
||||
String hiveAPassword = props.getProperty("jdbc.hiveA.password");
|
||||
String hiveAScretKey = props.getProperty("jdbc.hiveA.key");
|
||||
if (null != hiveAPassword) {
|
||||
props.setProperty("jdbc.hiveA.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(hiveAPassword), hiveAScretKey)));
|
||||
}
|
||||
|
||||
//B版hive库
|
||||
String hiveBPassword = props.getProperty("jdbc.hiveB.password");
|
||||
String hiveBScretKey = props.getProperty("jdbc.hiveB.key");
|
||||
if (null != hiveBPassword) {
|
||||
props.setProperty("jdbc.hiveB.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(hiveBPassword), hiveBScretKey)));
|
||||
}
|
||||
|
||||
//神通数据库库
|
||||
String clusterPassword = props.getProperty("jdbc.log.cluster.password");
|
||||
String clusterScretKey = props.getProperty("jdbc.log.cluster.key");
|
||||
if (null != clusterPassword) {
|
||||
props.setProperty("jdbc.log.cluster.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(clusterPassword), clusterScretKey)));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
super.processProperties(beanFactoryToProcess, props);
|
||||
}
|
||||
|
||||
}
|
||||
304
src/main/java/com/nis/util/Reflections.java
Normal file
304
src/main/java/com/nis/util/Reflections.java
Normal file
@@ -0,0 +1,304 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* 反射工具类.
|
||||
* 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
|
||||
* @author calvin
|
||||
* @version 2013-01-15
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public class Reflections {
|
||||
|
||||
private static final String SETTER_PREFIX = "set";
|
||||
|
||||
private static final String GETTER_PREFIX = "get";
|
||||
|
||||
private static final String CGLIB_CLASS_SEPARATOR = "$$";
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(Reflections.class);
|
||||
|
||||
/**
|
||||
* 调用Getter方法.
|
||||
* 支持多级,如:对象名.对象名.方法
|
||||
*/
|
||||
public static Object invokeGetter(Object obj, String propertyName) {
|
||||
Object object = obj;
|
||||
for (String name : StringUtils.split(propertyName, ".")){
|
||||
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
|
||||
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用Setter方法, 仅匹配方法名。
|
||||
* 支持多级,如:对象名.对象名.方法
|
||||
*/
|
||||
public static void invokeSetter(Object obj, String propertyName, Object value) {
|
||||
Object object = obj;
|
||||
String[] names = StringUtils.split(propertyName, ".");
|
||||
for (int i=0; i<names.length; i++){
|
||||
if(i<names.length-1){
|
||||
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
|
||||
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
|
||||
}else{
|
||||
String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
|
||||
invokeMethodByName(object, setterMethodName, new Object[] { value });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
|
||||
*/
|
||||
public static Object getFieldValue(final Object obj, final String fieldName) {
|
||||
Field field = getAccessibleField(obj, fieldName);
|
||||
|
||||
if (field == null) {
|
||||
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
|
||||
}
|
||||
|
||||
Object result = null;
|
||||
try {
|
||||
result = field.get(obj);
|
||||
} catch (IllegalAccessException e) {
|
||||
logger.error("不可能抛出的异常{}", e.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
|
||||
*/
|
||||
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
|
||||
Field field = getAccessibleField(obj, fieldName);
|
||||
|
||||
if (field == null) {
|
||||
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
|
||||
}
|
||||
|
||||
try {
|
||||
field.set(obj, value);
|
||||
} catch (IllegalAccessException e) {
|
||||
logger.error("不可能抛出的异常:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接调用对象方法, 无视private/protected修饰符.
|
||||
* 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用.
|
||||
* 同时匹配方法名+参数类型,
|
||||
*/
|
||||
public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
|
||||
final Object[] args) {
|
||||
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
|
||||
if (method == null) {
|
||||
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
|
||||
}
|
||||
|
||||
try {
|
||||
return method.invoke(obj, args);
|
||||
} catch (Exception e) {
|
||||
throw convertReflectionExceptionToUnchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接调用对象方法, 无视private/protected修饰符,
|
||||
* 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
|
||||
* 只匹配函数名,如果有多个同名函数调用第一个。
|
||||
*/
|
||||
public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
|
||||
Method method = getAccessibleMethodByName(obj, methodName);
|
||||
if (method == null) {
|
||||
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
|
||||
}
|
||||
|
||||
try {
|
||||
return method.invoke(obj, args);
|
||||
} catch (Exception e) {
|
||||
throw convertReflectionExceptionToUnchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
|
||||
*
|
||||
* 如向上转型到Object仍无法找到, 返回null.
|
||||
*/
|
||||
public static Field getAccessibleField(final Object obj, final String fieldName) {
|
||||
Validate.notNull(obj, "object can't be null");
|
||||
Validate.notBlank(fieldName, "fieldName can't be blank");
|
||||
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
|
||||
try {
|
||||
Field field = superClass.getDeclaredField(fieldName);
|
||||
makeAccessible(field);
|
||||
return field;
|
||||
} catch (NoSuchFieldException e) {//NOSONAR
|
||||
// Field不在当前类定义,继续向上转型
|
||||
continue;// new add
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
|
||||
* 如向上转型到Object仍无法找到, 返回null.
|
||||
* 匹配函数名+参数类型。
|
||||
*
|
||||
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
|
||||
*/
|
||||
public static Method getAccessibleMethod(final Object obj, final String methodName,
|
||||
final Class<?>... parameterTypes) {
|
||||
Validate.notNull(obj, "object can't be null");
|
||||
Validate.notBlank(methodName, "methodName can't be blank");
|
||||
|
||||
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
|
||||
try {
|
||||
Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
|
||||
makeAccessible(method);
|
||||
return method;
|
||||
} catch (NoSuchMethodException e) {
|
||||
// Method不在当前类定义,继续向上转型
|
||||
continue;// new add
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
|
||||
* 如向上转型到Object仍无法找到, 返回null.
|
||||
* 只匹配函数名。
|
||||
*
|
||||
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
|
||||
*/
|
||||
public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
|
||||
Validate.notNull(obj, "object can't be null");
|
||||
Validate.notBlank(methodName, "methodName can't be blank");
|
||||
|
||||
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
|
||||
Method[] methods = searchType.getDeclaredMethods();
|
||||
for (Method method : methods) {
|
||||
if (method.getName().equals(methodName)) {
|
||||
makeAccessible(method);
|
||||
return method;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
|
||||
*/
|
||||
public static void makeAccessible(Method method) {
|
||||
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
|
||||
&& !method.isAccessible()) {
|
||||
method.setAccessible(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
|
||||
*/
|
||||
public static void makeAccessible(Field field) {
|
||||
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier
|
||||
.isFinal(field.getModifiers())) && !field.isAccessible()) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
|
||||
* 如无法找到, 返回Object.class.
|
||||
* eg.
|
||||
* public UserDao extends HibernateDao<User>
|
||||
*
|
||||
* @param clazz The class to introspect
|
||||
* @return the first generic declaration, or Object.class if cannot be determined
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Class<T> getClassGenricType(final Class clazz) {
|
||||
return getClassGenricType(clazz, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
|
||||
* 如无法找到, 返回Object.class.
|
||||
*
|
||||
* 如public UserDao extends HibernateDao<User,Long>
|
||||
*
|
||||
* @param clazz clazz The class to introspect
|
||||
* @param index the Index of the generic ddeclaration,start from 0.
|
||||
* @return the index generic declaration, or Object.class if cannot be determined
|
||||
*/
|
||||
public static Class getClassGenricType(final Class clazz, final int index) {
|
||||
|
||||
Type genType = clazz.getGenericSuperclass();
|
||||
|
||||
if (!(genType instanceof ParameterizedType)) {
|
||||
logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
|
||||
return Object.class;
|
||||
}
|
||||
|
||||
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
|
||||
|
||||
if (index >= params.length || index < 0) {
|
||||
logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
|
||||
+ params.length);
|
||||
return Object.class;
|
||||
}
|
||||
if (!(params[index] instanceof Class)) {
|
||||
logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
|
||||
return Object.class;
|
||||
}
|
||||
|
||||
return (Class) params[index];
|
||||
}
|
||||
|
||||
public static Class<?> getUserClass(Object instance) {
|
||||
Assert.notNull(instance, "Instance must not be null");
|
||||
Class clazz = instance.getClass();
|
||||
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
|
||||
Class<?> superClass = clazz.getSuperclass();
|
||||
if (superClass != null && !Object.class.equals(superClass)) {
|
||||
return superClass;
|
||||
}
|
||||
}
|
||||
return clazz;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 将反射时的checked exception转换为unchecked exception.
|
||||
*/
|
||||
public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
|
||||
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|
||||
|| e instanceof NoSuchMethodException) {
|
||||
return new IllegalArgumentException(e);
|
||||
} else if (e instanceof InvocationTargetException) {
|
||||
return new RuntimeException(((InvocationTargetException) e).getTargetException());
|
||||
} else if (e instanceof RuntimeException) {
|
||||
return (RuntimeException) e;
|
||||
}
|
||||
return new RuntimeException("Unexpected Checked Exception.", e);
|
||||
}
|
||||
}
|
||||
475
src/main/java/com/nis/util/StringUtils.java
Normal file
475
src/main/java/com/nis/util/StringUtils.java
Normal file
@@ -0,0 +1,475 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang3.StringEscapeUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
|
||||
import com.ckfinder.connector.ServletContextFactory;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
/**
|
||||
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
|
||||
*
|
||||
* @author ThinkGem
|
||||
* @version 2013-05-22
|
||||
*/
|
||||
public class StringUtils extends org.apache.commons.lang3.StringUtils {
|
||||
|
||||
private static final char SEPARATOR = '_';
|
||||
private static final String CHARSET_NAME = "UTF-8";
|
||||
public static final String HASH_ALGORITHM = "SHA-1";
|
||||
public static final int HASH_INTERATIONS = 1024;
|
||||
public static final int SALT_SIZE = 8;
|
||||
|
||||
/**
|
||||
* 转换为字节数组
|
||||
*
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static byte[] getBytes(String str) {
|
||||
if (str != null) {
|
||||
try {
|
||||
return str.getBytes(CHARSET_NAME);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为字节数组
|
||||
*
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static String toString(byte[] bytes) {
|
||||
try {
|
||||
return new String(bytes, CHARSET_NAME);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否包含字符串
|
||||
*
|
||||
* @param str
|
||||
* 验证字符串
|
||||
* @param strs
|
||||
* 字符串组
|
||||
* @return 包含返回true
|
||||
*/
|
||||
public static boolean inString(String str, String... strs) {
|
||||
if (str != null) {
|
||||
for (String s : strs) {
|
||||
if (str.equals(trim(s))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换掉HTML标签方法
|
||||
*/
|
||||
public static String replaceHtml(String html) {
|
||||
if (isBlank(html)) {
|
||||
return "";
|
||||
}
|
||||
String regEx = "<.+?>";
|
||||
Pattern p = Pattern.compile(regEx);
|
||||
Matcher m = p.matcher(html);
|
||||
String s = m.replaceAll("");
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
|
||||
*
|
||||
* @param html
|
||||
* @return
|
||||
*/
|
||||
public static String replaceMobileHtml(String html) {
|
||||
if (html == null) {
|
||||
return "";
|
||||
}
|
||||
return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
|
||||
*
|
||||
* @param txt
|
||||
* @return
|
||||
*/
|
||||
public static String toHtml(String txt) {
|
||||
if (txt == null) {
|
||||
return "";
|
||||
}
|
||||
return replace(replace(Encodes.escapeHtml(txt), "\n", "<br/>"), "\t", " ");
|
||||
}
|
||||
|
||||
/**
|
||||
* 缩略字符串(不区分中英文字符)
|
||||
*
|
||||
* @param str
|
||||
* 目标字符串
|
||||
* @param length
|
||||
* 截取长度
|
||||
* @return
|
||||
*/
|
||||
public static String abbr(String str, int length) {
|
||||
if (str == null) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int currentLength = 0;
|
||||
for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
|
||||
currentLength += String.valueOf(c).getBytes("GBK").length;
|
||||
if (currentLength <= length - 3) {
|
||||
sb.append(c);
|
||||
} else {
|
||||
sb.append("...");
|
||||
break;
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static String abbr2(String param, int length) {
|
||||
if (param == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuffer result = new StringBuffer();
|
||||
int n = 0;
|
||||
char temp;
|
||||
boolean isCode = false; // 是不是HTML代码
|
||||
boolean isHTML = false; // 是不是HTML特殊字符,如
|
||||
for (int i = 0; i < param.length(); i++) {
|
||||
temp = param.charAt(i);
|
||||
if (temp == '<') {
|
||||
isCode = true;
|
||||
} else if (temp == '&') {
|
||||
isHTML = true;
|
||||
} else if (temp == '>' && isCode) {
|
||||
n = n - 1;
|
||||
isCode = false;
|
||||
} else if (temp == ';' && isHTML) {
|
||||
isHTML = false;
|
||||
}
|
||||
try {
|
||||
if (!isCode && !isHTML) {
|
||||
n += String.valueOf(temp).getBytes("GBK").length;
|
||||
}
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (n <= length - 3) {
|
||||
result.append(temp);
|
||||
} else {
|
||||
result.append("...");
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 取出截取字符串中的HTML标记
|
||||
String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2");
|
||||
// 去掉不需要结素标记的HTML标记
|
||||
temp_result = temp_result.replaceAll(
|
||||
"</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>",
|
||||
"");
|
||||
// 去掉成对的HTML标记
|
||||
temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2");
|
||||
// 用正则表达式取出标记
|
||||
Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
|
||||
Matcher m = p.matcher(temp_result);
|
||||
List<String> endHTML = Lists.newArrayList();
|
||||
while (m.find()) {
|
||||
endHTML.add(m.group(1));
|
||||
}
|
||||
// 补全不成对的HTML标记
|
||||
for (int i = endHTML.size() - 1; i >= 0; i--) {
|
||||
result.append("</");
|
||||
result.append(endHTML.get(i));
|
||||
result.append(">");
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为Double类型
|
||||
*/
|
||||
public static Double toDouble(Object val) {
|
||||
if (val == null) {
|
||||
return 0D;
|
||||
}
|
||||
try {
|
||||
return Double.valueOf(trim(val.toString()));
|
||||
} catch (Exception e) {
|
||||
return 0D;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为Float类型
|
||||
*/
|
||||
public static Float toFloat(Object val) {
|
||||
return toDouble(val).floatValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为Long类型
|
||||
*/
|
||||
public static Long toLong(Object val) {
|
||||
return toDouble(val).longValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为Integer类型
|
||||
*/
|
||||
public static Integer toInteger(Object val) {
|
||||
return toLong(val).intValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得i18n字符串
|
||||
*/
|
||||
public static String getMessage(String code, Object[] args) {
|
||||
LocaleResolver localLocaleResolver = (LocaleResolver) SpringContextHolder.getBean(LocaleResolver.class);
|
||||
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
|
||||
.getRequest();
|
||||
Locale localLocale = localLocaleResolver.resolveLocale(request);
|
||||
return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得用户远程地址
|
||||
*/
|
||||
public static String getRemoteAddr(HttpServletRequest request) {
|
||||
String remoteAddr = request.getHeader("X-Real-IP");
|
||||
if (isNotBlank(remoteAddr)) {
|
||||
remoteAddr = request.getHeader("X-Forwarded-For");
|
||||
} else if (isNotBlank(remoteAddr)) {
|
||||
remoteAddr = request.getHeader("Proxy-Client-IP");
|
||||
} else if (isNotBlank(remoteAddr)) {
|
||||
remoteAddr = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰命名法工具
|
||||
*
|
||||
* @return toCamelCase("hello_world") == "helloWorld"
|
||||
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
|
||||
* toUnderScoreCase("helloWorld") = "hello_world"
|
||||
*/
|
||||
public static String toCamelCase(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
s = s.toLowerCase();
|
||||
|
||||
StringBuilder sb = new StringBuilder(s.length());
|
||||
boolean upperCase = false;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
|
||||
if (c == SEPARATOR) {
|
||||
upperCase = true;
|
||||
} else if (upperCase) {
|
||||
sb.append(Character.toUpperCase(c));
|
||||
upperCase = false;
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰命名法工具
|
||||
*
|
||||
* @return toCamelCase("hello_world") == "helloWorld"
|
||||
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
|
||||
* toUnderScoreCase("helloWorld") = "hello_world"
|
||||
*/
|
||||
public static String toCapitalizeCamelCase(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
s = toCamelCase(s);
|
||||
return s.substring(0, 1).toUpperCase() + s.substring(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰命名法工具
|
||||
*
|
||||
* @return toCamelCase("hello_world") == "helloWorld"
|
||||
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
|
||||
* toUnderScoreCase("helloWorld") = "hello_world"
|
||||
*/
|
||||
public static String toUnderScoreCase(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean upperCase = false;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
|
||||
boolean nextUpperCase = true;
|
||||
|
||||
if (i < (s.length() - 1)) {
|
||||
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
|
||||
}
|
||||
|
||||
if ((i > 0) && Character.isUpperCase(c)) {
|
||||
if (!upperCase || !nextUpperCase) {
|
||||
sb.append(SEPARATOR);
|
||||
}
|
||||
upperCase = true;
|
||||
} else {
|
||||
upperCase = false;
|
||||
}
|
||||
|
||||
sb.append(Character.toLowerCase(c));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果不为空,则设置值
|
||||
*
|
||||
* @param target
|
||||
* @param source
|
||||
*/
|
||||
public static void setValueIfNotBlank(String target, String source) {
|
||||
if (isNotBlank(source)) {
|
||||
target = source;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为JS获取对象值,生成三目运算返回结果
|
||||
*
|
||||
* @param objectString
|
||||
* 对象串 例如:row.user.id
|
||||
* 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id
|
||||
*/
|
||||
public static String jsGetVal(String objectString) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
StringBuilder val = new StringBuilder();
|
||||
String[] vals = split(objectString, ".");
|
||||
for (int i = 0; i < vals.length; i++) {
|
||||
val.append("." + vals[i]);
|
||||
result.append("!" + (val.substring(1)) + "?'':");
|
||||
}
|
||||
result.append(val.substring(1));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成安全的密码,生成随机的16位salt并经过1024次 sha-1 hash
|
||||
*/
|
||||
public static String entryptPassword(String plainPassword) {
|
||||
byte[] salt = Digests.generateSalt(SALT_SIZE);
|
||||
byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
|
||||
return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证密码
|
||||
*
|
||||
* @param plainPassword
|
||||
* 明文密码
|
||||
* @param password
|
||||
* 密文密码
|
||||
* @return 验证成功返回true
|
||||
*/
|
||||
public static boolean validatePassword(String plainPassword, String password) {
|
||||
byte[] salt = Encodes.decodeHex(password.substring(0, 16));
|
||||
byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
|
||||
return password.equals(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取上传文件的根目录
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static String getUserfilesBaseDir() {
|
||||
String dir = Configurations.getStringProperty("userfiles.basedir", "");
|
||||
try {
|
||||
if (StringUtils.isBlank(dir)) {
|
||||
dir = ServletContextFactory.getServletContext().getRealPath("/");
|
||||
} else {
|
||||
dir = ServletContextFactory.getServletContext().getRealPath("/") + dir;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (!dir.endsWith("/")) {
|
||||
dir += "/";
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <p>
|
||||
* 判断字符串是否为空. 为空条件:全角\半角\tab 等没有实际意义的字符.
|
||||
* 具体参看{@link Character#isWhitespace(char)}对空格的定义.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.isBlank(" ") = true 为半角空格
|
||||
* StringUtils.isBlank(" ") = true 为全角空格
|
||||
* StringUtils.isBlank(" ") = true 为tab键
|
||||
* </pre>
|
||||
*
|
||||
* @param str
|
||||
* 字符串
|
||||
* @return <code>true<code> 字符串为空 ,<code>false</code> 不为空
|
||||
*/
|
||||
public static boolean strIsBlank(String str) {
|
||||
int strLen;
|
||||
if (str == null || (strLen = str.length()) == 0) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0; i < strLen; i++) {
|
||||
if ((Character.isWhitespace(str.charAt(i)) == false)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
83
src/main/java/com/nis/util/TreeUtil.java
Normal file
83
src/main/java/com/nis/util/TreeUtil.java
Normal file
@@ -0,0 +1,83 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.nis.domain.SysMenu;
|
||||
import com.nis.web.security.UserUtils;
|
||||
|
||||
/**
|
||||
* 将树构建成上下层结构
|
||||
* @author Administrator
|
||||
*
|
||||
*/
|
||||
public final class TreeUtil {
|
||||
|
||||
private List<SysMenu> menuList = new ArrayList<SysMenu>();
|
||||
|
||||
public TreeUtil(List<SysMenu> menuList) {
|
||||
this.menuList = menuList;
|
||||
}
|
||||
|
||||
public List<SysMenu> buildTree(){
|
||||
List<SysMenu> newMenuList = new ArrayList<SysMenu>();
|
||||
|
||||
for (SysMenu menu : menuList) {
|
||||
if (menu.getParent().getId().equals(1l)) {
|
||||
if (isBusinessOfAdmin(menu.getName())) {
|
||||
continue;
|
||||
}
|
||||
build(menu);
|
||||
newMenuList.add(menu);
|
||||
}
|
||||
}
|
||||
|
||||
return newMenuList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤admin的业务功能
|
||||
* @return
|
||||
*/
|
||||
private boolean isBusinessOfAdmin(String menuName) {
|
||||
if (UserUtils.getUser().isAdmin()
|
||||
&& menuName.equals(Constants.SYS_BUSINESS_MENU_NAME) ) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void build(SysMenu rootMenu) {
|
||||
|
||||
List<SysMenu> children = getChildren(rootMenu);
|
||||
|
||||
if ( !StringUtil.isEmpty(children) ) {
|
||||
rootMenu.setChildren(children);
|
||||
for (SysMenu child : children) {
|
||||
if (StringUtils.isBlank(child.getHref())) { //根据url是否为空判断结束
|
||||
build(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private List<SysMenu> getChildren(SysMenu rootMenu){
|
||||
|
||||
List<SysMenu> children = new ArrayList<SysMenu>();
|
||||
|
||||
for(SysMenu child : menuList) {
|
||||
if (rootMenu.getId().equals(child.getParent().getId())) {
|
||||
children.add(child);
|
||||
}
|
||||
}
|
||||
|
||||
return children;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
*@Title: ElasticsearchSqlUtil.java
|
||||
*@Package com.nis.util
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年10月17日 下午4:09:17
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.util.elasticsearch;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.ibatis.mapping.ResultMap;
|
||||
import org.apache.ibatis.mapping.ResultMapping;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import com.nis.domain.LogEntity;
|
||||
import com.nis.domain.Page;
|
||||
import com.nis.util.Constants;
|
||||
import com.nis.util.JsonMapper;
|
||||
import com.nis.util.StringUtil;
|
||||
import com.nis.util.StringUtils;
|
||||
import com.nis.util.httpclient.HttpClientUtil;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
/**
|
||||
* @ClassName: ElasticsearchSqlUtil.java
|
||||
* @Description: 在service中替代oracle查询
|
||||
* @author (wx)
|
||||
* @date 2016年10月17日 下午4:09:17
|
||||
* @version V1.0
|
||||
*/
|
||||
@SuppressWarnings({"unchecked","rawtypes"})
|
||||
public class ElasticsearchSqlDao {
|
||||
private static final Logger logger=Logger.getLogger(ElasticsearchSqlDao.class);
|
||||
private static final SqlSessionFactory sqlSessionFactory=SpringContextHolder.getBean(SqlSessionFactory.class);
|
||||
private static final Map<Class,Map<String,String>> fieldsMapMap=new HashMap<>();
|
||||
public void init(Class clazz){
|
||||
Map<String,String> fieldsMap=new HashMap<>();
|
||||
ResultMap data=sqlSessionFactory.getConfiguration().getResultMap(clazz.getSimpleName()+"Map");
|
||||
List<ResultMapping> mappingList=data.getResultMappings();
|
||||
for(ResultMapping map:mappingList){
|
||||
fieldsMap.put(map.getColumn().toUpperCase(), map.getProperty());
|
||||
}
|
||||
fieldsMapMap.put(clazz, fieldsMap);
|
||||
}
|
||||
/**
|
||||
* 获取elasticsearch中的mapping field
|
||||
* getSearchFields(这里用一句话描述这个方法的作用)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param page
|
||||
* @param clazz
|
||||
* @return
|
||||
*List<String>
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
private String getSearchFields(Page<?> page,Class<?> clazz){
|
||||
String fields=page.getFields();
|
||||
|
||||
if(StringUtil.isBlank(fields)){
|
||||
fields="*";
|
||||
}else{
|
||||
String[] fieldArray=fields.split(",");
|
||||
for(String field :fieldArray){
|
||||
if(fieldsMapMap.get(clazz).containsKey(field.toUpperCase())){
|
||||
fields=fields.replace(field, fieldsMapMap.get(clazz).get(field.toUpperCase()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getWhereCondition(where 条件转换)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param entity
|
||||
* @param givenDateFormat
|
||||
* @return
|
||||
* @throws ParseException
|
||||
* @throws IllegalArgumentException
|
||||
* @throws IllegalAccessException
|
||||
*String
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
private String getWhereCondition(LogEntity<?> entity,SimpleDateFormat givenDateFormat) throws ParseException, IllegalArgumentException, IllegalAccessException{
|
||||
StringBuffer where=new StringBuffer();
|
||||
//使用反射获取entity的所有字段值
|
||||
Class clazz=entity.getClass();
|
||||
List<Field> fieldList=new ArrayList<Field>();
|
||||
fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
|
||||
fieldList.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
|
||||
|
||||
for(Field field:fieldList){
|
||||
if(Modifier.isFinal(field.getModifiers()))continue;
|
||||
if(Modifier.isPrivate(field.getModifiers())||Modifier.isProtected(field.getModifiers())){
|
||||
field.setAccessible(true);
|
||||
}
|
||||
String type=field.getType().getSimpleName();
|
||||
Object value=field.get(entity);
|
||||
if(value==null)continue;
|
||||
if(field.getName().endsWith("StartTime")){
|
||||
String startTime=value.toString();
|
||||
if(!StringUtil.isBlank(startTime)){
|
||||
String fieldName=field.getName()
|
||||
.replace("search", "")
|
||||
.replace("Start", "");
|
||||
fieldName=fieldName.replace(fieldName.substring(0, 1),fieldName.substring(0, 1).toLowerCase());
|
||||
where.append(" AND "+fieldName +">=");
|
||||
where.append(givenDateFormat.parse(startTime).getTime()/1000);
|
||||
|
||||
}
|
||||
}else if(field.getName().endsWith("EndTime")){
|
||||
String endTime=value.toString();
|
||||
if(!StringUtil.isBlank(endTime)){
|
||||
String fieldName=field.getName()
|
||||
.replace("search", "")
|
||||
.replace("End", "");
|
||||
fieldName=fieldName.replace(fieldName.substring(0, 1),fieldName.substring(0, 1).toLowerCase());
|
||||
where.append(" AND "+fieldName +"<");
|
||||
where.append(givenDateFormat.parse(endTime).getTime()/1000);
|
||||
|
||||
}
|
||||
}else{
|
||||
String fieldName=field.getName().replace("search", "");
|
||||
fieldName=fieldName.replace(fieldName.substring(0, 1),fieldName.substring(0, 1).toLowerCase());
|
||||
if(fieldsMapMap.get(clazz).containsValue(fieldName)){
|
||||
if("Date".equals(type)){
|
||||
Date date=(Date)value;
|
||||
where.append(" AND "+fieldName+"=");
|
||||
where.append(date.getTime()/1000);
|
||||
}else{
|
||||
where.append(" AND "+fieldName +"=");
|
||||
where.append("'"+value.toString()+"'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
where.delete(0, " AND ".length());
|
||||
return where.toString().trim();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getOderbys(排序转换)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param page
|
||||
* @param clazz
|
||||
* @return
|
||||
*String
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
private String getOderbys(Page page,Class clazz){
|
||||
String orderBy=page.getOrderBy();
|
||||
for(String field :orderBy.split(" ")){
|
||||
if(fieldsMapMap.get(clazz).containsKey(field.toUpperCase())){
|
||||
orderBy=orderBy.replace(field, fieldsMapMap.get(clazz).get(field.toUpperCase()));
|
||||
}
|
||||
}
|
||||
return orderBy;
|
||||
|
||||
}
|
||||
|
||||
public String geneEs4SQL(Class clazz,Page<?> page,LogEntity<?> entity) throws ParseException, IllegalArgumentException, IllegalAccessException{
|
||||
if(!fieldsMapMap.containsKey(clazz)){
|
||||
this.init(clazz);
|
||||
}
|
||||
SimpleDateFormat givenDateFormat=new SimpleDateFormat(Constants.SEARCH_DATEFORMAT);
|
||||
String indexName=clazz.getSimpleName().toUpperCase();
|
||||
String fields=getSearchFields(page, clazz);
|
||||
String where=getWhereCondition(entity, givenDateFormat);
|
||||
where=StringUtils.isBlank(where)?" ":" where "+where;
|
||||
String groupBy="";
|
||||
String orderBy=getOderbys(page,clazz);
|
||||
orderBy=StringUtils.isBlank(orderBy)?" ":" ORDER BY "+orderBy;
|
||||
String pageInfo=getPageInfo(page);
|
||||
String sql="SELECT "+fields+
|
||||
" FROM "+indexName+where+groupBy+orderBy+pageInfo;
|
||||
logger.info("es-sql:"+sql);
|
||||
return sql.replaceAll(" ", "%20").replaceAll("<", "%3C").replaceAll(">", "%3E");
|
||||
}
|
||||
public String search(LogEntity<?> entity,String acticeSys) throws ParseException, IllegalArgumentException, IllegalAccessException, ClientProtocolException, IOException{
|
||||
String sql=geneEs4SQL(entity.getClass(),entity.getPage(),entity);
|
||||
if(acticeSys.equals(Constants.ACTIVESYS_C)){
|
||||
logger.info("查询C版ES");
|
||||
return HttpClientUtil.get("http://"+Constants.SEARCH_ES_HOSTANDPORT_C+"/_sql?sql="+sql);
|
||||
}else if(acticeSys.equals(Constants.ACTIVESYS_A)){
|
||||
logger.info("查询A版ES");
|
||||
return HttpClientUtil.get("http://"+Constants.SEARCH_ES_HOSTANDPORT_A+"/_sql?sql="+sql);
|
||||
}else{
|
||||
logger.info("查询B版ES");
|
||||
return HttpClientUtil.get("http://"+Constants.SEARCH_ES_HOSTANDPORT_B+"/_sql?sql="+sql);
|
||||
}
|
||||
}
|
||||
private String getPageInfo(Page page){
|
||||
int pageNo=page.getPageNo();
|
||||
int pageSize=page.getPageSize();
|
||||
return " limit "+(pageNo-1)*pageSize+", "+page.getPageSize();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* findLogs(查询方法)
|
||||
* (初始化好list 之后传入方法,查询结果会加入到list中)
|
||||
* @param logList
|
||||
* @param esHostAndPort
|
||||
* @param log
|
||||
* @param givenFormat
|
||||
* @throws ParseException
|
||||
* @throws JSONException
|
||||
* @throws IllegalArgumentException
|
||||
* @throws IllegalAccessException
|
||||
*void
|
||||
* @throws IOException
|
||||
* @throws ClientProtocolException
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void findLogs(List logList,LogEntity<?> log,String activeSys) throws ParseException, JSONException, IllegalArgumentException, IllegalAccessException, ClientProtocolException, IOException{
|
||||
Class clazz=log.getClass();
|
||||
JSONObject obj=new JSONObject(search(log,activeSys));
|
||||
long count=obj.getJSONObject("hits").getLong("total");
|
||||
long took=obj.getLong("took");
|
||||
logger.info("search by es cost: "+took+"ms");
|
||||
log.getPage().setCount(count);
|
||||
if(count>0){
|
||||
JSONArray resultJson=obj.getJSONObject("hits").getJSONArray("hits");
|
||||
for(int i=0;i<resultJson.length();i++){
|
||||
JSONObject re=(JSONObject)resultJson.get(i);
|
||||
JSONObject json=re.getJSONObject("_source");
|
||||
Iterator it=json.keys();
|
||||
//找出时间字段,由于中心时间戳没有存毫秒,在这里转换时间的时候需要将10位的时间戳转换为13位的时间戳
|
||||
//默认以Time结尾的字段为时间字段
|
||||
while(it.hasNext()){
|
||||
String key=it.next().toString();
|
||||
if(key.endsWith("Time")&&json.has(key)&&!json.isNull(key)){
|
||||
long time=json.getLong(key);
|
||||
if(String.valueOf(time).length()==10){
|
||||
json.put(key, time*1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
logList.add(JsonMapper.fromJsonString(json.toString(), clazz));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
/**
|
||||
* main(这里用一句话描述这个方法的作用)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param args
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
// TODO Auto-generated method stub
|
||||
StringBuffer sf=new StringBuffer(" AND 1=1");
|
||||
System.out.println(sf.delete(0, " AND".length()).toString());
|
||||
}
|
||||
|
||||
}
|
||||
59
src/main/java/com/nis/util/excel/ExcelField.java
Normal file
59
src/main/java/com/nis/util/excel/ExcelField.java
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util.excel;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Excel注解定义
|
||||
* @author ThinkGem
|
||||
* @version 2013-03-10
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface ExcelField {
|
||||
|
||||
/**
|
||||
* 导出字段名(默认调用当前字段的“get”方法,如指定导出字段为对象,请填写“对象名.对象属性”,例:“area.name”、“office.name”)
|
||||
*/
|
||||
String value() default "";
|
||||
|
||||
/**
|
||||
* 导出字段标题(需要添加批注请用“**”分隔,标题**批注,仅对导出模板有效)
|
||||
*/
|
||||
String title();
|
||||
|
||||
/**
|
||||
* 字段类型(0:导出导入;1:仅导出;2:仅导入)
|
||||
*/
|
||||
int type() default 0;
|
||||
|
||||
/**
|
||||
* 导出字段对齐方式(0:自动;1:靠左;2:居中;3:靠右)
|
||||
*/
|
||||
int align() default 0;
|
||||
|
||||
/**
|
||||
* 导出字段字段排序(升序)
|
||||
*/
|
||||
int sort() default 0;
|
||||
|
||||
/**
|
||||
* 如果是字典类型,请设置字典的type值
|
||||
*/
|
||||
String dictType() default "";
|
||||
|
||||
/**
|
||||
* 反射类型
|
||||
*/
|
||||
Class<?> fieldType() default Class.class;
|
||||
|
||||
/**
|
||||
* 字段归属组(根据分组导出导入)
|
||||
*/
|
||||
int[] groups() default {};
|
||||
}
|
||||
476
src/main/java/com/nis/util/excel/ExportExcel.java
Normal file
476
src/main/java/com/nis/util/excel/ExportExcel.java
Normal file
@@ -0,0 +1,476 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util.excel;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.Comment;
|
||||
import org.apache.poi.ss.usermodel.DataFormat;
|
||||
import org.apache.poi.ss.usermodel.Font;
|
||||
import org.apache.poi.ss.usermodel.IndexedColors;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
|
||||
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.util.DictUtils;
|
||||
import com.nis.util.Encodes;
|
||||
import com.nis.util.Reflections;
|
||||
|
||||
/**
|
||||
* 导出Excel文件(导出“XLSX”格式,支持大数据量导出 @see org.apache.poi.ss.SpreadsheetVersion)
|
||||
* @author ThinkGem
|
||||
* @version 2013-04-21
|
||||
*/
|
||||
public class ExportExcel {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
|
||||
|
||||
/**
|
||||
* 工作薄对象
|
||||
*/
|
||||
private SXSSFWorkbook wb;
|
||||
|
||||
/**
|
||||
* 工作表对象
|
||||
*/
|
||||
private Sheet sheet;
|
||||
|
||||
/**
|
||||
* 样式列表
|
||||
*/
|
||||
private Map<String, CellStyle> styles;
|
||||
|
||||
/**
|
||||
* 当前行号
|
||||
*/
|
||||
private int rownum;
|
||||
|
||||
/**
|
||||
* 注解列表(Object[]{ ExcelField, Field/Method })
|
||||
*/
|
||||
List<Object[]> annotationList = Lists.newArrayList();
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param title 表格标题,传“空值”,表示无标题
|
||||
* @param cls 实体对象,通过annotation.ExportField获取标题
|
||||
*/
|
||||
public ExportExcel(String title, Class<?> cls){
|
||||
this(title, cls, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param title 表格标题,传“空值”,表示无标题
|
||||
* @param cls 实体对象,通过annotation.ExportField获取标题
|
||||
* @param type 导出类型(1:导出数据;2:导出模板)
|
||||
* @param groups 导入分组
|
||||
*/
|
||||
public ExportExcel(String title, Class<?> cls, int type, int... groups){
|
||||
// Get annotation field
|
||||
Field[] fs = cls.getDeclaredFields();
|
||||
for (Field f : fs){
|
||||
ExcelField ef = f.getAnnotation(ExcelField.class);
|
||||
if (ef != null && (ef.type()==0 || ef.type()==type)){
|
||||
if (groups!=null && groups.length>0){
|
||||
boolean inGroup = false;
|
||||
for (int g : groups){
|
||||
if (inGroup){
|
||||
break;
|
||||
}
|
||||
for (int efg : ef.groups()){
|
||||
if (g == efg){
|
||||
inGroup = true;
|
||||
annotationList.add(new Object[]{ef, f});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}else{
|
||||
annotationList.add(new Object[]{ef, f});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Get annotation method
|
||||
Method[] ms = cls.getDeclaredMethods();
|
||||
for (Method m : ms){
|
||||
ExcelField ef = m.getAnnotation(ExcelField.class);
|
||||
if (ef != null && (ef.type()==0 || ef.type()==type)){
|
||||
if (groups!=null && groups.length>0){
|
||||
boolean inGroup = false;
|
||||
for (int g : groups){
|
||||
if (inGroup){
|
||||
break;
|
||||
}
|
||||
for (int efg : ef.groups()){
|
||||
if (g == efg){
|
||||
inGroup = true;
|
||||
annotationList.add(new Object[]{ef, m});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}else{
|
||||
annotationList.add(new Object[]{ef, m});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Field sorting
|
||||
Collections.sort(annotationList, new Comparator<Object[]>() {
|
||||
public int compare(Object[] o1, Object[] o2) {
|
||||
return new Integer(((ExcelField)o1[0]).sort()).compareTo(
|
||||
new Integer(((ExcelField)o2[0]).sort()));
|
||||
};
|
||||
});
|
||||
// Initialize
|
||||
List<String> headerList = Lists.newArrayList();
|
||||
for (Object[] os : annotationList){
|
||||
String t = ((ExcelField)os[0]).title();
|
||||
// 如果是导出,则去掉注释
|
||||
if (type==1){
|
||||
String[] ss = StringUtils.split(t, "**", 2);
|
||||
if (ss.length==2){
|
||||
t = ss[0];
|
||||
}
|
||||
}
|
||||
headerList.add(t);
|
||||
}
|
||||
initialize(title, headerList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param title 表格标题,传“空值”,表示无标题
|
||||
* @param headers 表头数组
|
||||
*/
|
||||
public ExportExcel(String title, String[] headers) {
|
||||
initialize(title, Lists.newArrayList(headers));
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param title 表格标题,传“空值”,表示无标题
|
||||
* @param headerList 表头列表
|
||||
*/
|
||||
public ExportExcel(String title, List<String> headerList) {
|
||||
initialize(title, headerList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化函数
|
||||
* @param title 表格标题,传“空值”,表示无标题
|
||||
* @param headerList 表头列表
|
||||
*/
|
||||
private void initialize(String title, List<String> headerList) {
|
||||
this.wb = new SXSSFWorkbook(500);
|
||||
this.sheet = wb.createSheet("Export");
|
||||
this.styles = createStyles(wb);
|
||||
// Create title
|
||||
if (StringUtils.isNotBlank(title)){
|
||||
Row titleRow = sheet.createRow(rownum++);
|
||||
titleRow.setHeightInPoints(30);
|
||||
Cell titleCell = titleRow.createCell(0);
|
||||
titleCell.setCellStyle(styles.get("title"));
|
||||
titleCell.setCellValue(title);
|
||||
sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
|
||||
titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
|
||||
}
|
||||
// Create header
|
||||
if (headerList == null){
|
||||
throw new RuntimeException("headerList not null!");
|
||||
}
|
||||
Row headerRow = sheet.createRow(rownum++);
|
||||
headerRow.setHeightInPoints(16);
|
||||
for (int i = 0; i < headerList.size(); i++) {
|
||||
Cell cell = headerRow.createCell(i);
|
||||
cell.setCellStyle(styles.get("header"));
|
||||
String[] ss = StringUtils.split(headerList.get(i), "**", 2);
|
||||
if (ss.length==2){
|
||||
cell.setCellValue(ss[0]);
|
||||
Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
|
||||
new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
|
||||
comment.setString(new XSSFRichTextString(ss[1]));
|
||||
cell.setCellComment(comment);
|
||||
}else{
|
||||
cell.setCellValue(headerList.get(i));
|
||||
}
|
||||
sheet.autoSizeColumn(i);
|
||||
}
|
||||
for (int i = 0; i < headerList.size(); i++) {
|
||||
int colWidth = sheet.getColumnWidth(i)*2;
|
||||
sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
|
||||
}
|
||||
log.debug("Initialize success.");
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建表格样式
|
||||
* @param wb 工作薄对象
|
||||
* @return 样式列表
|
||||
*/
|
||||
private Map<String, CellStyle> createStyles(Workbook wb) {
|
||||
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
|
||||
|
||||
CellStyle style = wb.createCellStyle();
|
||||
style.setAlignment(CellStyle.ALIGN_CENTER);
|
||||
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
|
||||
Font titleFont = wb.createFont();
|
||||
titleFont.setFontName("Arial");
|
||||
titleFont.setFontHeightInPoints((short) 16);
|
||||
titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
|
||||
style.setFont(titleFont);
|
||||
styles.put("title", style);
|
||||
|
||||
style = wb.createCellStyle();
|
||||
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
|
||||
style.setBorderRight(CellStyle.BORDER_THIN);
|
||||
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
style.setBorderLeft(CellStyle.BORDER_THIN);
|
||||
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
style.setBorderTop(CellStyle.BORDER_THIN);
|
||||
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
style.setBorderBottom(CellStyle.BORDER_THIN);
|
||||
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
Font dataFont = wb.createFont();
|
||||
dataFont.setFontName("Arial");
|
||||
dataFont.setFontHeightInPoints((short) 10);
|
||||
style.setFont(dataFont);
|
||||
styles.put("data", style);
|
||||
|
||||
style = wb.createCellStyle();
|
||||
style.cloneStyleFrom(styles.get("data"));
|
||||
style.setAlignment(CellStyle.ALIGN_LEFT);
|
||||
styles.put("data1", style);
|
||||
|
||||
style = wb.createCellStyle();
|
||||
style.cloneStyleFrom(styles.get("data"));
|
||||
style.setAlignment(CellStyle.ALIGN_CENTER);
|
||||
styles.put("data2", style);
|
||||
|
||||
style = wb.createCellStyle();
|
||||
style.cloneStyleFrom(styles.get("data"));
|
||||
style.setAlignment(CellStyle.ALIGN_RIGHT);
|
||||
styles.put("data3", style);
|
||||
|
||||
style = wb.createCellStyle();
|
||||
style.cloneStyleFrom(styles.get("data"));
|
||||
// style.setWrapText(true);
|
||||
style.setAlignment(CellStyle.ALIGN_CENTER);
|
||||
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
|
||||
Font headerFont = wb.createFont();
|
||||
headerFont.setFontName("Arial");
|
||||
headerFont.setFontHeightInPoints((short) 10);
|
||||
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
|
||||
headerFont.setColor(IndexedColors.WHITE.getIndex());
|
||||
style.setFont(headerFont);
|
||||
styles.put("header", style);
|
||||
|
||||
return styles;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一行
|
||||
* @return 行对象
|
||||
*/
|
||||
public Row addRow(){
|
||||
return sheet.createRow(rownum++);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 添加一个单元格
|
||||
* @param row 添加的行
|
||||
* @param column 添加列号
|
||||
* @param val 添加值
|
||||
* @return 单元格对象
|
||||
*/
|
||||
public Cell addCell(Row row, int column, Object val){
|
||||
return this.addCell(row, column, val, 0, Class.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一个单元格
|
||||
* @param row 添加的行
|
||||
* @param column 添加列号
|
||||
* @param val 添加值
|
||||
* @param align 对齐方式(1:靠左;2:居中;3:靠右)
|
||||
* @return 单元格对象
|
||||
*/
|
||||
public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType){
|
||||
Cell cell = row.createCell(column);
|
||||
CellStyle style = styles.get("data"+(align>=1&&align<=3?align:""));
|
||||
try {
|
||||
if (val == null){
|
||||
cell.setCellValue("");
|
||||
} else if (val instanceof String) {
|
||||
cell.setCellValue((String) val);
|
||||
} else if (val instanceof Integer) {
|
||||
cell.setCellValue((Integer) val);
|
||||
} else if (val instanceof Long) {
|
||||
cell.setCellValue((Long) val);
|
||||
} else if (val instanceof Double) {
|
||||
cell.setCellValue((Double) val);
|
||||
} else if (val instanceof Float) {
|
||||
cell.setCellValue((Float) val);
|
||||
} else if (val instanceof Date) {
|
||||
DataFormat format = wb.createDataFormat();
|
||||
style.setDataFormat(format.getFormat("yyyy-MM-dd"));
|
||||
cell.setCellValue((Date) val);
|
||||
} else {
|
||||
if (fieldType != Class.class){
|
||||
cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val));
|
||||
}else{
|
||||
cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
|
||||
"fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val));
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString());
|
||||
cell.setCellValue(val.toString());
|
||||
}
|
||||
cell.setCellStyle(style);
|
||||
return cell;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加数据(通过annotation.ExportField添加数据)
|
||||
* @return list 数据列表
|
||||
*/
|
||||
public <E> ExportExcel setDataList(List<E> list){
|
||||
for (E e : list){
|
||||
int colunm = 0;
|
||||
Row row = this.addRow();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object[] os : annotationList){
|
||||
ExcelField ef = (ExcelField)os[0];
|
||||
Object val = null;
|
||||
// Get entity value
|
||||
try{
|
||||
if (StringUtils.isNotBlank(ef.value())){
|
||||
val = Reflections.invokeGetter(e, ef.value());
|
||||
}else{
|
||||
if (os[1] instanceof Field){
|
||||
val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
|
||||
}else if (os[1] instanceof Method){
|
||||
val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
|
||||
}
|
||||
}
|
||||
// If is dict, get dict label
|
||||
if (StringUtils.isNotBlank(ef.dictType())){
|
||||
val = DictUtils.getDictLabel(val==null?"":val.toString(), ef.dictType(), "");
|
||||
}
|
||||
}catch(Exception ex) {
|
||||
// Failure to ignore
|
||||
log.info(ex.toString());
|
||||
val = "";
|
||||
}
|
||||
this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
|
||||
sb.append(val + ", ");
|
||||
}
|
||||
log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString());
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出数据流
|
||||
* @param os 输出数据流
|
||||
*/
|
||||
public ExportExcel write(OutputStream os) throws IOException{
|
||||
wb.write(os);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出到客户端
|
||||
* @param fileName 输出文件名
|
||||
*/
|
||||
public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
|
||||
response.reset();
|
||||
response.setContentType("application/octet-stream; charset=utf-8");
|
||||
response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
|
||||
write(response.getOutputStream());
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出到文件
|
||||
* @param fileName 输出文件名
|
||||
*/
|
||||
public ExportExcel writeFile(String name) throws FileNotFoundException, IOException{
|
||||
FileOutputStream os = new FileOutputStream(name);
|
||||
this.write(os);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理临时文件
|
||||
*/
|
||||
public ExportExcel dispose(){
|
||||
wb.dispose();
|
||||
return this;
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 导出测试
|
||||
// */
|
||||
// public static void main(String[] args) throws Throwable {
|
||||
//
|
||||
// List<String> headerList = Lists.newArrayList();
|
||||
// for (int i = 1; i <= 10; i++) {
|
||||
// headerList.add("表头"+i);
|
||||
// }
|
||||
//
|
||||
// List<String> dataRowList = Lists.newArrayList();
|
||||
// for (int i = 1; i <= headerList.size(); i++) {
|
||||
// dataRowList.add("数据"+i);
|
||||
// }
|
||||
//
|
||||
// List<List<String>> dataList = Lists.newArrayList();
|
||||
// for (int i = 1; i <=1000000; i++) {
|
||||
// dataList.add(dataRowList);
|
||||
// }
|
||||
//
|
||||
// ExportExcel ee = new ExportExcel("表格标题", headerList);
|
||||
//
|
||||
// for (int i = 0; i < dataList.size(); i++) {
|
||||
// Row row = ee.addRow();
|
||||
// for (int j = 0; j < dataList.get(i).size(); j++) {
|
||||
// ee.addCell(row, j, dataList.get(i).get(j));
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// ee.writeFile("target/export.xlsx");
|
||||
//
|
||||
// ee.dispose();
|
||||
//
|
||||
// log.debug("Export success.");
|
||||
//
|
||||
// }
|
||||
|
||||
}
|
||||
369
src/main/java/com/nis/util/excel/ImportExcel.java
Normal file
369
src/main/java/com/nis/util/excel/ImportExcel.java
Normal file
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util.excel;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.util.DictUtils;
|
||||
import com.nis.util.Reflections;
|
||||
|
||||
/**
|
||||
* 导入Excel文件(支持“XLS”和“XLSX”格式)
|
||||
* @author ThinkGem
|
||||
* @version 2013-03-10
|
||||
*/
|
||||
public class ImportExcel {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
|
||||
|
||||
/**
|
||||
* 工作薄对象
|
||||
*/
|
||||
private Workbook wb;
|
||||
|
||||
/**
|
||||
* 工作表对象
|
||||
*/
|
||||
private Sheet sheet;
|
||||
|
||||
/**
|
||||
* 标题行号
|
||||
*/
|
||||
private int headerNum;
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param path 导入文件,读取第一个工作表
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(String fileName, int headerNum)
|
||||
throws InvalidFormatException, IOException {
|
||||
this(new File(fileName), headerNum);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param path 导入文件对象,读取第一个工作表
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(File file, int headerNum)
|
||||
throws InvalidFormatException, IOException {
|
||||
this(file, headerNum, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param path 导入文件
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @param sheetIndex 工作表编号
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(String fileName, int headerNum, int sheetIndex)
|
||||
throws InvalidFormatException, IOException {
|
||||
this(new File(fileName), headerNum, sheetIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param path 导入文件对象
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @param sheetIndex 工作表编号
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(File file, int headerNum, int sheetIndex)
|
||||
throws InvalidFormatException, IOException {
|
||||
this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param file 导入文件对象
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @param sheetIndex 工作表编号
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex)
|
||||
throws InvalidFormatException, IOException {
|
||||
this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param path 导入文件对象
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @param sheetIndex 工作表编号
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex)
|
||||
throws InvalidFormatException, IOException {
|
||||
if (StringUtils.isBlank(fileName)){
|
||||
throw new RuntimeException("导入文档为空!");
|
||||
}else if(fileName.toLowerCase().endsWith("xls")){
|
||||
this.wb = new HSSFWorkbook(is);
|
||||
}else if(fileName.toLowerCase().endsWith("xlsx")){
|
||||
this.wb = new XSSFWorkbook(is);
|
||||
}else{
|
||||
throw new RuntimeException("文档格式不正确!");
|
||||
}
|
||||
if (this.wb.getNumberOfSheets()<sheetIndex){
|
||||
throw new RuntimeException("文档中没有工作表!");
|
||||
}
|
||||
this.sheet = this.wb.getSheetAt(sheetIndex);
|
||||
this.headerNum = headerNum;
|
||||
log.debug("Initialize success.");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取行对象
|
||||
* @param rownum
|
||||
* @return
|
||||
*/
|
||||
public Row getRow(int rownum){
|
||||
return this.sheet.getRow(rownum);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据行号
|
||||
* @return
|
||||
*/
|
||||
public int getDataRowNum(){
|
||||
return headerNum+1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最后一个数据行号
|
||||
* @return
|
||||
*/
|
||||
public int getLastDataRowNum(){
|
||||
return this.sheet.getLastRowNum()+headerNum;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最后一个列号
|
||||
* @return
|
||||
*/
|
||||
public int getLastCellNum(){
|
||||
return this.getRow(headerNum).getLastCellNum();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单元格值
|
||||
* @param row 获取的行
|
||||
* @param column 获取单元格列号
|
||||
* @return 单元格值
|
||||
*/
|
||||
public Object getCellValue(Row row, int column){
|
||||
Object val = "";
|
||||
try{
|
||||
Cell cell = row.getCell(column);
|
||||
if (cell != null){
|
||||
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
|
||||
val = cell.getNumericCellValue();
|
||||
}else if (cell.getCellType() == Cell.CELL_TYPE_STRING){
|
||||
val = cell.getStringCellValue();
|
||||
}else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA){
|
||||
val = cell.getCellFormula();
|
||||
}else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
|
||||
val = cell.getBooleanCellValue();
|
||||
}else if (cell.getCellType() == Cell.CELL_TYPE_ERROR){
|
||||
val = cell.getErrorCellValue();
|
||||
}
|
||||
}
|
||||
}catch (Exception e) {
|
||||
return val;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取导入数据列表
|
||||
* @param cls 导入对象类型
|
||||
* @param groups 导入分组
|
||||
*/
|
||||
public <E> List<E> getDataList(Class<E> cls, int... groups) throws InstantiationException, IllegalAccessException{
|
||||
List<Object[]> annotationList = Lists.newArrayList();
|
||||
// Get annotation field
|
||||
Field[] fs = cls.getDeclaredFields();
|
||||
for (Field f : fs){
|
||||
ExcelField ef = f.getAnnotation(ExcelField.class);
|
||||
if (ef != null && (ef.type()==0 || ef.type()==2)){
|
||||
if (groups!=null && groups.length>0){
|
||||
boolean inGroup = false;
|
||||
for (int g : groups){
|
||||
if (inGroup){
|
||||
break;
|
||||
}
|
||||
for (int efg : ef.groups()){
|
||||
if (g == efg){
|
||||
inGroup = true;
|
||||
annotationList.add(new Object[]{ef, f});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}else{
|
||||
annotationList.add(new Object[]{ef, f});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Get annotation method
|
||||
Method[] ms = cls.getDeclaredMethods();
|
||||
for (Method m : ms){
|
||||
ExcelField ef = m.getAnnotation(ExcelField.class);
|
||||
if (ef != null && (ef.type()==0 || ef.type()==2)){
|
||||
if (groups!=null && groups.length>0){
|
||||
boolean inGroup = false;
|
||||
for (int g : groups){
|
||||
if (inGroup){
|
||||
break;
|
||||
}
|
||||
for (int efg : ef.groups()){
|
||||
if (g == efg){
|
||||
inGroup = true;
|
||||
annotationList.add(new Object[]{ef, m});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}else{
|
||||
annotationList.add(new Object[]{ef, m});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Field sorting
|
||||
Collections.sort(annotationList, new Comparator<Object[]>() {
|
||||
public int compare(Object[] o1, Object[] o2) {
|
||||
return new Integer(((ExcelField)o1[0]).sort()).compareTo(
|
||||
new Integer(((ExcelField)o2[0]).sort()));
|
||||
};
|
||||
});
|
||||
//log.debug("Import column count:"+annotationList.size());
|
||||
// Get excel data
|
||||
List<E> dataList = Lists.newArrayList();
|
||||
for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
|
||||
E e = (E)cls.newInstance();
|
||||
int column = 0;
|
||||
Row row = this.getRow(i);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object[] os : annotationList){
|
||||
Object val = this.getCellValue(row, column++);
|
||||
if (val != null){
|
||||
ExcelField ef = (ExcelField)os[0];
|
||||
// If is dict type, get dict value
|
||||
if (StringUtils.isNotBlank(ef.dictType())){
|
||||
val = DictUtils.getDictCode(ef.dictType(), val.toString(), "");
|
||||
//log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
|
||||
}
|
||||
// Get param type and type cast
|
||||
Class<?> valType = Class.class;
|
||||
if (os[1] instanceof Field){
|
||||
valType = ((Field)os[1]).getType();
|
||||
}else if (os[1] instanceof Method){
|
||||
Method method = ((Method)os[1]);
|
||||
if ("get".equals(method.getName().substring(0, 3))){
|
||||
valType = method.getReturnType();
|
||||
}else if("set".equals(method.getName().substring(0, 3))){
|
||||
valType = ((Method)os[1]).getParameterTypes()[0];
|
||||
}
|
||||
}
|
||||
//log.debug("Import value type: ["+i+","+column+"] " + valType);
|
||||
try {
|
||||
if (valType == String.class){
|
||||
String s = String.valueOf(val.toString());
|
||||
if(StringUtils.endsWith(s, ".0")){
|
||||
val = StringUtils.substringBefore(s, ".0");
|
||||
}else{
|
||||
val = String.valueOf(val.toString());
|
||||
}
|
||||
}else if (valType == Integer.class){
|
||||
val = Double.valueOf(val.toString()).intValue();
|
||||
}else if (valType == Long.class){
|
||||
val = Double.valueOf(val.toString()).longValue();
|
||||
}else if (valType == Double.class){
|
||||
val = Double.valueOf(val.toString());
|
||||
}else if (valType == Float.class){
|
||||
val = Float.valueOf(val.toString());
|
||||
}else if (valType == Date.class){
|
||||
val = DateUtil.getJavaDate((Double)val);
|
||||
}else{
|
||||
if (ef.fieldType() != Class.class){
|
||||
val = ef.fieldType().getMethod("getValue", String.class).invoke(null, val.toString());
|
||||
}else{
|
||||
val = Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
|
||||
"fieldtype."+valType.getSimpleName()+"Type")).getMethod("getValue", String.class).invoke(null, val.toString());
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.info("Get cell value ["+i+","+column+"] error: " + ex.toString());
|
||||
val = null;
|
||||
}
|
||||
// set entity value
|
||||
if (os[1] instanceof Field){
|
||||
Reflections.invokeSetter(e, ((Field)os[1]).getName(), val);
|
||||
}else if (os[1] instanceof Method){
|
||||
String mthodName = ((Method)os[1]).getName();
|
||||
if ("get".equals(mthodName.substring(0, 3))){
|
||||
mthodName = "set"+StringUtils.substringAfter(mthodName, "get");
|
||||
}
|
||||
Reflections.invokeMethod(e, mthodName, new Class[] {valType}, new Object[] {val});
|
||||
}
|
||||
}
|
||||
sb.append(val+", ");
|
||||
}
|
||||
dataList.add(e);
|
||||
log.debug("Read success: ["+i+"] "+sb.toString());
|
||||
}
|
||||
return dataList;
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 导入测试
|
||||
// */
|
||||
// public static void main(String[] args) throws Throwable {
|
||||
//
|
||||
// ImportExcel ei = new ImportExcel("target/export.xlsx", 1);
|
||||
//
|
||||
// for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {
|
||||
// Row row = ei.getRow(i);
|
||||
// for (int j = 0; j < ei.getLastCellNum(); j++) {
|
||||
// Object val = ei.getCellValue(row, j);
|
||||
// System.out.print(val+", ");
|
||||
// }
|
||||
// System.out.print("\n");
|
||||
// }
|
||||
//
|
||||
// }
|
||||
|
||||
}
|
||||
44
src/main/java/com/nis/util/excel/fieldtype/RoleListType.java
Normal file
44
src/main/java/com/nis/util/excel/fieldtype/RoleListType.java
Normal file
@@ -0,0 +1,44 @@
|
||||
package com.nis.util.excel.fieldtype;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.domain.SysRole;
|
||||
import com.nis.util.Collections3;
|
||||
import com.nis.util.StringUtils;
|
||||
import com.nis.web.service.RoleService;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
public class RoleListType {
|
||||
|
||||
private static RoleService roleService = SpringContextHolder.getBean(RoleService.class);
|
||||
|
||||
/**
|
||||
* 获取对象值(导入)
|
||||
*/
|
||||
public static Object getValue(String val) {
|
||||
List<SysRole> roleList = Lists.newArrayList();
|
||||
List<SysRole> allRoleList = roleService.findAllRole();
|
||||
for (String s : StringUtils.split(val, ",")){
|
||||
for (SysRole e : allRoleList){
|
||||
if (StringUtils.trimToEmpty(s).equals(e.getName())){
|
||||
roleList.add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return roleList.size()>0?roleList:null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置对象值(导出)
|
||||
*/
|
||||
public static String setValue(Object val) {
|
||||
if (val != null){
|
||||
@SuppressWarnings("unchecked")
|
||||
List<SysRole> roleList = (List<SysRole>)val;
|
||||
return Collections3.extractToString(roleList, "name", ", ");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
}
|
||||
116
src/main/java/com/nis/util/httpclient/HttpClientUtil.java
Normal file
116
src/main/java/com/nis/util/httpclient/HttpClientUtil.java
Normal file
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
*@Title: HttpClientBean.java
|
||||
*@Package com.nis.util.httpclient
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年11月7日 下午2:36:26
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.util.httpclient;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
/**
|
||||
* @ClassName: HttpClientBean.java
|
||||
* @Description: TODO
|
||||
* @author (dell)
|
||||
* @date 2016年11月7日 下午2:36:26
|
||||
* @version V1.0
|
||||
*/
|
||||
public class HttpClientUtil {
|
||||
protected final Logger logger = Logger.getLogger(HttpClientUtil.class);
|
||||
/**
|
||||
* 处理get请求.
|
||||
* @param url 请求路径
|
||||
* @return json
|
||||
* @throws IOException
|
||||
* @throws ClientProtocolException
|
||||
*/
|
||||
public static String get(String url) throws ClientProtocolException, IOException{
|
||||
//实例化httpclient
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
//实例化get方法
|
||||
HttpGet httpget = new HttpGet(url);
|
||||
//请求结果
|
||||
CloseableHttpResponse response = null;
|
||||
String content ="";
|
||||
// try {
|
||||
//执行get方法
|
||||
response = httpclient.execute(httpget);
|
||||
// if(response.getStatusLine().getStatusCode()==200){
|
||||
content = EntityUtils.toString(response.getEntity(),"utf-8");
|
||||
// }
|
||||
// } catch (ClientProtocolException e) {
|
||||
// e.printStackTrace();
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
return content;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理post请求.
|
||||
* @param url 请求路径
|
||||
* @param params 参数
|
||||
* @return json
|
||||
* @throws IOException
|
||||
* @throws ClientProtocolException
|
||||
*/
|
||||
public String post(String url,Map<String, String> params) throws ClientProtocolException, IOException{
|
||||
//实例化httpClient
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
//实例化post方法
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
//处理参数
|
||||
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
|
||||
Set<String> keySet = params.keySet();
|
||||
for(String key : keySet) {
|
||||
nvps.add(new BasicNameValuePair(key, params.get(key)));
|
||||
}
|
||||
//结果
|
||||
CloseableHttpResponse response = null;
|
||||
String content="";
|
||||
// try {
|
||||
//提交的参数
|
||||
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
|
||||
//将参数给post方法
|
||||
httpPost.setEntity(uefEntity);
|
||||
//执行post方法
|
||||
response = httpclient.execute(httpPost);
|
||||
// if(response.getStatusLine().getStatusCode()==200){
|
||||
content = EntityUtils.toString(response.getEntity(),"utf-8");
|
||||
// System.out.println(content);
|
||||
// }
|
||||
// } catch (ClientProtocolException e) {
|
||||
// e.printStackTrace();
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
return content;
|
||||
}
|
||||
public static void main(String[] args) throws ClientProtocolException, IOException {
|
||||
HttpClientUtil hd = new HttpClientUtil();
|
||||
hd.get("http://10.0.6.115:9200/_sql?sql=select * from dfipportlog-2016-09-07-15 limit 1 10");
|
||||
Map<String,String> map = new HashMap();
|
||||
map.put("id","1");
|
||||
hd.post("http://localhost:8080/springMVC/menu/getChildren.do",map);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
*@Title: IdleConnectionEvictor.java
|
||||
*@Package com.nis.util.httpclient
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年11月7日 下午2:20:35
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.util.httpclient;
|
||||
|
||||
import org.apache.http.conn.HttpClientConnectionManager;
|
||||
|
||||
/**
|
||||
* @ClassName: IdleConnectionEvictor.java
|
||||
* @Description: TODO
|
||||
* @author (dell)
|
||||
* @date 2016年11月7日 下午2:20:35
|
||||
* @version V1.0
|
||||
*/
|
||||
public class IdleConnectionEvictor extends Thread{
|
||||
private final HttpClientConnectionManager connMgr;
|
||||
|
||||
private Integer waitTime;
|
||||
|
||||
private volatile boolean shutdown;
|
||||
|
||||
public IdleConnectionEvictor(HttpClientConnectionManager connMgr,Integer waitTime) {
|
||||
this.connMgr = connMgr;
|
||||
this.waitTime = waitTime;
|
||||
this.start();
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
while (!shutdown) {
|
||||
synchronized (this) {
|
||||
wait(waitTime);
|
||||
// 关闭失效的连接
|
||||
connMgr.closeExpiredConnections();
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException ex) {
|
||||
// 结束
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 销毁释放资源
|
||||
*/
|
||||
public void shutdown() {
|
||||
shutdown = true;
|
||||
synchronized (this) {
|
||||
notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
235
src/main/java/com/nis/util/redis/JedisClusterPipeline.java
Normal file
235
src/main/java/com/nis/util/redis/JedisClusterPipeline.java
Normal file
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* Copyright: Copyright (c) 2015
|
||||
*
|
||||
* @author youaremoon
|
||||
* @date 2016年6月25日
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.nis.util.redis;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
|
||||
import redis.clients.jedis.BinaryJedisCluster;
|
||||
import redis.clients.jedis.Client;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
import redis.clients.jedis.JedisClusterConnectionHandler;
|
||||
import redis.clients.jedis.JedisClusterInfoCache;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisSlotBasedConnectionHandler;
|
||||
import redis.clients.jedis.PipelineBase;
|
||||
import redis.clients.jedis.exceptions.JedisMovedDataException;
|
||||
import redis.clients.jedis.exceptions.JedisRedirectionException;
|
||||
import redis.clients.util.JedisClusterCRC16;
|
||||
import redis.clients.util.SafeEncoder;
|
||||
|
||||
/**
|
||||
* 在集群模式下提供批量操作的功能。 <br/>
|
||||
* 由于集群模式存在节点的动态添加删除,且client不能实时感知(只有在执行命令时才可能知道集群发生变更),
|
||||
* 因此,该实现不保证一定成功,建议在批量操作之前调用 refreshCluster() 方法重新获取集群信息。<br />
|
||||
* 应用需要保证不论成功还是失败都会调用close() 方法,否则可能会造成泄露。<br/>
|
||||
* 如果失败需要应用自己去重试,因此每个批次执行的命令数量需要控制。防止失败后重试的数量过多。<br />
|
||||
* 基于以上说明,建议在集群环境较稳定(增减节点不会过于频繁)的情况下使用,且允许失败或有对应的重试策略。<br />
|
||||
*
|
||||
* 该类非线程安全
|
||||
*
|
||||
* @author youaremoon
|
||||
* @version
|
||||
* @since Ver 1.1
|
||||
*/
|
||||
public class JedisClusterPipeline extends PipelineBase implements Closeable {
|
||||
// private static final Logger LOGGER = LoggerFactory.getLogger(JedisClusterPipeline.class);
|
||||
|
||||
// 部分字段没有对应的获取方法,只能采用反射来做
|
||||
// 你也可以去继承JedisCluster和JedisSlotBasedConnectionHandler来提供访问接口
|
||||
private static final Field FIELD_CONNECTION_HANDLER;
|
||||
private static final Field FIELD_CACHE;
|
||||
static {
|
||||
FIELD_CONNECTION_HANDLER = getField(BinaryJedisCluster.class, "connectionHandler");
|
||||
FIELD_CACHE = getField(JedisClusterConnectionHandler.class, "cache");
|
||||
}
|
||||
|
||||
private JedisSlotBasedConnectionHandler connectionHandler;
|
||||
private JedisClusterInfoCache clusterInfoCache;
|
||||
private Queue<Client> clients = new LinkedList<Client>(); // 根据顺序存储每个命令对应的Client
|
||||
private Map<JedisPool, Jedis> jedisMap = new HashMap<>(); // 用于缓存连接
|
||||
private boolean hasDataInBuf = false; // 是否有数据在缓存区
|
||||
|
||||
/**
|
||||
* 根据jedisCluster实例生成对应的JedisClusterPipeline
|
||||
* @param
|
||||
* @return
|
||||
*/
|
||||
public static JedisClusterPipeline pipelined(JedisCluster jedisCluster) {
|
||||
JedisClusterPipeline pipeline = new JedisClusterPipeline();
|
||||
pipeline.setJedisCluster(jedisCluster);
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
public JedisClusterPipeline() {
|
||||
}
|
||||
|
||||
public void setJedisCluster(JedisCluster jedis) {
|
||||
connectionHandler = getValue(jedis, FIELD_CONNECTION_HANDLER);
|
||||
clusterInfoCache = getValue(connectionHandler, FIELD_CACHE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新集群信息,当集群信息发生变更时调用
|
||||
* @param
|
||||
* @return
|
||||
*/
|
||||
public void refreshCluster() {
|
||||
connectionHandler.renewSlotCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步读取所有数据. 与syncAndReturnAll()相比,sync()只是没有对数据做反序列化
|
||||
*/
|
||||
public void sync() {
|
||||
innerSync(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步读取所有数据 并按命令顺序返回一个列表
|
||||
*
|
||||
* @return 按照命令的顺序返回所有的数据
|
||||
*/
|
||||
public List<Object> syncAndReturnAll() {
|
||||
List<Object> responseList = new ArrayList<Object>();
|
||||
|
||||
innerSync(responseList);
|
||||
|
||||
return responseList;
|
||||
}
|
||||
|
||||
private void innerSync(List<Object> formatted) {
|
||||
HashSet<Client> clientSet = new HashSet<Client>();
|
||||
|
||||
try {
|
||||
for (Client client : clients) {
|
||||
// 在sync()调用时其实是不需要解析结果数据的,但是如果不调用get方法,发生了JedisMovedDataException这样的错误应用是不知道的,因此需要调用get()来触发错误。
|
||||
// 其实如果Response的data属性可以直接获取,可以省掉解析数据的时间,然而它并没有提供对应方法,要获取data属性就得用反射,不想再反射了,所以就这样了
|
||||
Object data = generateResponse(client.getOne()).get();
|
||||
if (null != formatted) {
|
||||
formatted.add(data);
|
||||
}
|
||||
|
||||
// size相同说明所有的client都已经添加,就不用再调用add方法了
|
||||
if (clientSet.size() != jedisMap.size()) {
|
||||
clientSet.add(client);
|
||||
}
|
||||
}
|
||||
} catch (JedisRedirectionException jre) {
|
||||
if (jre instanceof JedisMovedDataException) {
|
||||
// if MOVED redirection occurred, rebuilds cluster's slot cache,
|
||||
// recommended by Redis cluster specification
|
||||
refreshCluster();
|
||||
}
|
||||
|
||||
throw jre;
|
||||
} finally {
|
||||
if (clientSet.size() != jedisMap.size()) {
|
||||
// 所有还没有执行过的client要保证执行(flush),防止放回连接池后后面的命令被污染
|
||||
for (Jedis jedis : jedisMap.values()) {
|
||||
if (clientSet.contains(jedis.getClient())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
flushCachedData(jedis);
|
||||
}
|
||||
}
|
||||
|
||||
hasDataInBuf = false;
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
clean();
|
||||
|
||||
clients.clear();
|
||||
|
||||
for (Jedis jedis : jedisMap.values()) {
|
||||
if (hasDataInBuf) {
|
||||
flushCachedData(jedis);
|
||||
}
|
||||
|
||||
jedis.close();
|
||||
}
|
||||
|
||||
jedisMap.clear();
|
||||
|
||||
hasDataInBuf = false;
|
||||
}
|
||||
|
||||
private void flushCachedData(Jedis jedis) {
|
||||
try {
|
||||
jedis.getClient().getAll();
|
||||
} catch (RuntimeException ex) {
|
||||
// 其中一个client出问题,后面出问题的几率较大
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Client getClient(String key) {
|
||||
byte[] bKey = SafeEncoder.encode(key);
|
||||
|
||||
return getClient(bKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Client getClient(byte[] key) {
|
||||
Jedis jedis = getJedis(JedisClusterCRC16.getSlot(key));
|
||||
|
||||
Client client = jedis.getClient();
|
||||
clients.add(client);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
private Jedis getJedis(int slot) {
|
||||
JedisPool pool = clusterInfoCache.getSlotPool(slot);
|
||||
|
||||
// 根据pool从缓存中获取Jedis
|
||||
Jedis jedis = jedisMap.get(pool);
|
||||
if (null == jedis) {
|
||||
jedis = pool.getResource();
|
||||
jedisMap.put(pool, jedis);
|
||||
}
|
||||
|
||||
hasDataInBuf = true;
|
||||
return jedis;
|
||||
}
|
||||
|
||||
private static Field getField(Class<?> cls, String fieldName) {
|
||||
try {
|
||||
Field field = cls.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
|
||||
return field;
|
||||
} catch (NoSuchFieldException | SecurityException e) {
|
||||
throw new RuntimeException("cannot find or access field '" + fieldName + "' from " + cls.getName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked" })
|
||||
private static <T> T getValue(Object obj, Field field) {
|
||||
try {
|
||||
return (T)field.get(obj);
|
||||
} catch (IllegalArgumentException | IllegalAccessException e) {
|
||||
// LOGGER.error("get value fail", e);
|
||||
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
458
src/main/java/com/nis/util/redis/RedisDao.java
Normal file
458
src/main/java/com/nis/util/redis/RedisDao.java
Normal file
@@ -0,0 +1,458 @@
|
||||
/**
|
||||
*@Title: RedisUtil.java
|
||||
*@Package com.nis.demo
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年9月13日 下午3:05:45
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.util.redis;
|
||||
import java.io.IOException;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
|
||||
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.nis.util.BeanHelper;
|
||||
import com.nis.util.Configurations;
|
||||
import com.nis.util.Constants;
|
||||
|
||||
import redis.clients.jedis.HostAndPort;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
|
||||
/**
|
||||
* @ClassName: RedisUtil.java
|
||||
* @Description: TODO
|
||||
* @author (wx)
|
||||
* @date 2016年9月13日 下午3:05:45
|
||||
* @version V1.0
|
||||
*/
|
||||
public class RedisDao {
|
||||
protected final Logger logger = Logger.getLogger(RedisDao.class);
|
||||
private JedisCluster cluster=null;
|
||||
private JedisClusterPipeline jcp=null;
|
||||
|
||||
public void initCluster(int type) throws Exception{
|
||||
if(cluster==null && Constants.IS_OPEN_REDIS){
|
||||
//初始化连接池配置
|
||||
GenericObjectPoolConfig config= getPoolConfig();
|
||||
//初始化节点信息
|
||||
Set<HostAndPort> jedisHostAndNodeSet= initNodes();
|
||||
int connectionTimeout=Configurations.getIntProperty("redis.cluster.connectiontimeout", 100);
|
||||
int soTimeout=Configurations.getIntProperty("redis.cluster.sotimeout", 100);
|
||||
int maxAttempts=Configurations.getIntProperty("redis.cluster.maxattempts", 3);
|
||||
//构造单例集群实例,其内部由多个节点构成,每个节点都有自己的连接池
|
||||
cluster=new JedisCluster(jedisHostAndNodeSet,connectionTimeout,soTimeout,maxAttempts,config);
|
||||
}
|
||||
logger.info("--------------------init redis cluster-----------");
|
||||
}
|
||||
/**
|
||||
* getJedisCluster(初始化redis的cluster)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
* @throws Exception
|
||||
*JedisCluster
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@PostConstruct
|
||||
public JedisCluster getJedisCluster() throws Exception{
|
||||
initCluster(0);
|
||||
return cluster;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* closeJedisCluster(关闭redis cluster的方法,在系统终止时使用)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @throws IOException
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@PreDestroy
|
||||
public void closeJedisCluster() throws IOException{
|
||||
if(cluster!=null)
|
||||
cluster.close();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getPoolConfig(初始化连接池的配置,这里可以设置很多参数的,不过目前没加)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
*GenericObjectPoolConfig
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
private GenericObjectPoolConfig getPoolConfig(){
|
||||
GenericObjectPoolConfig config=new GenericObjectPoolConfig();
|
||||
config.setMaxTotal(Configurations.getIntProperty("redis.pool.maxtotal", 500));//整个池的最大值
|
||||
config.setMaxIdle(Configurations.getIntProperty("redis.pool.maxidle", 100));//最大空闲
|
||||
config.setMaxWaitMillis(Configurations.getIntProperty("redis.pool.maxwaitmillis", -1));//获取不到永远等待
|
||||
config.setBlockWhenExhausted(Configurations.getBooleanProperty("redis.pool.blockwhenexhausted", true));
|
||||
config.setNumTestsPerEvictionRun(Configurations.getIntProperty("redis.pool.numtestsperevictionrun", Integer.MAX_VALUE));//always test all idle object
|
||||
config.setTestOnBorrow(Configurations.getBooleanProperty("redis.pool.testonborrow", true));
|
||||
config.setTestOnReturn(Configurations.getBooleanProperty("redis.pool.testonreturn", false));
|
||||
config.setTestWhileIdle(Configurations.getBooleanProperty("redis.pool.testwhileidle", true));//发呆过长时间是否先test一下
|
||||
config.setTimeBetweenEvictionRunsMillis(Configurations.getLongProperty("redis.pool.timebetweenevictionrunsmillis", 60000L));//-1不启动,默认1min一次
|
||||
config.setMinEvictableIdleTimeMillis(Configurations.getLongProperty("redis.pool.minevictableidletimemillis", 60000L));//可发呆的时间,10mins
|
||||
return config;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* initNodes(初始化节点信息)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
* @throws Exception
|
||||
*Set<HostAndPort>
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
private Set<HostAndPort> initNodes() throws Exception{
|
||||
String hostAndPorts=Configurations.getStringProperty("redis.cluster.host_port", null);
|
||||
if(hostAndPorts==null)
|
||||
throw new RuntimeException("配置文件中redis.cluster.host_port为空!");
|
||||
String[] hostAndPort=hostAndPorts.split(",");
|
||||
Set<HostAndPort> jedisClusterNodes=new HashSet<HostAndPort>();
|
||||
for(String host_port:hostAndPort){
|
||||
String [] _host_port=host_port.split(":");
|
||||
if(_host_port.length!=2)
|
||||
throw new RuntimeException("配置文件中redis.cluster.host_port格式不正确!");
|
||||
HostAndPort node=new HostAndPort(_host_port[0],Integer.parseInt(_host_port[1]));
|
||||
jedisClusterNodes.add(node);
|
||||
}
|
||||
return jedisClusterNodes;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getClusterNodes(获取redis集群中的所有节点,每个节点都是一个连接池)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
*Map<String,JedisPool>
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public Map<String, JedisPool> getClusterNodes(){
|
||||
return cluster==null?null:cluster.getClusterNodes();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getJedisClusterPipeline(获取redis cluster的 pipline.由于jedis没有实现,这里是用来一个第三方的pipline)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
* @throws Exception
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void getJedisClusterPipeline() throws Exception{
|
||||
if(cluster==null) cluster=getJedisCluster();;
|
||||
jcp=JedisClusterPipeline.pipelined(cluster);
|
||||
jcp.refreshCluster();//刷新集群状态
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getJedisClusterPipeline(获取redis cluster的 pipline.由于jedis没有实现,这里是用来一个第三方的pipline)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
*JedisClusterPipeline
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
// public JedisClusterPipeline getJedisClusterPipeline(JedisCluster cluster){
|
||||
// JedisClusterPipeline jcp=JedisClusterPipeline.pipelined(cluster);
|
||||
// jcp.refreshCluster();
|
||||
// return jcp;
|
||||
// }
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* closeJedisClusterPipeline(关闭pipeline)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param jcp
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void closeJedisClusterPipeline(){
|
||||
if(jcp!=null)
|
||||
jcp.close();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* closeJedisClusterPipeline(关闭pipeline)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param jcp
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
// public void closeJedisClusterPipeline(JedisClusterPipeline jcp){
|
||||
// if(jcp!=null)
|
||||
// jcp.close();
|
||||
// }
|
||||
/**
|
||||
*
|
||||
* * saveMaps(将对象转换成的Map保存到redis中)
|
||||
* (注意Date转换成long类型的时间戳然后以字符串的形式保存,蛋疼的jedis有问题,除了字符串跟byte[]数组就没别的保存类型了)
|
||||
* @param jcp//pipeLine
|
||||
* @param dataList//数据集合
|
||||
* @param tableName//实体类对应的表或者类名,用于生成唯一的hash key
|
||||
* @param keyField //实体类字段中表示唯一字段的字段名,其值用于生成唯一的hash key
|
||||
* @param clazz //类名
|
||||
* @throws Exception
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void saveMaps(List<? extends Object> dataList ,String tableName,Class clazz,String keyField) throws Exception{
|
||||
logger.info("save maps start");
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
if(jcp==null)getJedisClusterPipeline();
|
||||
long start=System.currentTimeMillis();
|
||||
// try{
|
||||
for(Object data:dataList){
|
||||
Map<String,String> dataMap=BeanHelper.transportBean2Map(clazz, data);
|
||||
jcp.hmset((tableName+"_"+dataMap.get(keyField)), dataMap);
|
||||
}
|
||||
jcp.sync();
|
||||
// }catch (Exception e) {
|
||||
// // TODO: handle exception
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
long end=System.currentTimeMillis();
|
||||
jcp.close();
|
||||
jcp=null;
|
||||
logger.info("save maps end, cost:"+(end-start));
|
||||
}
|
||||
/**
|
||||
*
|
||||
* updateMaps(更新redis中的对象)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param jcp
|
||||
* @param dataList
|
||||
* @param tableName
|
||||
* @param clazz
|
||||
* @param keyField
|
||||
* @throws Exception
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void updateMaps(List<? extends Object> dataList ,String tableName,Class clazz,String keyField) throws Exception{
|
||||
logger.info("update maps start");
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
if(jcp==null)getJedisClusterPipeline();
|
||||
long start=System.currentTimeMillis();
|
||||
// try{
|
||||
for(Object data:dataList){
|
||||
Map<String,String> dataMap=BeanHelper.transportBean2Map(clazz, data);
|
||||
jcp.hmset((tableName+"_"+dataMap.get(keyField)), dataMap);
|
||||
}
|
||||
jcp.sync();
|
||||
// }catch (Exception e) {
|
||||
// // TODO: handle exception
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
long end=System.currentTimeMillis();
|
||||
jcp.close();
|
||||
jcp=null;
|
||||
logger.info("update maps end, cost:"+(end-start));
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getMapById(获取Id 为xxxx的对象,返回一个Map)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param tableName
|
||||
* @param id
|
||||
* @return
|
||||
*Map<String,String>
|
||||
* @throws Exception
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public Map<String,String> getMapById(String tableName,long id) throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
Map<String, String> result=cluster.hgetAll(tableName+"_"+id);
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getMapById(获取Id 为xxxx的对象,返回一个Map)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param cluster
|
||||
* @param tableName
|
||||
* @param id
|
||||
* @return
|
||||
*Map<String,String>
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public Map<String,String> getMapById(JedisCluster cluster,String tableName,long id){
|
||||
Map<String, String> result=cluster.hgetAll(tableName+"_"+id);
|
||||
return result;
|
||||
}
|
||||
|
||||
public void saveList(List<String> jsonList,String sql,int expire) throws Exception{
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
if(jcp==null)getJedisClusterPipeline();
|
||||
for(String json :jsonList){
|
||||
jcp.rpush(sql, json);
|
||||
}
|
||||
jcp.expire(sql, expire);
|
||||
jcp.sync();
|
||||
jcp.close();
|
||||
jcp=null;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getSet(获取redis中的一个set的全部成员)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param key
|
||||
* @return
|
||||
* @throws Exception
|
||||
*Set<String>
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public Set<String> getSet(String key) throws Exception{
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
return cluster.smembers(key);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* saveSet(向一个set中添加成员)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param setName
|
||||
* @param values
|
||||
* @throws Exception
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void saveSet(String setName,String ...values) throws Exception{
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
if(jcp==null)getJedisClusterPipeline();
|
||||
for(String val:values){
|
||||
jcp.sadd(setName, val);
|
||||
}
|
||||
jcp.sync();
|
||||
jcp.close();
|
||||
jcp=null;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* isExistsInSet(判断一个字符串是否是set的成员,可用于去重,验证唯一性)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param setName
|
||||
* @param value
|
||||
* @return
|
||||
* @throws Exception
|
||||
*boolean
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public boolean isExistsInSet(String setName,String value) throws Exception{
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
return cluster.sismember(setName, value);
|
||||
}
|
||||
public List<String> getList(String sql,long start,long end) throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
List<String> data=cluster.lrange(sql, start, end);
|
||||
return data;
|
||||
}
|
||||
public void saveString(String key,String value,int expire) throws Exception{
|
||||
logger.info("save String start");
|
||||
long start=System.currentTimeMillis();
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
cluster.set(key, value);
|
||||
cluster.expire(key, expire);
|
||||
long end=System.currentTimeMillis();
|
||||
logger.info("save String end,cost:"+(end-start));
|
||||
}
|
||||
public String getString(String key) throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
return cluster.get(key);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* del(删除key)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param keys
|
||||
* @throws Exception
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void del(String... keys) throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
cluster.del(keys);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* clearData(清空数据)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @throws Exception
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void clearData() throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
logger.info("clear data start");
|
||||
long start=System.currentTimeMillis();
|
||||
Map<String, JedisPool> nodesMap=cluster.getClusterNodes();
|
||||
if(nodesMap==null){
|
||||
logger.error("empty redis nodes");
|
||||
return;
|
||||
}
|
||||
for(Entry<String, JedisPool> jedis:nodesMap.entrySet()){
|
||||
Jedis client=jedis.getValue().getResource();
|
||||
// only master node can flush db
|
||||
if(client.clusterInfo().indexOf("master")!=-1)
|
||||
client.flushAll();
|
||||
client.close();
|
||||
}
|
||||
long time=System.currentTimeMillis()-start;
|
||||
logger.info("clear data finish cost: "+time);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* exists(键是否存在)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param key
|
||||
* @return
|
||||
* @throws Exception
|
||||
*boolean
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public boolean exists(String key) throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
return cluster.exists(key);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user