package com.eqcp.framework.common.cache;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import com.eqcp.framework.common.util.StringUtil;
import com.eqcp.framework.dao.SysDictDao;
import com.eqcp.framework.model.SysDict;
/**
* 数据字典缓存类
* @author kun.yang
*
*/
public final class DictCache {
private static DictCache instance;
private static ApplicationContext context;
public static final String PRIMARY_ITEM = "_PRIMARY_";//一级字典项
private static Map<String,List<SysDict>> DICT_MAP = new HashMap<String,List<SysDict>>();
private DictCache(){
}
public static void init(ApplicationContext as){
context = as;
initDictMap();
}
public static DictCache getInstance(){
if(instance==null){
instance = new DictCache();
}
return instance;
}
private static void initDictMap(){
SysDictDao sysDictDao = (SysDictDao) context.getBean("sysDictDao");
List<SysDict> dictList = sysDictDao.findAll();
if(dictList!=null && dictList.size()>0){
for(SysDict dict:dictList){
if(dict!=null && dict.getStatus()!=null
&& !PRIMARY_ITEM.equals(dict.getKindCode())){
List<SysDict> dicts = DICT_MAP.get(dict.getKindCode());
if(dicts == null){
dicts = new ArrayList<SysDict>();
}
dicts.add(dict);
DICT_MAP.put(dict.getKindCode(), dicts);
}
}
}
}
public static void reloadDictMap(){
clearDictMap();
initDictMap();
}
public static void clearDictMap(){
DICT_MAP.clear();
}
public static List<SysDict> getDictsByKindCode(String kindCode,String cond1,String cond2,String order){
if(DICT_MAP.size() == 0){
reloadDictMap();
}
List<SysDict> resultList = new ArrayList<SysDict>();
List<SysDict> dicts = DICT_MAP.get(kindCode);
int sum = 0;
if(cond1!=null){
sum = 10;
}
if(cond2!=null){
sum = sum + 1;
}
if(dicts!=null && dicts.size()>0){
for(SysDict dict:dicts){
if(dict.getStatus() != 1){
continue;
}
switch (sum) {
case 0:
resultList.add(dict);break;
case 1:
if(cond2.equals(dict.getCond2()))
resultList.add(dict);break;
case 10:
if(cond1.equals(dict.getCond1()))
resultList.add(dict);break;
case 11:
if(cond1.equals(dict.getCond1()) && cond1.equals(dict.getCond2()))
resultList.add(dict);break;
}
}
}
return sort(resultList,order);
}
public static SysDict getDict(String kindCode,String dictCode){
if(!StringUtil.isNotEmptyAndBlank(dictCode)){
return null;
}
if(DICT_MAP.size() == 0){
reloadDictMap();
}
List<SysDict> dicts = DICT_MAP.get(kindCode);
if(dicts!=null && dicts.size()>0){
for(SysDict temp:dicts){
if(dictCode.equals(temp.getDictCode())){
return temp;
}
}
}
return null;
}
public static String getDictName(String kindCode,String dictCode){
if(kindCode == null || dictCode == null){
return null;
}
if(DICT_MAP.size() == 0){
reloadDictMap();
}
List<SysDict> dicts = DICT_MAP.get(kindCode);
if(dicts!=null && dicts.size()>0){
for(SysDict dict:dicts){
if(dictCode.equals(dict.getDictCode())){
return dict.getDictName();
}
}
}
return "";
}
private static List<SysDict> sort(final List<SysDict> list,final String orber){
Collections.sort(list, new Comparator<SysDict>(){
public int compare(SysDict o1, SysDict o2) {
int no1 = o1.getOrderNo()!=null?o1.getOrderNo():0;
int no2 = o2.getOrderNo()!=null?o2.getOrderNo():0;
if(orber == null || "asc".equals(orber)){
return no1-no2;
}else{
return no2-no1;
}
}
});
return list;
}
public static String getDictCode(String kindCode,String dictName){
if(kindCode == null || dictName == null){
return null;
}
if(DICT_MAP.size() == 0){
reloadDictMap();
}
List<SysDict> dicts = DICT_MAP.get(kindCode);
if(dicts!=null && dicts.size()>0){
for(SysDict dict:dicts){
if(dictName.equals(dict.getDictName())){
return dict.getDictCode();
}
}
}
return null;
}
}
package com.eqcp.framework.common.cache;
import java.io.IOException;
import net.spy.memcached.*;
import com.eqcp.framework.common.exception.AppException;
public final class MemcachedCache {
// config: /resources/config.properties
private static MemcachedClient client;
public MemcachedCache(){
}
public static synchronized MemcachedClient getInstance(){
if (client == null) {
String address = ConfigCache.getProperty("memcachedAddress");
try {
if(address == null || address == ""){
throw new AppException("Memcached 服务器地址错误");
}
client = new MemcachedClient(AddrUtil.getAddresses(address));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return client;
}
public static Object get(String key){
return getInstance().get(key);
}
/**
* 设置缓存.
* @param exp 过期时间(秒)
*/
public static void set(String key, int exp, Object value){
getInstance().set(key, exp, value);
}
}
package com.eqcp.framework.common.exception;
/**
*
* 异常处理类
*
* @author :txh
* @version :{版本}
* @date:
*/
public class AppException extends RuntimeException {
private static final long serialVersionUID = 1L;
private static final String CAUSED_BY = "aCaused by: ";
private Throwable cause = null;
public AppException(){};
public AppException(String msg){
super(msg);
}
public AppException(String msg,Throwable cause){
super(msg);
this.cause = cause;
}
public AppException(Throwable cause){
this.cause = cause;
}
public Throwable getCause() {
return cause;
}
public String toString() {
if (cause == null) {
return super.toString();
} else {
return super.toString() + CAUSED_BY + cause.toString();
}
}
public void printStackTrace() {
super.printStackTrace();
if (cause != null) {
System.err.println(CAUSED_BY);
cause.printStackTrace();
}
}
public void printStackTrace(java.io.PrintStream ps) {
super.printStackTrace(ps);
if (cause != null) {
ps.println(CAUSED_BY);
cause.printStackTrace(ps);
}
}
public void printStackTrace(java.io.PrintWriter pw) {
super.printStackTrace(pw);
if (cause != null) {
pw.println(CAUSED_BY);
cause.printStackTrace(pw);
}
}
}
package com.eqcp.framework.common.util;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CalendarUtil {
protected static final Logger log = LoggerFactory.getLogger(CalendarUtil.class);
/**
* * 指定周的日期
* @param n为推迟的周数,1本周,-1向前推迟一周,2下周,依次类推
* @param dayOfWeek 想周几,这里就传几Calendar.MONDAY(TUESDAY...)
* @param f 日期格式
* @return
*/
public static String getDateByWeek(int n,int day,String f){
Calendar cal = Calendar.getInstance();
String monday;
cal.add(Calendar.DATE, n*7);
//cal.set(Calendar.DAY_OF_WEEK,Calendar.THURSDAY);
cal.set(Calendar.DAY_OF_WEEK,day);
monday = new SimpleDateFormat(f).format(cal.getTime());
//System.out.println(monday);
log.debug(monday);
return monday;
}
/**
* 上一周星期N的日期
* @return
*/
public static String getDateByLastWeek(int day){
return getDateByWeek(-1,day,"yyyy-MM-dd");
}
/**
* 本周某星期的日期
* @param day
* @return
*/
public static String getDateThisWeek(int day){
//return getDateByWeek(0,day,"yyyy-MM-dd HH:mm:ss");
return getDateByWeek(0,day,"yyyy-MM-dd");
}
}
package com.eqcp.framework.common.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
/**
* 集合帮助类
* @author kun.yang
*
*/
public class CollectionUtil {
/**
* 数组转集合List
* @Title: toArrayList
* @Description: 描述
* @author kun.yang
* @param @param objs
* @param @return 设定文件
* @return List 返回类型
* @throws
*/
public static List toArrayList(Object...objs){
List result = new ArrayList();
if(objs!=null && objs.length>0){
for(Object o:objs){
result.add(o);
}
}
return result;
}
public static Map<String,Object> toHashMap(String[]keys,Object[]values ){
Map<String,Object> map = new HashMap<String,Object>(keys.length);
if(keys!=null && values!=null){
if(keys.length!=values.length){
throw new RuntimeException("参数个数不匹配,请检查!");
}
for(int i=0;i<keys.length;i++){
map.put(keys[i], values[i]);
}
}
return map;
}
public static Map<String,Object> toHashMap(String key,Object value){
Map<String,Object> map = new HashMap<String,Object>(1);
map.put(key, value);
return map;
}
/**
* 集合是否为空
* @param cols
* @return
*/
public static boolean isNotEmpty(Collection cols){
if(cols != null && cols.size() > 0){
return true;
}else{
return false;
}
}
/**
* 从集合中去掉重复,并保持原有的顺序
* @param list
* @return
*/
public static <E> List<E> withoutDuplicates(List<E> original){
if(original == null || original.size()==0){
return original;
}
return new ArrayList<E>(new LinkedHashSet<E>(original));
}
}
package com.eqcp.framework.common.util;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
public class CommonUtil {
public static final String DB_DIALECT = "ORACLE";
/**
* 判断某个对象是否为空 集合类、数组做特殊处理
*
* @param obj
* @return 如为空,返回true,否则false
*/
public static boolean isEmpty(Object obj) {
if (obj == null)
return true;
// 如果不为null,需要处理几种特殊对象类型
if (obj instanceof String) {
return obj.equals("");
} else if (obj instanceof Collection) {
// 对象为集合
Collection coll = (Collection) obj;
return coll.size() == 0;
} else if (obj instanceof Map) {
// 对象为Map
Map map = (Map) obj;
return map.size() == 0;
} else if (obj.getClass().isArray()) {
// 对象为数组
return Array.getLength(obj) == 0;
} else {
// 其他类型,只要不为null,即不为empty
return false;
}
}
/**
* <p>
* (不建议使用这种方式查询,会造成url太长)
* 根据request传入的参数构造查询条件语句
*
* <li>查询参数名必须包含$Q_的特殊标志
* <li>$Q_后面的字符串与数据库字段对应
* <li>$Q_前面的字符串位查询匹配方式(如=,like,>=)
* <li>如不指定,时间默认匹配为=,其他默认为like
* <li>当传入的参数值匹配DATA_FORMAT/TIME_FORMAT,则当时间处理
* <li>eq$Q_xxx 在url中严格字符串匹配
* @param request HttpServletRequest
* @return 查询条件hql语句
*
*/
@Deprecated
public static String getQueryHql(HttpServletRequest request) {
StringBuffer buf = new StringBuffer();
Enumeration params = request.getParameterNames();
String param = null;
String value = null;
int i = 0;
HashMap qMap = new HashMap();
while (params.hasMoreElements()) {
param = (String) params.nextElement();
value = request.getParameter(param);
String mode = "";// 查询模式
if (param.startsWith("_") || param.startsWith("$CODEVALUE_")) {
continue;
}
if (value == null || value.equalsIgnoreCase("null")) {
continue;
}
if (value.trim().length() == 0) {
continue;
}
value = value.trim();
if (param.indexOf("$Q_") != -1) {
i++;
if (i != 1) {
buf.append(" and ");
}
// 字段名
buf.append(param.substring(param.indexOf("$Q_") + 3));
// 保存查询条件
qMap.put(param, value);
// 防止'注入
if (value.indexOf("'") != -1) {
value = value.replaceAll("'", "''");
}
String temp = param.substring(0, param.indexOf("$Q_"));
if (!isEmpty(temp)) {
mode = temp;
}
// 查询值
// 是否是时间
boolean timeFlag = false;
if (value.indexOf("-") != -1) {
String[] valueDatas = value.split("-");
if (valueDatas != null && valueDatas.length == 2) {
if (StringUtil.isDigitalString(valueDatas[0]) && StringUtil.isDigitalString(valueDatas[1])) {
int yearTag = Integer.parseInt(valueDatas[0]);
int monthTag = Integer.parseInt(valueDatas[1]);
if (yearTag < 2100 && yearTag > 1900 && monthTag >= 1 && monthTag < 13) {
value = value + "-01";
}
}
}
SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATA_FORMAT);
SimpleDateFormat timeFormat = new SimpleDateFormat(Constants.TIME_FORMAT);
try {
dateFormat.parse(value);
timeFlag = true;
} catch (ParseException e) {
try {
timeFormat.parse(value);
timeFlag = true;
} catch (ParseException e1) {
timeFlag = false;
}
}
}
// 查询方式
if (isEmpty(mode)) {
// 默认查询模式
if (timeFlag) {
mode = "=";
} else {
mode = "like";
}
}
if(mode.length()!=0 && (mode.equals("#=") || mode.equals("eq"))){
buf.append(" = ");
}else{
buf.append(" " + mode + " ");
}
if (!timeFlag && mode.length()!=0 && !mode.equals("#=")) {
buf.append(" '");
}else{
buf.append(" ");
}
if (mode.equals("like")) {
buf.append("%");
}
if (timeFlag) {
if (value.indexOf(":") == -1 && mode.indexOf("<") != -1 ) {
value += " 23:59:59";
}
if(value.indexOf(":") == -1 && mode.indexOf(">") != -1){
value += " 00:00:00";
}
if (DB_DIALECT.equals("ORACLE") || DB_DIALECT.equals("oracle")) {
buf.append("To_date('" + value + "','yyyy-mm-dd hh24:mi:ss')");
} else {
buf.append("'" + value + "'");
}
} else {
buf.append(value);
}
if (mode.equals("like")) {
buf.append("%");
}
if (!timeFlag && mode.length()!=0 && !mode.equals("#=")) {
buf.append("'");
}else{
buf.append(" ");
}
}
}
request.setAttribute("qMap", qMap);
return buf.toString();
}
public static String encodeURI(String str){
try {
return java.net.URLEncoder.encode(str, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public static String encodeURI(String str,String enc){
try {
return java.net.URLEncoder.encode(str,enc);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public static String decodeURI(String str){
try {
return java.net.URLDecoder.decode(str,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public static String decodeURI(String str,String enc){
try {
return java.net.URLDecoder.decode(str,enc);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
}