test
1 package com.eqcp.framework.common.cache; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.util.HashMap; 7 import java.util.Iterator; 8 import java.util.Map; 9 import java.util.Properties; 10 import java.util.Set; 11 12 import javax.servlet.ServletContext; 13 14 import org.apache.commons.logging.Log; 15 import org.apache.commons.logging.LogFactory; 16 17 import com.eqcp.framework.common.util.Constants; 18 19 /** 20 * 加载配置文件 21 * 22 * @author kun.yang 23 * 24 */ 25 public class ConfigCache { 26 27 private static final String[] CONFIG_FILES = new String[]{"config.properties"}; 28 29 private static final Map<String, String> CONFIG_MAP = new HashMap<String, String>(); 30 31 private static final Log log = LogFactory.getLog(ConfigCache.class); 32 33 34 35 public static void init(ServletContext sc){ 36 //加入项目绝对目录 37 String appHome = sc.getRealPath("/").replace("\\", "/"); 38 if (!appHome.endsWith("/")) { 39 appHome = appHome + "/"; 40 } 41 CONFIG_MAP.put(Constants.APP_HOME,appHome); 42 43 //加载配置文件 44 loadConfigFiles(); 45 46 //CONFIG_MAP.put(Constants.APP_CONTEXT_PATH, sc.getContextPath()); 47 //项目路径不存在,则给默认值clcpm 48 if(CONFIG_MAP.get(Constants.APP_CONTEXT_PATH)==null){ 49 CONFIG_MAP.put(Constants.APP_CONTEXT_PATH, "/clcpm"); 50 } 51 52 } 53 54 /** 55 * 加载配置文件 56 */ 57 public static void loadConfigFiles(){ 58 for(String file:CONFIG_FILES){ 59 InputStream in = ConfigCache.class.getClassLoader().getResourceAsStream("resources"+File.separator+file); 60 Properties p = new Properties(); 61 try { 62 p.load(in); 63 } catch (IOException e) { 64 e.printStackTrace(); 65 } 66 Set keySet = p.keySet(); 67 Iterator it = keySet.iterator(); 68 while(it.hasNext()){ 69 String key = (String)it.next(); 70 if(key!=null && p.getProperty(key)!=null){ 71 CONFIG_MAP.put(key.trim(),p.getProperty(key).trim()); 72 } 73 } 74 } 75 } 76 77 public static String getProperty(String key){ 78 return CONFIG_MAP.get(key); 79 } 80 81 public static void setProperty(String key,String value){ 82 CONFIG_MAP.put(key, value); 83 } 84 85 public static void clearConfigMap(){ 86 CONFIG_MAP.clear(); 87 } 88 89 public static void printConfigMap(){ 90 log.info("=============ConfigCache Begin====================="); 91 for(Map.Entry<String, String> e : CONFIG_MAP.entrySet()){ 92 log.info(e.getKey() + "=" + e.getValue()); 93 } 94 log.info("=============ConfigCache End======================="); 95 } 96 97 /** 98 * 获得项目绝对路径 99 * @return 100 */ 101 public static String getAppHome(){ 102 return CONFIG_MAP.get(Constants.APP_HOME); 103 } 104 105 /** 106 * 获得项目路径 107 * @return 108 */ 109 public static String getAppContextPath(){ 110 return CONFIG_MAP.get(Constants.APP_CONTEXT_PATH); 111 } 112 }
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 ""; } }
posted on 2013-08-02 17:19 Mrrr-Workroon 阅读(163) 评论(0) 收藏 举报
浙公网安备 33010602011771号