redis整合
redis整合
reidsUtil
import org.hibernate.cfg.ExtendsQueueEntry;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class RedisUtil {
private static Jedis j;
private JedisPool jedisPool;
static String host = "127.0.0.1";
//static String password="damikeji";
static int port = 6379;
/*序列化工具*/
/**
* 单个序列化
* @param object
* @return
*/
public static byte[] serialize(Object object) {
if (object == null) {
return null;
}
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
byte[] bytes = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
bytes = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(oos);
close(baos);
}
return bytes;
}
/**
* 单个反序列化
*
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes) {
if (bytes == null) {
return null;
}
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(bais);
close(ois);
}
return null;
}
/**
* 序列化 list 集合
*
* @param list
* @return
*/
public static byte[] serializeList(List<?> list) {
if (list == null || list.size() == 0) {
return null;
}
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
byte[] bytes = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
for (Object obj : list) {
oos.writeObject(obj);
}
bytes = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(oos);
close(baos);
}
return bytes;
}
/**
* 反序列化 list 集合
*
* @param bytes
* @return
*/
public static List<?> unserializeList(byte[] bytes) {
if (bytes == null) {
return null;
}
List<Object> list = new ArrayList<Object>();
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
while (bais.available() > 0) {
Object obj = (Object) ois.readObject();
if (obj == null) {
break;
}
list.add(obj);
}
} catch (Exception e) {
//e.printStackTrace();
} finally {
close(bais);
close(ois);
}
return list;
}
/**
* 关闭io流对象
*
* @param closeable
*/
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*序列化工具-- ↑ */
private static JedisPool jedispool = null;
static {
//Jedis jedis = new Jedis(host);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//设置最大允许连接数
jedisPoolConfig.setMaxTotal(15000);
jedisPoolConfig.setMaxIdle(60000);
//设置最大的空闲连接
jedisPoolConfig.setMaxIdle(800);
//1. 创建Jeids连接池对象
jedispool=new JedisPool(jedisPoolConfig,host,port);
}
public static Jedis getJedis(){
try {
if (jedispool != null) {
Jedis jedis = jedispool.getResource();
//Jedis jedis = new Jedis(host);
return jedis;
}
return null;
} catch (Exception e) {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//设置最大允许连接数
jedisPoolConfig.setMaxTotal(15000);
jedisPoolConfig.setMaxIdle(60000);
//设置最大的空闲连接
jedisPoolConfig.setMaxIdle(800);
jedispool=new JedisPool(jedisPoolConfig,host,port);
System.out.println(e);
return null;
}
}
public static void main(String[] args) {
/*List<String> list = new ArrayList<>();
list.add("1");
list.add("1");
list.add("1");
list.add("1");
list.add("1");
RedisUtil.setList("select testlist from 222 where ", list);*/
/* for (int i = 0; i < 216546546; i++) {
*//*System.out.println(RedisUtil.get("time"));*//*
Jedis jedis = new Jedis(host);
jedis.get("time");
}*/
}
public static String get(String key){
Jedis jedis = getJedis();
System.out.println("Read [[" + key + "]] from redis");
String temp = jedis.get(key.replaceAll(" ",""));
close(jedis);
return temp;
}
public static void set(String key, String value) {
Jedis jedis = getJedis();
String entityName = hql2EntityName(key);
key = key.replaceAll(" ", "");
if(entityName!=null){
listAdd(entityName, key);
}
jedis.set(key, value);
close(jedis);
}
public static List<?> getList(String key){
Jedis jedis = getJedis();
System.out.println("Read [[" + key + "]] from redis");
key = key.replaceAll(" ", "");
if(jedis == null || !jedis.exists(key)){
return null;
}
byte[] data = jedis.get(key.getBytes());
close(jedis);
return unserializeList(data);
}
public static void setList(String key ,List<?> list){
Jedis jedis =getJedis();
String entityName = hql2EntityName(key);
key = key.replaceAll(" ", "");
if(entityName!=null){
listAdd(entityName, key);
}
try {
if(list == null || list.size() == 0){
jedis.set(key.getBytes(), "".getBytes());
}else{//如果list为空,则设置一个空
jedis.set(key.getBytes(), serializeList(list));
}
close(jedis);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
/**
* 向一个list中添加数据 (注意这是没有序列化的 上边setList的key不能用这个)
* @param key
* @param value
*/
public static void listAdd(String key,String value){
Jedis jedis = RedisUtil.getJedis();
jedis.lpush(key, value);
close(jedis);
}
/**
*
* @return
*/
public static List<String> lrangeList(String key){
Jedis jedis = RedisUtil.getJedis();
List<String> list=jedis.lrange(key, 0 ,-1);
close(jedis);
return list;
}
public static void delentity(String entityName) {
Jedis jedis = RedisUtil.getJedis();
if (jedis != null) {
List<String> list=jedis.lrange(entityName, 0 ,-1);
for (String s : list) {
jedis.del(s);
}
jedis.del(entityName);
close(jedis);
}
}
public static String hql2EntityName(String hql) {
String a = "from ";
String b = " where";
String str ="";
if(hql.indexOf("update")>-1){
a = "update ";
b = " set";
}
try {
str = ExtendString.split(ExtendString.split(hql,a)[1],b)[0].trim();
} catch (Exception e) {
System.out.println(1);
}
return ExtendString.split(str," ")[0];
}
public static void close(Jedis jedis) {
if (jedis != null) {
jedispool.returnResource(jedis);
}
}
public static boolean isRidisRun(){
try {
Jedis resource = jedispool.getResource();
jedispool.returnResource(resource);
return true;
} catch (Exception e) {
return false;
}
}
}
baseaction.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.jframe.redisclient.RedisService;
import com.jframe.redisclient.RedisTool;
import com.jframe.redisclient.RedisUtil;
import com.spaq.cydw.service.CydwJbxxService;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.write.Label;
import jxl.write.WritableFont;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import com.fins.gt.model.FilterInfo;
import com.fins.gt.model.SortInfo;
import com.fins.gt.server.GridServerHandler;
import com.fins.gt.util.LogHandler;
import com.fins.gt.util.StringUtils;
import com.fins.gt.view.js.AjaxUrl;
import com.lowagie.text.pdf.codec.Base64;
import com.sso.app.model.FunData;
import com.sso.app.service.FunDataService;
import com.sso.audit.log.model.SysLog;
import com.sso.audit.log.model.SysLogCfg;
import com.sso.audit.log.service.SysLogCfgService;
import com.sso.audit.log.service.SysLogService;
import com.sso.right.service.DataRightService;
import com.sys.code.service.CodeService;
import redis.clients.jedis.Jedis;
public class BaseAction extends SysService{
private PrintWriter out;
protected HttpServletRequest request;
protected HttpServletResponse response;
protected Map parameterMap;
protected boolean printed=false;
protected String viewPath;
protected String viewBasePath;
protected ServletWrapper servletWrapper;
protected GridServerHandler gridServerHandler;
protected HttpSession session;
protected CurUser curUser;
protected Param requestParam;
/**
* sevlet服务方法
* @throws ServletException
* @throws IOException
*/
public void service() throws ServletException, IOException{
throw new ServletException("Please override service() Method!");
}
/**
* servlet初始化
* @param request
* @param response
*/
public void init(HttpServletRequest request,HttpServletResponse response) {
this.setRequest(request);
this.setResponse(response);
this.setServletWrapper(new ServletWrapper(request,response));
this.gridServerHandler = new GridServerHandler(request,response);
this.setParameterMap(request.getParameterMap());
Map pMap = this.getParameterSimpleMap();
this.requestParam = new Param(pMap);
this.session = this.request.getSession(true);
}
/**
* 获取表格句柄
* @return
*/
protected GridServerHandler getGridServerHandler()
{
return this.gridServerHandler;
}
protected void println(Object text){
print(text);
println();
}
protected void println(){
printed=true;
getOut().println();
}
protected void print(Object text){
printed=true;
getOut().print(String.valueOf(text));
}
protected void flushOut(){
getOut().flush();
}
protected void closeOut(){
getOut().close();
}
protected void setCurUser(CurUser curUser)
{
this.curUser = curUser;
this.session = this.request.getSession(true);
this.session.setAttribute(SysConst.CUR_USERINFO, this.curUser);
}
protected CurUser getCurUser()
{
this.session = this.request.getSession(true);
this.curUser =(CurUser) this.session.getAttribute(SysConst.CUR_USERINFO);
return this.curUser;
}
protected String getViewUrl(String viewName){
String queryStr= null;
int aidx=viewName.indexOf('?');
if (aidx>0){
queryStr=viewName.substring(aidx+1);
viewName=viewName.substring(0,aidx);
}
if (!StringUtils.endsWithIgnoreCase(viewName, ".jsp")
&&!StringUtils.endsWithIgnoreCase(viewName, ".html")
&&!StringUtils.endsWithIgnoreCase(viewName, ".htm")
){
viewName=viewName+".jsp";
}
if (StringUtils.isNotEmpty(queryStr)){
viewName=viewName+'?'+queryStr;
}
if (viewName.indexOf("//")==0){
return viewName.substring(1);
}
if (viewName.indexOf("/")==0){
return getViewBasePath()+viewName;
}
String viewPath=getViewPath();
if (viewName.indexOf("../")==0){
viewName=viewName.substring(3);
int idx=viewPath.lastIndexOf('/');
viewPath=viewPath.substring(0,idx);
}
return getViewBasePath()+ viewPath +"/"+viewName;
}
protected void redirect(String url) {
try {
response.sendRedirect(getViewUrl(url));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void redirectOtherWebUrl(String url){
try {
response.sendRedirect(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 跳转到指定jsp或html页面
* @param url
*/
protected void forward(String url) {
//String ctxPath = request.getContextPath();
try {
this.request.setAttribute("requestParam", this.requestParam);
//将屏幕高度写到页面中,以便程序调用
String winWidth = this.session.getAttribute("winWidth")== null ? "1276" : (String) this.session.getAttribute("winWidth"); //
String winHeight = this.session.getAttribute("winHeight")== null ? "654" : (String) this.session.getAttribute("winHeight");
this.request.setAttribute("winWidth",winWidth);
this.request.setAttribute("winHeight",winHeight);
request.getRequestDispatcher( url).forward(request, response);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 跳转到指定freemarker模板页面,注意这里没有指定特别的参数,如果需要可以将参数写入request属性中传递
* @param ftlPath
*/
protected void forward2ftl(String ftlPath){
FreeMarker freeMark = new FreeMarker(request,response);
freeMark.process(ftlPath);
}
/**
* 跳转到指定freemarker模板页面,注意这里没有指定特别的参数,一些特殊参数可以写root参数中
* @param ftlPath
* @param root
*/
protected void forward2ftl(String ftlPath,Map root){
FreeMarker freeMark = new FreeMarker(request,response);
freeMark.setRoot(root);
freeMark.process(ftlPath);
}
protected void include(String viewName) throws ServletException, IOException{
request.getRequestDispatcher(getViewUrl(viewName)).include(request, response);
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
this.setParameterMap(request.getParameterMap());
}
public HttpServletResponse getResponse() {
return response;
}
public void setContentType(String contextType) {
response.setContentType(contextType);
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public boolean isPrinted() {
return printed;
}
public String getViewPath() {
return viewPath;
}
public void setViewPath(String viewPath) {
this.viewPath = viewPath;
}
public String getViewBasePath() {
return viewBasePath;
}
public void setViewBasePath(String viewBasePath) {
this.viewBasePath = viewBasePath;
}
public Map getParameterMap() {
return parameterMap;
}
public Map getParameterSimpleMap() {
Iterator kit= parameterMap.keySet().iterator();
Map param=new HashMap();
while(kit.hasNext()){
String key=String.valueOf(kit.next());
String[] v=null;
try {
v=(String[])parameterMap.get(key);
} catch (Exception e) {
continue;
}
if (v!=null && v.length==1){
param.put(key,v[0]);
}else{
param.put(key,v);
}
}
return param;
}
public String getParameter(String name) {
return request.getParameter(name);
}
public void setParameterMap(Map parameterMap) {
this.parameterMap = parameterMap;
}
public void dispose() {
out=null;
request=null;
response=null;
printed=false;
viewPath=null;
viewBasePath=null;
}
public String getIpAddr() {
HttpServletRequest request = this.request;
String ip = request.getHeader(" x-forwarded-for ");
System.out.println("取到的IP地址:"+ip);
if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
ip = request.getHeader(" Proxy-Client-IP ");
}
if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
ip = request.getHeader(" WL-Proxy-Client-IP ");
}
if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
public ServletWrapper getServletWrapper() {
return servletWrapper;
}
public void setServletWrapper(ServletWrapper servletWrapper) {
this.servletWrapper = servletWrapper;
}
public PrintWriter getOut() {
if (out==null){
try {
setOut(response.getWriter());
} catch (IOException e) {
LogHandler.error(this,e);
}
}
return out;
}
public void setOut(PrintWriter out) {
this.out = out;
}
public String getFilterInfoSql(Class clz,String defaultStr){
String filterSql =getFilterInfoSql(clz);
if("( 1=1 )".equals(filterSql)){
return "("+defaultStr+")";
}
return filterSql;
}
/**
* equal,notEqual,less,great,lessEqual,greatEqual
* "=","!=","<",">","<=",">=","like","startWith","endWith".
* @return
*/
public String getFilterInfoSql(Class clz){
List<FilterInfo> filterInfos = gridServerHandler.getFilterInfo();
//System.out.println( ExtendJson.list2Json(gridServerHandler.getData()));
StringBuffer sqlBuf = new StringBuffer("( 1=1 ");
for(FilterInfo f:filterInfos){
boolean isString = false;
for(Field field:clz.getDeclaredFields()){
if(field.getName().equalsIgnoreCase(f.getFieldName())){
isString=String.class.equals(field.getType());
break;
}
}
if("like".equalsIgnoreCase(f.getLogic())){
if(isString){
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append(" like '%"+f.getValue()+"%'");
}
}else if("startWith".equalsIgnoreCase(f.getLogic())){
if(isString){
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append(" like '"+f.getValue()+"%'");
}
}else if("endWith".equalsIgnoreCase(f.getLogic())){
if(isString){
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append(" like '%"+f.getValue()+"'");
}
}else if("equal".equalsIgnoreCase(f.getLogic())){
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append("="+(isString?"'":"")+f.getValue()+(isString?"'":""));
}else if("notEqual".equalsIgnoreCase(f.getLogic())){
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append("!="+(isString?"'":"")+f.getValue()+(isString?"'":""));
}else if( "less".equalsIgnoreCase(f.getLogic())){
if(!isString){
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append("<"+f.getValue());
}
}else if( "great".equalsIgnoreCase(f.getLogic())){
if(!isString){
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append(">"+f.getValue());
}
}else if("lessEqual".equalsIgnoreCase(f.getLogic())){
if(!isString){
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append("<="+f.getValue());
}
}else if("greatEqual".equalsIgnoreCase(f.getLogic())){
if(!isString){
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append(">="+f.getValue());
}
}
else if("in".equalsIgnoreCase(f.getLogic())){
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append(" in (" + f.getValue() + ")");
}
else{
sqlBuf.append(" and "+f.getFieldName());
sqlBuf.append(f.getLogic()+(isString?"'":"")+f.getValue()+(isString?"'":""));
}
}
sqlBuf.append(")");
return sqlBuf.toString();
}
/**
* 获取sql排序语句
* @return
*/
public String getSortSql()
{
SortInfo sort = gridServerHandler.getSingleSortInfo();
String sql ="";
if(sort!=null)
{
String sortSeq = sort.getSortOrder();
if(!sortSeq.equalsIgnoreCase(SortInfo.DEFAULTSORT))
{
sql += " order by " + sort.getFieldName() + " " +sort.getSortOrder() ;
}
}
return sql;
}
public void baseSave(Class clz, String serviceName)
{
boolean success=true;
GridServerHandler gridServerHandler=new GridServerHandler(request,response);
//取得新增的数据集合, 每条数据记录在 map 里
List insertedRecords = gridServerHandler.getInsertedRecords(clz);
//取得修改的数据集合, 每条数据记录在 map 里
List updatedList = gridServerHandler.getUpdatedRecords(clz);
//取得删除的数据集合, 每条数据记录在 map 里
List deletedRecords = gridServerHandler.getDeletedRecords(clz);
if(this.beforeListSave(gridServerHandler,insertedRecords, updatedList, deletedRecords)){
BaseService service = (BaseService) this.getBean(serviceName);
service.save( insertedRecords,updatedList,deletedRecords);
// 如果希望取得bean的集合 那么请使用有参方法: xxx.getXXXXXXRecords(Class beanClass);
//例如: List updateList = gridServerHandler.getUpdatedRecords(StudentVO.class);
//调用"相应的方法" 来update delete insert数据
//success = dao.saveStudents(insertedRecords , updatedList, deletedRecords );
this.afterListSave( insertedRecords, updatedList, deletedRecords);
//设置该次操作是否成功.
}
else{
success =false; //提示操作失败
}
gridServerHandler.setSuccess(success);
//如果操作不成功 你也可以自定义一些异常信息发送给客户端.
//gridServerHandler.setSuccess(false);
//gridServerHandler.setException("... exception info ...");
//向客户端输出json字符串.
//System.out.println(gridServerHandler.getSaveResponseText());
print(gridServerHandler.getSaveResponseText());
//运行日志
this.log(insertedRecords, updatedList, deletedRecords, success, serviceName);
}
protected boolean beforeListSave(GridServerHandler gridServerHandler,
List insertedRecords, List updatedList, List deletedRecords){
return true;
}
protected void afterListSave(List insertedRecords, List updatedList, List deletedRecords){
}
public void baseLoad(String serviceName,String hql)
{
this.baseLoad(serviceName, hql,"");
}
public void baseLoad(String serviceName,String hql,String defOrderBy)
{
BaseService service = (BaseService) this.getBean(serviceName);
GridServerHandler gridServerHandler = this.getGridServerHandler();
String orderBy = ExtendString.nullToSpace( this.getSortSql());
//System.out.println("ordrBy=" + orderBy);
if("".equals(orderBy))
{
hql = hql + " "+ defOrderBy;
}
else
{
hql = hql + " " + orderBy;
}
int start = gridServerHandler.getStartRowNum(); //当前页起始行号
//int end = gridServerHandler.getEndRowNum(); //当前页结束行号
int limit = gridServerHandler.getPageSize(); //每页大小
ResultSet rs= service.findListByHqlPage(hql, start-1, limit);
//List ls = service.findList(condition);
this.baseLoad(rs);
}
public void baseLoad( Class clz ,String serviceName,String where)
{
this.baseLoad(clz, serviceName, where,"");
}
//获取数据权限控制
private String getDataRight(){
int funId = this.requestParam.getInt("rightFunId");
int tabId = this.requestParam.getInt("rightTabId");
if(funId > 0 && tabId >0 ){
FunDataService funDataService = (FunDataService) this.getBean("funDataService");
FunData funData = funDataService.getFunDatas(funId, tabId);
if(funData.getId() >0){
DataRightService service =(DataRightService) this.getBean("dataRightService");
String rights= service.getRightsByRole(this.getCurUser().getRoleId(),funId,tabId,funData.getId());
if(!rights.equals("")){
return funData.getField() + " in (" + rights + ")"; //返回数据权限类型
}
else{
return funData.getField() + " in (-1)";
}
}
}
return "";
}
public void baseLoad( Class clz ,String serviceName,String where ,String defOrderBy )
{
BaseService service = (BaseService) this.getBean(serviceName);
GridServerHandler gridServerHandler = this.getGridServerHandler();
String orderBy = ExtendString.nullToSpace( this.getSortSql());
//System.out.println("ordrBy=" + orderBy);
String condition = "";
orderBy = "".equals(orderBy)? defOrderBy : orderBy;
if(StringUtils.isEmpty(where)){
condition = " where "+this.getFilterInfoSql(clz);
}else{
condition = where + " AND "+ this.getFilterInfoSql(clz);
}
String rights = this.getDataRight();
if(!"".equals(rights)){
condition += " and " + rights;
}
condition += " " + orderBy;
//在这里把查询方法保存起来,便于导出
String clazz = this.getClass().getName();
String method = Thread.currentThread() .getStackTrace()[2].getMethodName();
this.session.setAttribute(clazz+method+ "conditon", condition);
int start = gridServerHandler.getStartRowNum(); //当前页起始行号
//int end = gridServerHandler.getEndRowNum(); //当前页结束行号
int limit = gridServerHandler.getPageSize(); //每页大小
ResultSet rs= service.findListByPage( clz, condition, start-1, limit);
//List ls = service.findList(condition);
this.baseLoad(rs);
}
/*public void baseLoad( Class clz ,String serviceName,String where ,String defOrderBy )
{
long time = System.currentTimeMillis();
BaseService service = (BaseService) this.getBean(serviceName);
GridServerHandler gridServerHandler = this.getGridServerHandler();
String orderBy = ExtendString.nullToSpace( this.getSortSql());
//System.out.println("ordrBy=" + orderBy);
String condition = "";
orderBy = "".equals(orderBy)? defOrderBy : orderBy;
if(StringUtils.isEmpty(where)){
condition = " where "+this.getFilterInfoSql(clz);
}else{
condition = where + " AND "+ this.getFilterInfoSql(clz);
}
String rights = this.getDataRight();
if(!"".equals(rights)){
condition += " and " + rights;
}
condition += " " + orderBy;
//在这里把查询方法保存起来,便于导出
String clazz = this.getClass().getName();
String method = Thread.currentThread() .getStackTrace()[2].getMethodName();
this.session.setAttribute(clazz+method+ "conditon", condition);
int start = gridServerHandler.getStartRowNum(); //当前页起始行号
//int end = gridServerHandler.getEndRowNum(); //当前页结束行号
int limit = gridServerHandler.getPageSize(); //每页大小
*//*方案1:
默认从redis中读取(若存在),
快速反馈给前端,
读取完毕后再查询数据库,
如果数据库与redis中不同,
则更新redis中内容,
每次增删改只修改数据库中内容,
下次访问时再做缓存
方案2:
判断redis中是否存在该页记录,
若不存在,读取数据库数据并放入reids中下次使用,
每次增删改需要更新redis中内容和数据库内容
*//*
Jedis jedis = RedisUtil.getJedis();
String redisKey = new StringBuilder().append(clazz).append(".").append(method).append(clazz).append(".").append("method").append(".start.").append(start).append(".limit.").append(limit).append("==>SQL:").append(condition.replace(" ","")).toString();
if(jedis!=null){
ResultSet rs = null;
if(jedis.get("rs"+redisKey)==null){
rs= service.findListByPage( clz, condition, start-1, limit);
jedis.set("rs" + redisKey, ExtendJson.obj2Json(rs));
}else{
rs = (ResultSet) ExtendJson.json2Obj(jedis.get("rs"+redisKey),ResultSet.class);
new updateRedisCache(rs, service, clz, condition, start, limit, redisKey).start();
}
String jsonFromCache = jedis.get(redisKey);
//List ls = service.findList(condition);
if(jsonFromCache==null){
this.baseLoad(rs,redisKey);
System.out.println("====== Cache does not exist, read from database ======");
}else {
print(jsonFromCache);
System.out.println("====== Read data from redis ======");
this.baseLoadUpdate(rs,redisKey);
}
System.out.println(new StringBuilder().append(redisKey).append(" Over!!!").append("Time: ").append((System.currentTimeMillis()-time) ).append(" ms"));
}else{
ResultSet rs= service.findListByPage( clz, condition, start-1, limit);
this.baseLoad(rs);
System.out.println("====== Redis service is not started, read from the database ======");
System.out.println(new StringBuilder().append(redisKey).append(" Over!!!").append("Time: ").append((System.currentTimeMillis()-time) ).append(" ms"));
}
}*/
class updateRedisCache extends Thread{
private ResultSet resultSet;
private BaseService service;
private Class clz;
private String condition;
private int start;
private int limit;
private String redisKey;
public updateRedisCache() { }
public updateRedisCache( ResultSet resultSet, BaseService service, Class clz, String condition, int start, int limit, String redisKey) {
this.resultSet = resultSet;
this.service = service;
this.clz = clz;
this.condition = condition;
this.start = start;
this.limit = limit;
this.redisKey = redisKey;
}
@Override
public void run(){
Jedis jedis = RedisUtil.getJedis();
/**
*只保持一个刷新缓存方法
*
*/
if (jedis.get("running" + redisKey) == null) {
jedis.set("running" + redisKey, "running");
ResultSet rs= service.findListByPage( clz, condition, start-1, limit);
jedis.set("rs" + redisKey, ExtendJson.obj2Json(rs));
jedis.del("running" + redisKey);
}
RedisUtil.close(jedis);
}
}
/**
* 重新查询数据(不是过滤之前的)
* @param clz
* @param serviceName
* @param where
* @param defOrderBy
*/
public void baseLoad1( Class clz ,String serviceName,String where ,String defOrderBy )
{
BaseService service = (BaseService) this.getBean(serviceName);
GridServerHandler gridServerHandler = this.getGridServerHandler();
String orderBy = ExtendString.nullToSpace( this.getSortSql());
//System.out.println("ordrBy=" + orderBy);
String condition = "";
orderBy = "".equals(orderBy)? defOrderBy : orderBy;
/*if(StringUtils.isEmpty(where)){
}else{
}*/
if("( 1=1 )".equals(this.getFilterInfoSql(clz))){
condition = where + " AND "+ this.getFilterInfoSql(clz);
}else{
condition = " where "+this.getFilterInfoSql(clz);
}
String rights = this.getDataRight();
if(!"".equals(rights)){
condition += " and " + rights;
}
condition += " " + orderBy;
//在这里把查询方法保存起来,便于导出
String clazz = this.getClass().getName();
String method = Thread.currentThread() .getStackTrace()[2].getMethodName();
this.session.setAttribute(clazz+method+ "conditon", condition);
int start = gridServerHandler.getStartRowNum(); //当前页起始行号
//int end = gridServerHandler.getEndRowNum(); //当前页结束行号
int limit = gridServerHandler.getPageSize(); //每页大小
ResultSet rs= service.findListByPage( clz, condition, start-1, limit);
//List ls = service.findList(condition);
this.baseLoad(rs);
}
public void baseExp(Class clz ,String serviceName,String loadMethod){
BaseService service = (BaseService) this.getBean(serviceName);
String clazz = this.getClass().getName();
String condition = (String) this.session.getAttribute(clazz + loadMethod + "conditon");
List ls = service.findList(clz, condition);
this.lsCode2Text(ls);
if(ls.size()>0){
for(int i= 0;i<ls.size();i++){
this.lsCode2Text(ls.get(i));
this.code2Text(ls.get(i));
}
}
this.baseExportXls(ls, clz);
}
/**
* 本方法用于对rs结果集中字典部分进行转换
* @param ls
* @return
*/
protected List lsCode2Text(List ls){
for(Object obj:ls){
obj=lsCode2Text(obj);
}
return ls;
}
protected Object lsCode2Text(Object obj){
return obj;
}
/**
* 用于字典转换成文字
* @param code
* @param dict
* @param dictType 1,是字典,2是映射
* @return
*/
protected String c2t(int code,String dict,int dictType){
return this.c2t(code+"", dict, dictType);
}
protected String c2t(String code,String dict,int dictType) {
String[] a1 = ExtendString.split(code);
String k = "";
if (a1.length > 1) {
int i = 0;
for (String s : a1) {
i++;
String t = dictType == 1 ? this.getCodeValue(dict, s) : this.getSysTypeName(dict, s);
t = ExtendString.nullToSpace(t);
k += i == a1.length ? t : t + " , ";
}
} else {
k = dictType == 1 ? this.getCodeValue(dict, a1[0]) : this.getSysTypeName(dict, a1[0]);
k = ExtendString.nullToSpace(k);
}
return k;
}
public void baseLoad(ResultSet rs,String redisKey){
// 取得总记录数
int totalRowNum=gridServerHandler.getTotalRowNum();
//如果总数不存在, 那么调用"相应的方法" 来取得总数
//boolean hasFilterInfo = gridServerHandler.getFilterInfo()!=null&&gridServerHandler.getFilterInfo().size()>0;
if ( rs!=null){
//totalRowNum=dao.countAllStudents();
//将取得的总数赋给gridServerHandler
gridServerHandler.setTotalRowNum(rs.getTotalRows());
}
//调用"相应的方法" 来取得数据.下面4个方法 通常对于进行分页查询很有帮助,根据需要使用即可.
// gridServerHandler.setTotalRowNum(); //记录总条数
//list=dao.getStudentsByPage(gridServerHandler.getStartRowNum(),gridServerHandler.getPageSize());
// 本例中list里的元素是 map,
// 如果元素是bean, 请使用 gridServerHelp.setData(list,BeanClass.class);
List ls = rs.getResults();
ls = this.lsCode2Text(ls); //需要对rs结果集中的字典部分进行清洗
gridServerHandler.setData(ls);
// gridServerHandler.setException("your exception message");
//向客户端输出json字符串.
String json = gridServerHandler.getLoadResponseText();
//System.out.println("load=" + json);
//json = ExtendString.CS(json);
print(json);
RedisUtil.set(redisKey,json);
}
public void baseLoadUpdate(ResultSet rs,String redisKey){
// 取得总记录数
int totalRowNum=gridServerHandler.getTotalRowNum();
//如果总数不存在, 那么调用"相应的方法" 来取得总数
//boolean hasFilterInfo = gridServerHandler.getFilterInfo()!=null&&gridServerHandler.getFilterInfo().size()>0;
if ( rs!=null){
//totalRowNum=dao.countAllStudents();
//将取得的总数赋给gridServerHandler
gridServerHandler.setTotalRowNum(rs.getTotalRows());
}
//调用"相应的方法" 来取得数据.下面4个方法 通常对于进行分页查询很有帮助,根据需要使用即可.
// gridServerHandler.setTotalRowNum(); //记录总条数
//list=dao.getStudentsByPage(gridServerHandler.getStartRowNum(),gridServerHandler.getPageSize());
// 本例中list里的元素是 map,
// 如果元素是bean, 请使用 gridServerHelp.setData(list,BeanClass.class);
List ls = rs.getResults();
ls = this.lsCode2Text(ls); //需要对rs结果集中的字典部分进行清洗
gridServerHandler.setData(ls);
// gridServerHandler.setException("your exception message");
//向客户端输出json字符串.
String json = gridServerHandler.getLoadResponseText();
//System.out.println("load=" + json);
//json = ExtendString.CS(json);
/*print(json);*/
RedisUtil.set(redisKey,json);
}
public void baseLoad(ResultSet rs){
// 取得总记录数
int totalRowNum=gridServerHandler.getTotalRowNum();
//如果总数不存在, 那么调用"相应的方法" 来取得总数
//boolean hasFilterInfo = gridServerHandler.getFilterInfo()!=null&&gridServerHandler.getFilterInfo().size()>0;
if ( rs!=null){
//totalRowNum=dao.countAllStudents();
//将取得的总数赋给gridServerHandler
gridServerHandler.setTotalRowNum(rs.getTotalRows());
}
//调用"相应的方法" 来取得数据.下面4个方法 通常对于进行分页查询很有帮助,根据需要使用即可.
// gridServerHandler.setTotalRowNum(); //记录总条数
//list=dao.getStudentsByPage(gridServerHandler.getStartRowNum(),gridServerHandler.getPageSize());
// 本例中list里的元素是 map,
// 如果元素是bean, 请使用 gridServerHelp.setData(list,BeanClass.class);
List ls = rs.getResults();
ls = this.lsCode2Text(ls); //需要对rs结果集中的字典部分进行清洗
gridServerHandler.setData(ls);
// gridServerHandler.setException("your exception message");
//向客户端输出json字符串.
String json = gridServerHandler.getLoadResponseText();
//System.out.println("load=" + json);
//json = ExtendString.CS(json);
print(json);
}
public void baseExportXls(Class clz ,String serviceName,String where )
{
this.baseExportXls(clz, serviceName, where,"");
}
public void baseExportXls(Class clz ,String serviceName,String where ,String defOrderBy ){
BaseService service = (BaseService) this.getBean(serviceName);
GridServerHandler gridServerHandler = this.getGridServerHandler();
String orderBy = ExtendString.nullToSpace( this.getSortSql());
//System.out.println("ordrBy=" + orderBy);
String condition = "";
if("".equals(orderBy))
{
if(StringUtils.isEmpty(where)){
condition = " where "+this.getFilterInfoSql(clz)+" "+ defOrderBy;
}else{
condition = where + " AND "+ this.getFilterInfoSql(clz)+" "+ defOrderBy;
}
}
else
{
if(StringUtils.isEmpty(where)){
condition = " where "+this.getFilterInfoSql(clz)+" "+ orderBy;
}else{
condition = where + " AND "+ this.getFilterInfoSql(clz)+" " + orderBy;
}
}
//ResultSet rs= service.findListByPage( clz, condition, -1, -1);
List ls = service.findList(clz, condition);
this.baseExportXls(ls, clz);
}
public void baseExportXls(String serviceName,String hql,Class clz){
this.baseExportXls(serviceName, hql,"", clz);
}
public void baseExportXls(String serviceName,String hql,String defOrderBy,Class clz){
BaseService service = (BaseService) this.getBean(serviceName);
GridServerHandler gridServerHandler = this.getGridServerHandler();
String orderBy = ExtendString.nullToSpace( this.getSortSql());
//System.out.println("ordrBy=" + orderBy);
if("".equals(orderBy))
{
hql = hql + " "+ defOrderBy;
}
else
{
hql = hql + " " + orderBy;
}
this.baseExportXls(service.findListByHql(hql), clz);
}
public void baseExportXls(List ls,Class clz) {
try {
gridServerHandler.exportXLS(ls, clz);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* base64编码
* @param str
* @return
* @author:jackyli
*/
public String encodeByBase64(String str){
return Base64.encodeBytes(str.getBytes(), Base64.GZIP| Base64.URL_SAFE | Base64.DONT_BREAK_LINES);
}
/**
* base64解码
* @param str
* @return
* @author:jackyli
*/
public String decodeByBase64(String str){
return new String(Base64.decode(str,
Base64.GZIP | Base64.URL_SAFE | Base64.DONT_BREAK_LINES));
}
/**
* 提供数据与模板文件的地址
* 功能:生成excel报表,
* @param dataMap
* @param templateFileName
* @throws IOException
* @throws ParsePropertyException
*/
public void exportXls(Map dataMap,String templateFileName) throws ParsePropertyException, IOException{
String basePath = this.request.getSession().getServletContext().getRealPath("/");
//System.out.println("basePath:"+basePath);
String fileName = templateFileName.substring(templateFileName.lastIndexOf("/")+1);
String destFileName = File.separator+"excel" + File.separator + fileName;
//System.out.println("destFile:"+destFileName);
if(!templateFileName.startsWith("/")){
templateFileName ="/"+templateFileName;
}
XLSTransformer transformer = new XLSTransformer();
transformer.transformXLS(basePath+templateFileName, dataMap, basePath+destFileName);
this.forward(destFileName);
}
public void exportXls(int[] columnWidth,String[] headers,List<String[]> data,String fileName) throws RowsExceededException, WriteException, IOException{
//新建Excel文件
String filePath=request.getSession().getServletContext().getRealPath(fileName);
File myFilePath=new File(filePath);
if(!myFilePath.exists())
myFilePath.createNewFile();
FileWriter resultFile=new FileWriter(myFilePath);
PrintWriter myFile=new PrintWriter(resultFile);
resultFile.close();
//用JXL向新建的文件中添加内容
OutputStream outf = new FileOutputStream(filePath);
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(outf);
jxl.write.WritableSheet ws = wwb.createSheet("sheettest", 0);
int i=0;
int j=0;
for (int k = 0; k < headers.length; k++) {
jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES, 12 ,WritableFont.BOLD, true );
jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);
wcfF.setAlignment(Alignment.CENTRE);
Label label = new Label(k,0,headers[k],wcfF);
ws.addCell(label);
ws.setColumnView(k, columnWidth[k]);
}
for(String[] d:data){
for (int k = 0; k < headers.length; k++) {
ws.addCell(new Label(k,j+i+1,d[k]));
}
i++;
}
wwb.write();
wwb.close();
response.sendRedirect(request.getContextPath()+""+fileName);
}
//===============
public void exportXls(String name,List ls,Class beanClass) throws IOException{
GridServerHandler gridServerHandler=new GridServerHandler(request,response);
gridServerHandler.setEncodeFileName(true);
gridServerHandler.exportXLS(ls, beanClass);
//gridServerHandler.downloadFile(gridServerHandler.encodeFileName(name));
}
/**
* 用于接收grid.getInsertedRecord()、grid.getUpdatedRecords(),grid.getDeletedRecords()的数组字符串转成List对象
* @param jsonStr
* @param clz
* @return
*/
public List convertJsonArrayToList(String jsonStr,Class clz){
JSONArray jsonArray = JSONArray.fromObject(jsonStr);
List arrays = new ArrayList();
if(jsonArray!=null){
for(int i=0;i<jsonArray.size();i++){
JSONObject _jsonObj=jsonArray.getJSONObject(i);
Object hotelDetail = (Object)_jsonObj.toBean(_jsonObj, clz);
arrays.add(hotelDetail);
}
}
return arrays;
}
/**
* 从attribute上下文中获取boolean值
* @param key
* @return
*/
public boolean getBooleanAttribute(String key){
return ExtendString.parseBoolean(request.getAttribute(key));
}
/**
*
*/
public String baseDelRecord(Class clz, String serviceName, String args[]){
int id = ExtendString.parseInt(args[0]);
BaseService service = (BaseService) this.getBean(serviceName);
this.delLog(id, clz, true, service); //日志
service.del(clz, id);
return "true";
}
/**
* 删除前添加过滤不能删除的
* by rsx
* @param ids
* @return
*/
public String checkId(String ids){
return ids;
}
public String baseDelSelRecord(Class clz, String serviceName, String args[]){
try{
BaseService service = (BaseService) this.getBean(serviceName);
String ids = args[0];
ids = checkId(ids);
ids=ids.length()==0?"0":ids;
String hql = " delete from " + clz.getSimpleName() + " where id in ("+ids+")";
//log
this.delLog(args[0], clz, true, service);
service.delete(hql);
//service.find
if(ids.indexOf("0")==0){
return ids.split(",").length-1+"";
}else{
return ids.split(",").length+"";
}
}
catch(Exception ex){
ex.printStackTrace();
return "false";
}
}
public void baseTree(String typeTable){
Map<Integer,String> map = SysMapRepository.getTypeMap(typeTable);
String nodes = "<nodes> ";
Set<Integer> set = map.keySet();
for (Integer key : set) {
nodes += "<node id='xx" + key + "' text='" + map.get(key)
+ "' method='doFilter(" + key + ")' />";
}
nodes += "</nodes>";
this.print(nodes);
}
/**
* 初设化表格
* @param args
* @param serviceName
* @return
*/
public String baseInitForm(String args[],Class clz ,String serviceName){
BaseService service = (BaseService) this.getBean(serviceName);
Object obj;
if(args.length > 1){
//第二个参数可以为选择参数,这样可以增强初设化函数的功能
String uniField = ExtendString.nullToSpace(args[1]);
Serializable id = ExtendClass.typeTran(clz, uniField, args[0]);
obj = service.load(clz, id,uniField);
}
else{
Serializable id = ExtendString.isDigit(args[0]) ? ExtendString.parseInt(args[0]) : args[0];
obj = service.load(clz, id);
}
obj = this.setInitFormObj(obj); //提供给子类构造,改写用。
String json = ExtendJson.obj2Json(obj);
return json;
}
public String baseShowInfo(String args[],Class clz ,String serviceName){
BaseService service = (BaseService) this.getBean(serviceName);
Object obj;
if(args.length > 1){
//第二个参数可以为选择参数,这样可以增强初设化函数的功能
String uniField = ExtendString.nullToSpace(args[1]);
Serializable id = ExtendClass.typeTran(clz, uniField, args[0]);
obj = service.load(clz, id,uniField);
}
else{
Serializable id = ExtendString.isDigit(args[0]) ? ExtendString.parseInt(args[0]) : args[0];
obj = service.load(clz, id);
}
obj = this.code2Text(obj); //提供给子类构造,改写代码转转文本。
String json = ExtendJson.obj2Json(obj);
return json;
}
protected Object setInitFormObj(Object obj){
return obj;
}
protected Object code2Text(Object obj){
return obj;
}
public String getSysTypeMap(String args[]){
Map<String,String> map = SysMapRepository.getTypeMap(args[0]);
return ExtendJson.map2Json(map);
}
public String getSysTypeMapValue(String args[]){
Map<String,String> map = SysMapRepository.getTypeMap(args[0]);
return map.get(args[1]);
}
public void getSysTypeMapValueByAjax(){
String mapName = this.requestParam.getString("mapName");
String mapCode= this.requestParam.getString("mapCode");
Map<String,String> map = SysMapRepository.getTypeMap(mapName);
this.print(map.get(mapCode));
}
public String getDictMap(String args[]){
Map<String,String> map = BmCodeRepository.getBmCodeMap(args[0]);
return ExtendJson.map2Json(map);
}
public String getDictMapValue(String args[]){
Map<String,String> map = BmCodeRepository.getBmCodeMap(args[0]);
return map.get(args[1]);
}
public void getDictMapValueByAjax(){
String dictName=this.requestParam.getString("dictName");
String dictValue= this.requestParam.getString("dictValue");
Map<String,String> map = BmCodeRepository.getBmCodeMap(dictName);
this.print( map.get(dictValue));
}
public void getComboGridData(){
String dataSrcName = this.requestParam.getString("dataSrc");
String param = this.requestParam.getString("param");
int dataSrcType = this.requestParam.getInt("dataSrcType");
//System.out.print("dtype=" + dataSrcType);
int pageNo = this.requestParam.getInt("page");
int limit = this.requestParam.getInt("rows");
DataGrid dataGrid = null;
if(dataSrcType==1){
//1是映射,2是数据字典
dataGrid = SysMapRepository.getComboxGridData(dataSrcName,param, (pageNo-1) * limit, limit) ;
}else {
CodeService codeService =(CodeService) this.getBean("codeService");
ResultSet rs = codeService.findByPageFromRam(dataSrcName, param,(pageNo-1) * limit, limit);
dataGrid = new DataGrid(rs,"code","name");
}
this.print( ExtendJson.obj2Json( dataGrid));
}
/**
* 登录了返回true,否则返回false
* @return
*/
public String isLogin(String args[]){
return (this.curUser!=null) + "" ;
}
/**
* 获取指定系统参数值
* @param args
* @return
*/
public String getSysParamValue(String args[]){
return SysParamRepository.getSysParamValue(args[0]);
}
//public String baseSaveForm( Object,)
/////////////////////////////////日志管理//////////////////////////////////////////////////////////////
/**
* 在数据保存前写日志
* obj:为保存前的数据对象
* opRs:操作成功或失败
* serviceName :obj对象对应的service
*/
protected void log(Object obj,boolean opRs, String serviceName){
if(this.notLog(obj.getClass().getSimpleName())) return; //不要记录日志
SysLog log= new SysLog();
String json =ExtendJson.obj2Json(obj);
log.setAfterData( json );
Set<String> set = ExtendJson.getJsonKeySet(json);
if(!set.contains("id")) return ; //如果json中不存在id主键则返回原值
BaseService baseService = (BaseService) this.getBean(serviceName);
int id = ExtendString.parseInt( ExtendJson.getJsonValue(json, "id"));
if(id>0) {
Object obj2 = baseService.load(obj.getClass(), id);
String orObj = ExtendJson.obj2Json(obj2);
log.setBeforeData(orObj); //修改前数据 ??
}
else{
log.setBeforeData(""); //修改前数据 ??
}
String dept = "";
if("01".equals(this.curUser.getUserType())){
dept = this.curUser.getDeptId() + "," + this.curUser.getDeptName();
}
else if("02".equals(this.curUser.getUserType())){
dept = this.curUser.getUnitName();
}
log.setDept(dept);
log.setIp(this.curUser.getIp());
log.setOpTime(ExtendCalendar.getDateTime());
log.setOpType(id>0 ? "修改" : "新增");
log.setUrl( obj.getClass().toString());
log.setUserName(this.curUser.getUserName());
log.setUserNo(this.curUser.getUserId() + ":" + this.curUser.getUserNo());
log.setUserType(this.curUser.getUserType());
log.setOpRs(opRs==true? "1" : "2");
logService.save(log);
}
/**
* 记录删除日志
* id:删除的记录id
* clz:删除对象class
* serviceName :obj对象对应的service
* opRs:操作成功或失败
* serviceName :obj对象对应的service
*/
protected void delLog(int id,Class clz, boolean opRs, BaseService baseService){
if(this.notLog(clz.getSimpleName())) return; //不要记录日志
SysLog log= new SysLog();
log.setAfterData( "" );
//BaseService baseService = (BaseService) this.getBean(serviceName);
Object obj2 = baseService.load(clz, id);
String orObj = ExtendJson.obj2Json(obj2);
log.setBeforeData(orObj); //修改前数据 ??
String dept = "";
if("01".equals(this.curUser.getUserType())){
dept = this.curUser.getDeptId() + "," + this.curUser.getDeptName();
}
else if("02".equals(this.curUser.getUserType())){
dept = this.curUser.getUnitName();
}
log.setDept(dept);
log.setIp(this.curUser.getIp());
log.setOpTime(ExtendCalendar.getDateTime());
log.setOpType("删除");
log.setUrl( clz.toString());
log.setUserName(this.curUser.getUserName());
log.setUserNo(this.curUser.getUserId() + ":" + this.curUser.getUserNo());
log.setUserType(this.curUser.getUserType());
log.setOpRs(opRs==true? "1" : "2");
logService.save(log);
}
/**
* 记录删除日志
* id:删除的记录ids ,关键字间用逗号分割
* clz:删除对象class
* serviceName :obj对象对应的service
* opRs:操作成功或失败
* serviceName :obj对象对应的service
*/
protected void delLog(String ids,Class clz, boolean opRs, BaseService baseService){
if(this.notLog(clz.getSimpleName())) return; //不要记录日志
String hql = " from " + clz.getSimpleName() + " where id in ("+ ids +")";
List ls = baseService.find(hql);
for(Object obj :ls){
SysLog log= new SysLog();
log.setAfterData( "" );
//BaseService baseService = (BaseService) this.getBean(serviceName);
log.setBeforeData( ExtendJson.obj2Json(obj) ); //修改前数据 ??
String dept = "";
if("01".equals(this.curUser.getUserType())){
dept = this.curUser.getDeptId() + "," + this.curUser.getDeptName();
}
else if("02".equals(this.curUser.getUserType())){
dept = this.curUser.getUnitName();
}
log.setDept(dept);
log.setIp(this.curUser.getIp());
log.setOpTime(ExtendCalendar.getDateTime());
log.setOpType("删除");
log.setUrl( clz.toString());
log.setUserName(this.curUser.getUserName());
log.setUserNo(this.curUser.getUserId() + ":" + this.curUser.getUserNo());
log.setUserType(this.curUser.getUserType());
log.setOpRs(opRs==true? "1" : "2");
logService.save(log);
}
}
/**
* 在数据保存前写日志
* obj:为保存前的数据对象
* opRs:操作成功或失败
* opType:1:新增,2修改,3删除
* serviceName :obj对象对应的service
*/
protected void log(Object obj,boolean opRs,int opType, String serviceName){
if(this.notLog(obj.getClass().getSimpleName())) return; //不要记录日志
if(opType==1){
SysLog log= new SysLog();
log.setAfterData( ExtendJson.obj2Json(obj) );
log.setBeforeData("");
String dept = "";
if("01".equals(this.curUser.getUserType())){
dept = this.curUser.getDeptId() + "," + this.curUser.getDeptName();
}
else if("02".equals(this.curUser.getUserType())){
dept = this.curUser.getUnitName();
}
log.setDept(dept);
log.setIp(this.curUser.getIp());
log.setOpTime(ExtendCalendar.getDateTime());
log.setOpType("新增");
log.setUrl( obj.getClass().toString() );
log.setUserName(this.curUser.getUserName());
log.setUserNo(this.curUser.getUserId() + ":" + this.curUser.getUserNo());
log.setUserType(this.curUser.getUserType());
log.setOpRs(opRs==true? "1" : "2");
logService.save(log);
}
else if(opType==2){
SysLog log= new SysLog();
String json =ExtendJson.obj2Json(obj);
log.setAfterData( json );
Set<String> set = ExtendJson.getJsonKeySet(json);
if(!set.contains("id")) return ; //如果json中不存在id主键则返回原值
BaseService baseService = (BaseService) this.getBean(serviceName);
int id = ExtendString.parseInt( ExtendJson.getJsonValue(json, "id"));
Object obj2 = baseService.load(obj.getClass(), id);
String orObj = ExtendJson.obj2Json(obj2);
log.setBeforeData(orObj); //修改前数据 ??
String dept = "";
if("01".equals(this.curUser.getUserType())){
dept = this.curUser.getDeptId() + "," + this.curUser.getDeptName();
}
else if("02".equals(this.curUser.getUserType())){
dept = this.curUser.getUnitName();
}
log.setDept(dept);
log.setIp(this.curUser.getIp());
log.setOpTime(ExtendCalendar.getDateTime());
log.setOpType("修改");
log.setUrl( obj.getClass().toString());
log.setUserName(this.curUser.getUserName());
log.setUserNo(this.curUser.getUserId() + ":" + this.curUser.getUserNo());
log.setUserType(this.curUser.getUserType());
log.setOpRs(opRs==true? "1" : "2");
logService.save(log);
}
else if(opType==3){
SysLog log= new SysLog();
log.setAfterData( "" );
log.setBeforeData(ExtendJson.obj2Json(obj));
String dept = "";
if("01".equals(this.curUser.getUserType())){
dept = this.curUser.getDeptId() + "," + this.curUser.getDeptName();
}
else if("02".equals(this.curUser.getUserType())){
dept = this.curUser.getUnitName();
}
log.setDept(dept);
log.setIp(this.curUser.getIp());
log.setOpTime(ExtendCalendar.getDateTime());
log.setOpType("删除");
log.setUrl( obj.getClass().toString());
log.setUserName(this.curUser.getUserName());
log.setUserNo(this.curUser.getUserId() + ":" + this.curUser.getUserNo());
log.setUserType(this.curUser.getUserType());
log.setOpRs(opRs==true? "1" : "2");
logService.save(log);
}
}
private SysLogService logService = (SysLogService) this.getBean("sysLogService");
protected void log( List insertedRecords, List updatedList, List deletedRecords,boolean opRs, String serviceName){
for(Object obj:insertedRecords){
this.log(obj, opRs, 1, serviceName);
}
for(Object obj:updatedList){
this.log(obj, opRs, 2, serviceName);
}
for(Object obj:deletedRecords){
this.log(obj, opRs, 3, serviceName);
}
}
private SysLogCfgService logCfgService = (SysLogCfgService) this.getBean("sysLogCfgService");
private Map<String,String> sysLogCfgMap = new HashMap<String,String>();
private boolean notLog(String clz){
if( sysLogCfgMap.isEmpty()){
List<SysLogCfg> ls = logCfgService.findAll();
sysLogCfgMap = logCfgService.ls2Map(ls, "clz", "clz");
}
return sysLogCfgMap.get(clz)==null;
}
/**
* 初始化屏幕高度和宽度,以便在后续的窗口中使用
* @param args
* @return
*/
public String setWinWH(String args[]){
this.session.setAttribute("winWidth", args[0]);
this.session.setAttribute("winHeight", args[1]);
return "true";
}
}
basedaohibernate
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fins.gt.util.JSONUtils;
import org.apache.commons.collections.bag.SynchronizedSortedBag;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.hql.ast.QueryTranslatorImpl;
import org.junit.Test;
import org.springframework.orm.hibernate3.HibernateCallback;
import redis.clients.jedis.Jedis;
public class BaseDaoHiberante<T> extends DaoHibernate implements BaseDao<T> {
private Logger log = Logger.getLogger(BaseDaoHiberante.class);
/**
* 通过ID获取对象.
*
* @param clz
* Class
* @param id
* Serializable
* @return Object
*/
public T get(Class clz, Serializable id) {
return (T) this.getHibernateTemplate().get(clz, id);
}
/**
* 保存对象到数据库.
*
* @param entity
* Object
*/
public Serializable save(T entity) {
String entityName = entity.getClass().getSimpleName();
RedisUtil.delentity(entityName);
Serializable id=getHibernateTemplate().save(entity);
getHibernateTemplate().flush();
return id;
}
/**
* 从数据库中删除对象
*
* @更新作者:bingo
* @param entity
* Object
*/
public void delete(T entity) {
String entityName = entity.getClass().getSimpleName();
RedisUtil.delentity(entityName);
this.getHibernateTemplate().delete(entity);
}
/**
* 通过ID,数据库中删除数据
*
* @param clazz
* Class
* @param id
* Serializable
*/
public void delete(Class clazz, Serializable id) {
String entityName = clazz.getSimpleName();
RedisUtil.delentity(entityName);
getHibernateTemplate().delete(this.get(clazz, id));
//String hql = " delete from " + clazz.getSimpleName() + " where id=" + id;
}
/**
* 通过HQL语句获取对象结果集
*
* @param hql
* String
* @return List
*/
public List<T> find(String hql) {
if (RedisUtil.isRidisRun()) {
if (RedisUtil.get(hql)==null) {
List<T> list=getHibernateTemplate().find(hql);
RedisUtil.setList(hql, list);
return list;
}else {
//new UpdateCache(hql,1).start();
return (List<T>) RedisUtil.getList(hql);
}
}
return getHibernateTemplate().find(hql);
}
/**
* 通过HQL语句和value参数获取对象结果集
*
* @param hql
* String
* @param value
* Object
* @return List
*/
public List<T> find(String hql, Object value) {
//return getHibernateTemplate().find(hql, value);
String hqlkey = hql + value;
if (RedisUtil.isRidisRun()) {
if (RedisUtil.get(hqlkey)==null) {
List<T> list=getHibernateTemplate().find(hql, value);
RedisUtil.setList(hqlkey, list);
return list;
}else {
//new UpdateCache(hql,value,2,hqlkey).start();
return (List<T>) RedisUtil.getList(hqlkey);
}
}
return getHibernateTemplate().find(hql, value);
}
/**
* 通过HQL语句和value[]参数集获取对象结果集,调用方式如:find(hql,new Object[]{value1,value2})
*
* @param hql
* String
* @param values
* Object[]
* @return List
*/
public List<T> find(String hql, Object[] values) {
String valuess="";
String hqlkey = hql;
for (Object value : values) {
valuess += value;
}
hqlkey += valuess;
if (RedisUtil.isRidisRun()) {
if (RedisUtil.get(hqlkey)==null) {
List<T> list=getHibernateTemplate().find(hql, values);
RedisUtil.setList(hqlkey, list);
return list;
}else {
//new UpdateCache(hql, values, 4, hqlkey).start();
return (List<T>) RedisUtil.getList(hqlkey);
}
}
return getHibernateTemplate().find(hql, values);
}
/**
* 使用DetachedCriteria来构造查询条件.
*
* @param dcri
* DetachedCriteria
* @return List
*/
public List<T> find(DetachedCriteria dcri) {
return dcri.getExecutableCriteria(this.getSession()).list();
}
/**
* 保存或者更新对象到数据库.
*
* @param entity
* Object
*/
public void saveOrUpdate(T entity) {
String entityName = entity.getClass().getSimpleName();
Jedis jedis = RedisUtil.getJedis();
if (jedis != null) {
List<String> list = jedis.lrange(entityName,0,-1);
for(int i=0; i<list.size(); i++) {
System.out.println("列表项为: "+list.get(i));
jedis.del(list.get(i));
}
jedis.del(entityName);
RedisUtil.close(jedis);
getHibernateTemplate().saveOrUpdate(entity);
getHibernateTemplate().flush();
}else{
getHibernateTemplate().saveOrUpdate(entity);
getHibernateTemplate().flush();
}
}
@Test
public void tesss(){
//连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost");
System.out.println("连接成功");
// 获取存储的数据并输出
List<String> list = jedis.lrange("CydwJbxx", 0 ,-1);
for(int i=0; i<list.size(); i++) {
System.out.println("列表项为: "+list.get(i));
jedis.del(list.get(i));
}
List<String> list2 = RedisUtil.lrangeList("CydwJbxx");
for(int i=0; i<list2.size(); i++) {
System.out.println("列表项为: "+list2.get(i));
}
}
/**
* 更新对象到数据库.
*
* @param entity
* Object
*/
public void update(T entity) {
String entityName = entity.getClass().getSimpleName();
RedisUtil.delentity(entityName);
getHibernateTemplate().update(entity);
getHibernateTemplate().flush();
}
public void refresh(T entity){
getHibernateTemplate().refresh(entity);
}
/**
* 分页(段)查询
*
* @param queryString
* String
* @param start
* 第几页(段) int
* @param limit
* 每页返回几条数据 int
* @return List
*/
public List<T> findPaginate(final String queryString, final int start,
final int limit) {
HibernateCallback hc = new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(queryString);
if(start!=-1 && limit!=-1){
query.setMaxResults(limit);
query.setFirstResult(start);
}
return query.list();
}
};
String redisKey = queryString + limit +":"+ start;
if (RedisUtil.isRidisRun()) {
if(RedisUtil.get(redisKey.replaceAll(" ",""))==null){
List<T> list= getHibernateTemplate().executeFind(hc);
//RedisUtil.set(redisKey, JSON.toJSON(list).toString());
RedisUtil.setList(redisKey, list);
return list;
}else{
//返回缓存
List<T> list = (List<T>) RedisUtil.getList(redisKey);
return list;
}
}
return getHibernateTemplate().executeFind(hc);
}
public List<T> findPaginate(final String queryString,
final HqlParam[] qParams, final int start, final int limit) {
HibernateCallback hc = new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(queryString);
if (qParams != null) {
for (int i = 0; i < qParams.length; i++) {
query.setParameter(i, qParams[i].getValue(), qParams[i]
.getType());
}
}
if(start!=-1 && limit!=-1){
query.setMaxResults(limit);
query.setFirstResult(start);
}
return query.list();
}
};
String redisKey = queryString + limit +":"+ start;
if (RedisUtil.isRidisRun()) {
if(RedisUtil.get(redisKey.replaceAll(" ",""))==null){
List<T> list= getHibernateTemplate().executeFind(hc);
//RedisUtil.set(redisKey, JSON.toJSON(list).toString());
RedisUtil.setList(redisKey, list);
return list;
}else{
//返回缓存
List<T> list = (List<T>) RedisUtil.getList(redisKey);
return list;
}
}
return getHibernateTemplate().executeFind(hc);
}
public ResultSet<T> findRSPaginate(final String queryString, final int start,
final int limit) {
int totalRows = 0;
//System.out.println("hql=" + queryString);
List<T> l = this.findPaginate(queryString, start, limit);
if (l != null && l.size() != 0) {
//totalRows = this.getHibernateTemplate().find(queryString).size();
totalRows = this.getCount(queryString);
}
ResultSet<T> rs = new ResultSet<T>(l, totalRows);
return rs;
}
public ResultSet<T> findRSPaginate(final String queryString,
final HqlParam[] qParams, final int start, final int limit) {
int totalRows = 0;
List<T> l = this.findPaginate(queryString, qParams, start, limit);
if (l != null && l.size() != 0) {
if (qParams != null) {
Object[] values = new Object[qParams.length];
for (int i = 0; i < qParams.length; i++) {
values[i] = qParams[i].getValue();
}
totalRows = this.getCount(queryString, values);
} else {
totalRows = this.getCount(queryString);
}
}
ResultSet<T> rs = new ResultSet<T>(l, totalRows);
return rs;
}
private int getCount(String hql ,Object[] objs){
if(hql.indexOf("distinct") >0){
// Query query = this.createQuery(hql,objs);
// long count = query.list().size();
// return (int) count;
return this.find(hql).size();
}
else{
hql = "select count(*) " + hql.substring( hql.toLowerCase().indexOf("from"));
//System.out.println("getCount=" + hql);
//String hql = hql.toLowerCase().contains("where") ? "" : " select * from "
return this.countByHql(hql,objs);
}
}
private int getCount(String hql){
if(hql.indexOf("distinct") >0||hql.indexOf("group")>0){
// Query query = this.createQuery(hql);
// long count = query.list().size();
// return (int) count;
return this.find(hql).size();
}
else{
//获取表
hql = "select count(*) " + hql.substring( hql.toLowerCase().indexOf("from"));
//System.out.println("getCount=" + hql);
//String hql = hql.toLowerCase().contains("where") ? "" : " select * from "
return this.countByHql(hql);
}
}
public Long getDataTotal(String hql, Object[] values) {
QueryTranslatorImpl queryTranslator = new QueryTranslatorImpl(hql, hql,
Collections.EMPTY_MAP, (SessionFactoryImplementor) this
.getSessionFactory());
queryTranslator.compile(Collections.EMPTY_MAP, false);
String tempSQL = queryTranslator.getSQLString();
String countSQL = "select count(*) from (" + tempSQL + ") tmp_count_t";
Query query = this.getSession().createSQLQuery(countSQL);
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
List list = query.list();
BigDecimal count = list == null || list.size() <= 0 ? new BigDecimal(0)
: (BigDecimal) list.get(0);
return count.longValue();
}
}