1 package com.eqcp.framework.common.cache; 2 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.Comparator; 6 import java.util.HashMap; 7 import java.util.List; 8 import java.util.Map; 9 10 import org.springframework.context.ApplicationContext; 11 12 import com.eqcp.framework.common.util.StringUtil; 13 import com.eqcp.framework.dao.SysDictDao; 14 import com.eqcp.framework.model.SysDict; 15 16 /** 17 * 数据字典缓存类 18 * @author kun.yang 19 * 20 */ 21 public final class DictCache { 22 23 private static DictCache instance; 24 25 private static ApplicationContext context; 26 27 public static final String PRIMARY_ITEM = "_PRIMARY_";//一级字典项 28 29 private static Map<String,List<SysDict>> DICT_MAP = new HashMap<String,List<SysDict>>(); 30 31 private DictCache(){ 32 33 } 34 public static void init(ApplicationContext as){ 35 context = as; 36 initDictMap(); 37 } 38 39 public static DictCache getInstance(){ 40 if(instance==null){ 41 instance = new DictCache(); 42 } 43 return instance; 44 } 45 46 private static void initDictMap(){ 47 SysDictDao sysDictDao = (SysDictDao) context.getBean("sysDictDao"); 48 List<SysDict> dictList = sysDictDao.findAll(); 49 if(dictList!=null && dictList.size()>0){ 50 for(SysDict dict:dictList){ 51 if(dict!=null && dict.getStatus()!=null 52 && !PRIMARY_ITEM.equals(dict.getKindCode())){ 53 List<SysDict> dicts = DICT_MAP.get(dict.getKindCode()); 54 if(dicts == null){ 55 dicts = new ArrayList<SysDict>(); 56 } 57 dicts.add(dict); 58 DICT_MAP.put(dict.getKindCode(), dicts); 59 } 60 } 61 } 62 } 63 64 public static void reloadDictMap(){ 65 clearDictMap(); 66 initDictMap(); 67 } 68 69 public static void clearDictMap(){ 70 DICT_MAP.clear(); 71 } 72 73 public static List<SysDict> getDictsByKindCode(String kindCode,String cond1,String cond2,String order){ 74 if(DICT_MAP.size() == 0){ 75 reloadDictMap(); 76 } 77 List<SysDict> resultList = new ArrayList<SysDict>(); 78 List<SysDict> dicts = DICT_MAP.get(kindCode); 79 int sum = 0; 80 if(cond1!=null){ 81 sum = 10; 82 } 83 if(cond2!=null){ 84 sum = sum + 1; 85 } 86 if(dicts!=null && dicts.size()>0){ 87 for(SysDict dict:dicts){ 88 if(dict.getStatus() != 1){ 89 continue; 90 } 91 switch (sum) { 92 case 0: 93 resultList.add(dict);break; 94 case 1: 95 if(cond2.equals(dict.getCond2())) 96 resultList.add(dict);break; 97 case 10: 98 if(cond1.equals(dict.getCond1())) 99 resultList.add(dict);break; 100 case 11: 101 if(cond1.equals(dict.getCond1()) && cond1.equals(dict.getCond2())) 102 resultList.add(dict);break; 103 } 104 } 105 } 106 return sort(resultList,order); 107 } 108 109 public static SysDict getDict(String kindCode,String dictCode){ 110 if(!StringUtil.isNotEmptyAndBlank(dictCode)){ 111 return null; 112 } 113 if(DICT_MAP.size() == 0){ 114 reloadDictMap(); 115 } 116 List<SysDict> dicts = DICT_MAP.get(kindCode); 117 if(dicts!=null && dicts.size()>0){ 118 for(SysDict temp:dicts){ 119 if(dictCode.equals(temp.getDictCode())){ 120 return temp; 121 } 122 } 123 } 124 125 return null; 126 } 127 128 public static String getDictName(String kindCode,String dictCode){ 129 if(kindCode == null || dictCode == null){ 130 return null; 131 } 132 if(DICT_MAP.size() == 0){ 133 reloadDictMap(); 134 } 135 List<SysDict> dicts = DICT_MAP.get(kindCode); 136 if(dicts!=null && dicts.size()>0){ 137 for(SysDict dict:dicts){ 138 if(dictCode.equals(dict.getDictCode())){ 139 return dict.getDictName(); 140 } 141 } 142 } 143 return ""; 144 } 145 146 private static List<SysDict> sort(final List<SysDict> list,final String orber){ 147 Collections.sort(list, new Comparator<SysDict>(){ 148 public int compare(SysDict o1, SysDict o2) { 149 int no1 = o1.getOrderNo()!=null?o1.getOrderNo():0; 150 int no2 = o2.getOrderNo()!=null?o2.getOrderNo():0; 151 if(orber == null || "asc".equals(orber)){ 152 return no1-no2; 153 }else{ 154 return no2-no1; 155 } 156 } 157 }); 158 return list; 159 } 160 161 public static String getDictCode(String kindCode,String dictName){ 162 if(kindCode == null || dictName == null){ 163 return null; 164 } 165 if(DICT_MAP.size() == 0){ 166 reloadDictMap(); 167 } 168 List<SysDict> dicts = DICT_MAP.get(kindCode); 169 if(dicts!=null && dicts.size()>0){ 170 for(SysDict dict:dicts){ 171 if(dictName.equals(dict.getDictName())){ 172 return dict.getDictCode(); 173 } 174 } 175 } 176 return null; 177 } 178 } 179 180 package com.eqcp.framework.common.cache; 181 182 import java.io.IOException; 183 import net.spy.memcached.*; 184 import com.eqcp.framework.common.exception.AppException; 185 186 public final class MemcachedCache { 187 // config: /resources/config.properties 188 private static MemcachedClient client; 189 190 public MemcachedCache(){ 191 } 192 193 public static synchronized MemcachedClient getInstance(){ 194 if (client == null) { 195 String address = ConfigCache.getProperty("memcachedAddress"); 196 try { 197 if(address == null || address == ""){ 198 throw new AppException("Memcached 服务器地址错误"); 199 } 200 client = new MemcachedClient(AddrUtil.getAddresses(address)); 201 } catch (IOException e) { 202 // TODO Auto-generated catch block 203 e.printStackTrace(); 204 } 205 } 206 return client; 207 } 208 209 public static Object get(String key){ 210 return getInstance().get(key); 211 } 212 213 /** 214 * 设置缓存. 215 * @param exp 过期时间(秒) 216 */ 217 public static void set(String key, int exp, Object value){ 218 getInstance().set(key, exp, value); 219 } 220 } 221 222 package com.eqcp.framework.common.exception; 223 224 /** 225 * 226 * 异常处理类 227 * 228 * @author :txh 229 * @version :{版本} 230 * @date: 231 */ 232 public class AppException extends RuntimeException { 233 234 private static final long serialVersionUID = 1L; 235 236 private static final String CAUSED_BY = "aCaused by: "; 237 238 private Throwable cause = null; 239 240 public AppException(){}; 241 242 public AppException(String msg){ 243 super(msg); 244 } 245 246 public AppException(String msg,Throwable cause){ 247 super(msg); 248 this.cause = cause; 249 } 250 251 public AppException(Throwable cause){ 252 this.cause = cause; 253 } 254 255 public Throwable getCause() { 256 return cause; 257 } 258 259 public String toString() { 260 if (cause == null) { 261 return super.toString(); 262 } else { 263 return super.toString() + CAUSED_BY + cause.toString(); 264 } 265 } 266 267 public void printStackTrace() { 268 super.printStackTrace(); 269 if (cause != null) { 270 System.err.println(CAUSED_BY); 271 cause.printStackTrace(); 272 } 273 } 274 275 public void printStackTrace(java.io.PrintStream ps) { 276 super.printStackTrace(ps); 277 if (cause != null) { 278 ps.println(CAUSED_BY); 279 cause.printStackTrace(ps); 280 } 281 } 282 public void printStackTrace(java.io.PrintWriter pw) { 283 super.printStackTrace(pw); 284 if (cause != null) { 285 pw.println(CAUSED_BY); 286 cause.printStackTrace(pw); 287 } 288 } 289 } 290 291 package com.eqcp.framework.common.util; 292 293 import java.text.SimpleDateFormat; 294 import java.util.Calendar; 295 296 import org.slf4j.Logger; 297 import org.slf4j.LoggerFactory; 298 299 public class CalendarUtil { 300 301 protected static final Logger log = LoggerFactory.getLogger(CalendarUtil.class); 302 /** 303 * * 指定周的日期 304 * @param n为推迟的周数,1本周,-1向前推迟一周,2下周,依次类推 305 * @param dayOfWeek 想周几,这里就传几Calendar.MONDAY(TUESDAY...) 306 * @param f 日期格式 307 * @return 308 */ 309 public static String getDateByWeek(int n,int day,String f){ 310 Calendar cal = Calendar.getInstance(); 311 312 String monday; 313 cal.add(Calendar.DATE, n*7); 314 315 //cal.set(Calendar.DAY_OF_WEEK,Calendar.THURSDAY); 316 cal.set(Calendar.DAY_OF_WEEK,day); 317 monday = new SimpleDateFormat(f).format(cal.getTime()); 318 //System.out.println(monday); 319 log.debug(monday); 320 321 return monday; 322 } 323 /** 324 * 上一周星期N的日期 325 * @return 326 */ 327 public static String getDateByLastWeek(int day){ 328 return getDateByWeek(-1,day,"yyyy-MM-dd"); 329 } 330 331 /** 332 * 本周某星期的日期 333 * @param day 334 * @return 335 */ 336 public static String getDateThisWeek(int day){ 337 //return getDateByWeek(0,day,"yyyy-MM-dd HH:mm:ss"); 338 return getDateByWeek(0,day,"yyyy-MM-dd"); 339 } 340 } 341 342 package com.eqcp.framework.common.util; 343 344 import java.util.ArrayList; 345 import java.util.Collection; 346 import java.util.HashMap; 347 import java.util.LinkedHashSet; 348 import java.util.List; 349 import java.util.Map; 350 351 /** 352 * 集合帮助类 353 * @author kun.yang 354 * 355 */ 356 public class CollectionUtil { 357 358 /** 359 * 数组转集合List 360 * @Title: toArrayList 361 * @Description: 描述 362 * @author kun.yang 363 * @param @param objs 364 * @param @return 设定文件 365 * @return List 返回类型 366 * @throws 367 */ 368 public static List toArrayList(Object...objs){ 369 List result = new ArrayList(); 370 if(objs!=null && objs.length>0){ 371 for(Object o:objs){ 372 result.add(o); 373 } 374 } 375 return result; 376 } 377 378 public static Map<String,Object> toHashMap(String[]keys,Object[]values ){ 379 Map<String,Object> map = new HashMap<String,Object>(keys.length); 380 if(keys!=null && values!=null){ 381 if(keys.length!=values.length){ 382 throw new RuntimeException("参数个数不匹配,请检查!"); 383 } 384 for(int i=0;i<keys.length;i++){ 385 map.put(keys[i], values[i]); 386 } 387 } 388 return map; 389 } 390 391 public static Map<String,Object> toHashMap(String key,Object value){ 392 Map<String,Object> map = new HashMap<String,Object>(1); 393 map.put(key, value); 394 return map; 395 } 396 397 /** 398 * 集合是否为空 399 * @param cols 400 * @return 401 */ 402 public static boolean isNotEmpty(Collection cols){ 403 if(cols != null && cols.size() > 0){ 404 return true; 405 }else{ 406 return false; 407 } 408 } 409 410 /** 411 * 从集合中去掉重复,并保持原有的顺序 412 * @param list 413 * @return 414 */ 415 public static <E> List<E> withoutDuplicates(List<E> original){ 416 if(original == null || original.size()==0){ 417 return original; 418 } 419 return new ArrayList<E>(new LinkedHashSet<E>(original)); 420 } 421 422 } 423 424 package com.eqcp.framework.common.util; 425 426 import java.io.UnsupportedEncodingException; 427 import java.lang.reflect.Array; 428 import java.text.ParseException; 429 import java.text.SimpleDateFormat; 430 import java.util.Collection; 431 import java.util.Enumeration; 432 import java.util.HashMap; 433 import java.util.Map; 434 435 import javax.servlet.http.HttpServletRequest; 436 437 public class CommonUtil { 438 439 public static final String DB_DIALECT = "ORACLE"; 440 441 /** 442 * 判断某个对象是否为空 集合类、数组做特殊处理 443 * 444 * @param obj 445 * @return 如为空,返回true,否则false 446 */ 447 public static boolean isEmpty(Object obj) { 448 if (obj == null) 449 return true; 450 // 如果不为null,需要处理几种特殊对象类型 451 if (obj instanceof String) { 452 return obj.equals(""); 453 } else if (obj instanceof Collection) { 454 // 对象为集合 455 Collection coll = (Collection) obj; 456 return coll.size() == 0; 457 } else if (obj instanceof Map) { 458 // 对象为Map 459 Map map = (Map) obj; 460 return map.size() == 0; 461 } else if (obj.getClass().isArray()) { 462 // 对象为数组 463 return Array.getLength(obj) == 0; 464 } else { 465 // 其他类型,只要不为null,即不为empty 466 return false; 467 } 468 } 469 470 /** 471 * <p> 472 * (不建议使用这种方式查询,会造成url太长) 473 * 根据request传入的参数构造查询条件语句 474 * 475 * <li>查询参数名必须包含$Q_的特殊标志 476 * <li>$Q_后面的字符串与数据库字段对应 477 * <li>$Q_前面的字符串位查询匹配方式(如=,like,>=) 478 * <li>如不指定,时间默认匹配为=,其他默认为like 479 * <li>当传入的参数值匹配DATA_FORMAT/TIME_FORMAT,则当时间处理 480 * <li>eq$Q_xxx 在url中严格字符串匹配 481 * @param request HttpServletRequest 482 * @return 查询条件hql语句 483 * 484 */ 485 @Deprecated 486 public static String getQueryHql(HttpServletRequest request) { 487 488 StringBuffer buf = new StringBuffer(); 489 Enumeration params = request.getParameterNames(); 490 String param = null; 491 String value = null; 492 int i = 0; 493 HashMap qMap = new HashMap(); 494 while (params.hasMoreElements()) { 495 param = (String) params.nextElement(); 496 value = request.getParameter(param); 497 String mode = "";// 查询模式 498 if (param.startsWith("_") || param.startsWith("$CODEVALUE_")) { 499 continue; 500 } 501 if (value == null || value.equalsIgnoreCase("null")) { 502 continue; 503 } 504 if (value.trim().length() == 0) { 505 continue; 506 } 507 value = value.trim(); 508 if (param.indexOf("$Q_") != -1) { 509 i++; 510 if (i != 1) { 511 buf.append(" and "); 512 } 513 // 字段名 514 buf.append(param.substring(param.indexOf("$Q_") + 3)); 515 // 保存查询条件 516 qMap.put(param, value); 517 // 防止'注入 518 if (value.indexOf("'") != -1) { 519 value = value.replaceAll("'", "''"); 520 } 521 String temp = param.substring(0, param.indexOf("$Q_")); 522 if (!isEmpty(temp)) { 523 mode = temp; 524 } 525 // 查询值 526 // 是否是时间 527 boolean timeFlag = false; 528 if (value.indexOf("-") != -1) { 529 String[] valueDatas = value.split("-"); 530 if (valueDatas != null && valueDatas.length == 2) { 531 if (StringUtil.isDigitalString(valueDatas[0]) && StringUtil.isDigitalString(valueDatas[1])) { 532 int yearTag = Integer.parseInt(valueDatas[0]); 533 int monthTag = Integer.parseInt(valueDatas[1]); 534 if (yearTag < 2100 && yearTag > 1900 && monthTag >= 1 && monthTag < 13) { 535 value = value + "-01"; 536 } 537 } 538 539 } 540 SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATA_FORMAT); 541 SimpleDateFormat timeFormat = new SimpleDateFormat(Constants.TIME_FORMAT); 542 try { 543 dateFormat.parse(value); 544 timeFlag = true; 545 } catch (ParseException e) { 546 try { 547 timeFormat.parse(value); 548 timeFlag = true; 549 } catch (ParseException e1) { 550 timeFlag = false; 551 } 552 } 553 } 554 555 // 查询方式 556 if (isEmpty(mode)) { 557 // 默认查询模式 558 if (timeFlag) { 559 mode = "="; 560 } else { 561 mode = "like"; 562 } 563 } 564 565 if(mode.length()!=0 && (mode.equals("#=") || mode.equals("eq"))){ 566 buf.append(" = "); 567 }else{ 568 buf.append(" " + mode + " "); 569 } 570 571 if (!timeFlag && mode.length()!=0 && !mode.equals("#=")) { 572 buf.append(" '"); 573 }else{ 574 buf.append(" "); 575 } 576 if (mode.equals("like")) { 577 buf.append("%"); 578 } 579 580 if (timeFlag) { 581 if (value.indexOf(":") == -1 && mode.indexOf("<") != -1 ) { 582 value += " 23:59:59"; 583 } 584 if(value.indexOf(":") == -1 && mode.indexOf(">") != -1){ 585 value += " 00:00:00"; 586 } 587 if (DB_DIALECT.equals("ORACLE") || DB_DIALECT.equals("oracle")) { 588 buf.append("To_date('" + value + "','yyyy-mm-dd hh24:mi:ss')"); 589 } else { 590 buf.append("'" + value + "'"); 591 } 592 } else { 593 buf.append(value); 594 } 595 if (mode.equals("like")) { 596 buf.append("%"); 597 } 598 if (!timeFlag && mode.length()!=0 && !mode.equals("#=")) { 599 buf.append("'"); 600 }else{ 601 buf.append(" "); 602 } 603 } 604 } 605 606 request.setAttribute("qMap", qMap); 607 return buf.toString(); 608 } 609 610 public static String encodeURI(String str){ 611 try { 612 return java.net.URLEncoder.encode(str, "utf-8"); 613 } catch (UnsupportedEncodingException e) { 614 e.printStackTrace(); 615 } 616 return ""; 617 } 618 619 public static String encodeURI(String str,String enc){ 620 try { 621 return java.net.URLEncoder.encode(str,enc); 622 } catch (UnsupportedEncodingException e) { 623 e.printStackTrace(); 624 } 625 return ""; 626 } 627 628 public static String decodeURI(String str){ 629 try { 630 return java.net.URLDecoder.decode(str,"utf-8"); 631 } catch (UnsupportedEncodingException e) { 632 e.printStackTrace(); 633 } 634 return ""; 635 } 636 637 public static String decodeURI(String str,String enc){ 638 try { 639 return java.net.URLDecoder.decode(str,enc); 640 } catch (UnsupportedEncodingException e) { 641 e.printStackTrace(); 642 } 643 return ""; 644 } 645 } 646 647 package com.eqcp.framework.common.util; 648 649 /** 650 * 静态常量 651 * @author Administrator 652 * 653 */ 654 public class Constants { 655 656 public static final String DATA_FORMAT = "yyyy-MM-dd"; 657 658 public static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; 659 660 public static final long STATUS_DRAFT = 0;//拟稿 661 public static final long STATUS_UP = 1;//启用 662 public static final long STATUS_DOWN = -1;//禁用 663 664 public static final String PAGE_BTN_LIST = "page_btn_list"; //页面的button列表 665 666 public static final Long APPLY_QUANLITY_DEFAULT = 10000L; 667 668 public static final String APP_HOME = "appHome";//项目绝对路径 如: /usr/eqcp/clc/ 669 //getContextPath 670 public static final String APP_CONTEXT_PATH = "appContextPath";//项目路径 如:/clcpm 671 672 public static final Integer PAGE_INDEX_DEFAULT = 1;//默认当前页 673 674 public static final Integer PAGE_SIZE_DEFAULT = 20;//默认页面记录数 675 676 /** 677 * 市公司标识 678 */ 679 public static final String USER_TYPE_CITY = "D"; 680 681 /** 682 * 厂家标识 683 */ 684 public static final String USER_TYPE_SUPPLY = "C"; 685 686 } 687 688 package com.eqcp.framework.common.util; 689 690 import java.text.ParseException; 691 import java.text.SimpleDateFormat; 692 import java.util.Calendar; 693 import java.util.Date; 694 695 import org.apache.commons.lang3.RandomStringUtils; 696 697 public class DateTimeUtil { 698 699 public static final String DATE_FORMAT = "yyyyMMdd"; 700 public static final String DATE_TIME_FORMAT = "yyyyMMddHHmmss"; 701 702 /** 703 * 获取当前时间指定格式的时间字符串 704 * @return 705 */ 706 public static String toNowDateTimeStr(String pattern){ 707 SimpleDateFormat sdf = new SimpleDateFormat(pattern); 708 return sdf.format(new Date()); 709 } 710 711 /** 712 * 获取当前时间指定格式的时间字符串 713 * @return 714 */ 715 public static String formatDateTime(Date date,String pattern){ 716 SimpleDateFormat sdf = new SimpleDateFormat(pattern); 717 return sdf.format(date); 718 } 719 720 /** 721 * 随机事件 722 * @return 723 */ 724 public static String randomTime(int count){ 725 SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT); 726 String time = sdf.format(new Date()); 727 String str = "0123456789"; 728 return time+RandomStringUtils.random(count,str); 729 730 } 731 732 /** 733 * 返回两个时间的差值 734 * @author yun.li 735 * @param d1 时间1 736 * @param d2 时间2 737 * @return String 返回String的差值描述(如:xx天xx小时xx分钟xx秒) 738 * @throws 739 */ 740 public static String getWithTiem(Date d1,Date d2){ 741 if(d1==null||d2==null){ 742 return ""; 743 } 744 long daterange = d2.getTime() - d1.getTime(); 745 746 long t1 = 1000*60*60*24; 747 long t2 = 1000*60*60; 748 long t3 = 1000*60; 749 int dd = (int)Math.round(daterange/t1); 750 int hh = 0; 751 if(daterange-dd*t1>0) 752 hh = (int)Math.round((daterange-dd*t1)/t2); 753 754 int mm = 0; 755 if(daterange-dd*t1-hh*t2>0) 756 mm = (int)Math.round((daterange-dd*t1-hh*t2)/t3); 757 758 int ss = 0; 759 if(daterange-dd*t1-hh*t2-mm*t3>0) 760 ss = (int)Math.round((daterange-dd*t1-hh*t2-mm*t3)/1000); 761 762 String time = ""; 763 if(dd>0) 764 time += String.valueOf(dd)+"天"; 765 if(hh>0) 766 time += String.valueOf(hh)+"小时"; 767 if(mm>0) 768 time += String.valueOf(mm)+"分钟"; 769 if(ss>0) 770 time += String.valueOf(ss)+"秒"; 771 772 // System.out.println(time); 773 774 return time; 775 } 776 777 public static java.sql.Timestamp getWeekDay(java.sql.Timestamp stamp, 778 int days, int week) { 779 Calendar tempCal = Calendar.getInstance(); 780 tempCal.setTime(new java.util.Date(stamp.getTime())); 781 tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), 782 tempCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0); 783 tempCal.set(Calendar.DAY_OF_WEEK, tempCal.getFirstDayOfWeek()); 784 tempCal.add(Calendar.DAY_OF_WEEK, days); 785 if (week != 0) { 786 tempCal.add(Calendar.WEEK_OF_MONTH, week); 787 } 788 java.sql.Timestamp retStamp = new java.sql.Timestamp(tempCal.getTime() 789 .getTime()); 790 retStamp.setNanos(0); 791 return retStamp; 792 } 793 794 /** 795 * Return a Timestamp for right now 796 * 797 * @return Timestamp for right now 798 */ 799 public static java.sql.Timestamp nowTimestamp() { 800 return new java.sql.Timestamp(System.currentTimeMillis()); 801 } 802 803 public static java.sql.Timestamp StrToTimestamp(String timestampStr, String pattern) 804 throws Exception { 805 java.util.Date date = null; 806 SimpleDateFormat format = new SimpleDateFormat(pattern); 807 try { 808 date = format.parse(timestampStr); 809 } catch (Exception e) { 810 throw e; 811 } 812 return date == null ? null : new java.sql.Timestamp(date.getTime()); 813 } 814 815 public static Date parseDateTime(String datetime,String pattern){ 816 SimpleDateFormat format = new SimpleDateFormat(pattern); 817 try { 818 return format.parse(datetime); 819 } catch (ParseException e) { 820 e.printStackTrace(); 821 } 822 return null; 823 } 824 825 /** 826 * 计算2个日期的间隔天数(去掉时分秒比较) 827 * @param d1 828 * @param d2 829 * @return 830 */ 831 public static long calDaySpan(Date d1,Date d2){ 832 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 833 String str1 = format.format(d1); 834 String str2 = format.format(d2); 835 long quot = 0; 836 try{ 837 Date t1 = format.parse(str1); 838 Date t2 = format.parse(str2); 839 quot = t1.getTime() - t2.getTime(); 840 quot = quot / 1000 / 60 / 60 / 24; 841 }catch(Exception e){ 842 e.printStackTrace(); 843 } 844 return quot; 845 } 846 /* 847 public static void main(String[] args) { 848 Date d1 = parseDateTime("2009-06-22 10:00","yyyy-MM-dd"); 849 Date d2 = parseDateTime("2009-06-20 12:00","yyyy-MM-dd"); 850 long t = calDaySpan(d1,d2); 851 System.out.println(t); 852 } 853 */ 854 } 855 856 package com.eqcp.framework.common.util; 857 858 import java.io.File; 859 import java.io.FileOutputStream; 860 import java.io.IOException; 861 import java.io.InputStream; 862 863 import org.slf4j.Logger; 864 import org.slf4j.LoggerFactory; 865 866 import com.eqcp.framework.common.cache.ConfigCache; 867 import com.eqcp.framework.common.exception.AppException; 868 869 public class FileUtil { 870 871 protected static final Logger log = LoggerFactory.getLogger(FileUtil.class); 872 /** 873 * 写文件到本地 874 * 875 * @param in 876 * @param fileName 877 * @throws AppException 878 * @throws IOException 879 */ 880 public static File writeFile(InputStream in, String fileName){ 881 String uploadDir = ConfigCache.getProperty("jeyo.attachment.dir"); 882 File dir = new File(uploadDir); 883 if (!dir.exists()) { 884 dir.mkdirs(); 885 } 886 String prefix = DateTimeUtil.toNowDateTimeStr("yyyyMMddHHmmss")+"_"+StringUtil.getRandomNum(3)+"_"; 887 String filePath = uploadDir+File.separator+prefix+fileName; 888 File saveFile = new File(filePath); 889 FileOutputStream fs = null; 890 try{ 891 fs = new FileOutputStream(saveFile); 892 byte[] buffer = new byte[1024 * 1024]; 893 int byteread = 0; 894 while ((byteread = in.read(buffer)) != -1) { 895 fs.write(buffer, 0, byteread); 896 fs.flush(); 897 } 898 }catch(IOException e){ 899 String msg = "写文件时异常!file:"+filePath; 900 e.printStackTrace(); 901 //System.out.println(msg); 902 log.error(msg); 903 }finally{ 904 try { 905 if(fs!=null) 906 fs.close(); 907 if(in!=null) 908 in.close(); 909 } catch (IOException e) { 910 // TODO Auto-generated catch block 911 e.printStackTrace(); 912 } 913 } 914 return saveFile; 915 } 916 917 public static String convertFileSize(long filesize) { 918 String strunit = "B"; 919 String straftercomma = ""; 920 int intdivisor = 1; 921 if (filesize >= 1024 * 1024){ 922 strunit = "MB"; 923 intdivisor = 1024 * 1024; 924 }else if (filesize >= 1024){ 925 strunit = "KB"; 926 intdivisor = 1024; 927 } 928 if (intdivisor == 1) 929 return filesize + " " + strunit; 930 straftercomma = "" + 100 * (filesize % intdivisor) / intdivisor; 931 if (straftercomma == "") 932 straftercomma = ".0"; 933 return filesize / intdivisor + "." + straftercomma + " " + strunit; 934 } 935 936 public static String changeUploadFileName(String originalFilename,String newFileName){ 937 int index = originalFilename.lastIndexOf("."); 938 if(index!=-1){ 939 String suffix = originalFilename.substring(index, originalFilename.length()); 940 if(newFileName!=null && !"".equals(newFileName.trim())&& !newFileName.endsWith(suffix)){ 941 newFileName = newFileName + suffix; 942 }else{ 943 newFileName = originalFilename; 944 } 945 } 946 return newFileName; 947 } 948 } 949 950 package com.eqcp.framework.common.util; 951 952 import java.beans.IntrospectionException; 953 import java.beans.Introspector; 954 import java.beans.PropertyDescriptor; 955 import java.math.BigDecimal; 956 import java.math.BigInteger; 957 import java.util.List; 958 import java.util.Map; 959 import java.util.Set; 960 961 public class JsonUtil { 962 public static String object2json(Object obj) { 963 StringBuilder json = new StringBuilder(); 964 if (obj == null) { 965 json.append("\"\""); 966 } else if (obj instanceof String || obj instanceof Integer || obj instanceof Float 967 || obj instanceof Boolean || obj instanceof Short || obj instanceof Double 968 || obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger 969 || obj instanceof Byte) { 970 json.append("\"").append(string2json(obj.toString())).append("\""); 971 } else if (obj instanceof Object[]) { 972 json.append(array2json((Object[]) obj)); 973 } else if (obj instanceof List) { 974 json.append(list2json((List<?>) obj)); 975 } else if (obj instanceof Map) { 976 json.append(map2json((Map<?, ?>) obj)); 977 } else if (obj instanceof Set) { 978 // json.append(set2json((Set<?>) obj)); 979 } else { 980 json.append(bean2json(obj)); 981 } 982 return json.toString(); 983 } 984 public static String bean2json(Object bean) { 985 StringBuilder json = new StringBuilder(); 986 json.append("{"); 987 PropertyDescriptor[] props = null; 988 try { 989 props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors(); 990 } catch (IntrospectionException e) {} 991 if (props != null) { 992 for (int i = 0; i < props.length; i++) { 993 try { 994 String name = object2json(props[i].getName()); 995 String value = object2json(props[i].getReadMethod().invoke(bean)); 996 json.append(name); 997 json.append(":"); 998 json.append(value); 999 json.append(","); 1000 } catch (Exception e) {} 1001 } 1002 json.setCharAt(json.length() - 1, '}'); 1003 } else { 1004 json.append("}"); 1005 } 1006 return json.toString(); 1007 } 1008 public static String list2json(List<?> list) { 1009 StringBuilder json = new StringBuilder(); 1010 json.append("["); 1011 if (list != null && list.size() > 0) { 1012 for (Object obj : list) { 1013 json.append(object2json(obj)); 1014 json.append(","); 1015 } 1016 json.setCharAt(json.length() - 1, ']'); 1017 } else { 1018 json.append("]"); 1019 } 1020 return json.toString(); 1021 } 1022 public static String array2json(Object[] array) { 1023 StringBuilder json = new StringBuilder(); 1024 json.append("["); 1025 if (array != null && array.length > 0) { 1026 for (Object obj : array) { 1027 json.append(object2json(obj)); 1028 json.append(","); 1029 } 1030 json.setCharAt(json.length() - 1, ']'); 1031 } else { 1032 json.append("]"); 1033 } 1034 return json.toString(); 1035 } 1036 public static String map2json(Map<?, ?> map) { 1037 StringBuilder json = new StringBuilder(); 1038 json.append("{"); 1039 if (map != null && map.size() > 0) { 1040 for (Object key : map.keySet()) { 1041 json.append(object2json(key)); 1042 json.append(":"); 1043 json.append(object2json(map.get(key))); 1044 json.append(","); 1045 } 1046 json.setCharAt(json.length() - 1, '}'); 1047 } else { 1048 json.append("}"); 1049 } 1050 return json.toString(); 1051 } 1052 public static String set2json(Set<?> set) { 1053 StringBuilder json = new StringBuilder(); 1054 json.append("["); 1055 if (set != null && set.size() > 0) { 1056 for (Object obj : set) { 1057 json.append(object2json(obj)); 1058 json.append(","); 1059 } 1060 json.setCharAt(json.length() - 1, ']'); 1061 } else { 1062 json.append("]"); 1063 } 1064 return json.toString(); 1065 } 1066 public static String string2json(String s) { 1067 if (s == null) 1068 return ""; 1069 StringBuilder sb = new StringBuilder(); 1070 for (int i = 0; i < s.length(); i++) { 1071 char ch = s.charAt(i); 1072 switch (ch) { 1073 case '"': 1074 sb.append("\\\""); 1075 break; 1076 case '\\': 1077 sb.append("\\\\"); 1078 break; 1079 case '\b': 1080 sb.append("\\b"); 1081 break; 1082 case '\f': 1083 sb.append("\\f"); 1084 break; 1085 case '\n': 1086 sb.append("\\n"); 1087 break; 1088 case '\r': 1089 sb.append("\\r"); 1090 break; 1091 case '\t': 1092 sb.append("\\t"); 1093 break; 1094 case '/': 1095 sb.append("\\/"); 1096 break; 1097 default: 1098 if (ch >= '\u0000' && ch <= '\u001F') { 1099 String ss = Integer.toHexString(ch); 1100 sb.append("\\u"); 1101 for (int k = 0; k < 4 - ss.length(); k++) { 1102 sb.append('0'); 1103 } 1104 sb.append(ss.toUpperCase()); 1105 } else { 1106 sb.append(ch); 1107 } 1108 } 1109 } 1110 return sb.toString(); 1111 } 1112 1113 } 1114 1115 1116 package com.eqcp.framework.common.util; 1117 1118 public class ModelUtil { 1119 1120 private static String[] MODEL_BASE_PACKAGES; 1121 static{ 1122 MODEL_BASE_PACKAGES = new String[]{ 1123 "com.eqcp.framework.model", 1124 "com.eqcp.app.model", 1125 "com.eqcp.app.produceManage.model" 1126 }; 1127 } 1128 1129 /** 1130 * 查询类型 1131 * @param entityName 1132 * @return 1133 */ 1134 public static Class getEntityClass(String entityName){ 1135 Class clazz = null; 1136 for(int i=0;i<MODEL_BASE_PACKAGES.length;i++){ 1137 try { 1138 clazz = Class.forName(MODEL_BASE_PACKAGES[i]+"."+entityName); 1139 break; 1140 } catch (ClassNotFoundException e) { 1141 continue; 1142 } 1143 } 1144 if(clazz == null){ 1145 throw new RuntimeException("未找到实体:"+entityName); 1146 } 1147 return clazz; 1148 } 1149 } 1150 1151 package com.eqcp.framework.dao.hibernate; 1152 1153 import java.io.Serializable; 1154 import java.lang.reflect.ParameterizedType; 1155 import java.math.BigDecimal; 1156 import java.sql.SQLException; 1157 import java.util.ArrayList; 1158 import java.util.Collection; 1159 import java.util.Iterator; 1160 import java.util.List; 1161 import java.util.Map; 1162 1163 import org.apache.commons.lang3.ArrayUtils; 1164 import org.apache.commons.lang3.Validate; 1165 import org.hibernate.EntityMode; 1166 import org.hibernate.HibernateException; 1167 import org.hibernate.Query; 1168 import org.hibernate.Session; 1169 import org.hibernate.SessionFactory; 1170 import org.hibernate.metadata.ClassMetadata; 1171 import org.hibernate.type.Type; 1172 import org.slf4j.Logger; 1173 import org.slf4j.LoggerFactory; 1174 import org.springframework.beans.factory.annotation.Autowired; 1175 import org.springframework.orm.hibernate3.HibernateCallback; 1176 import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 1177 import org.springframework.stereotype.Repository; 1178 import org.springframework.util.Assert; 1179 1180 import com.eqcp.framework.common.util.CommonUtil; 1181 import com.eqcp.framework.model.vo.PaginatedListHelper; 1182 1183 1184 public class HibernateBaseDao<T> extends HibernateDaoSupport implements IHibernateBaseDao<T> { 1185 protected final Logger log = LoggerFactory.getLogger(getClass()); 1186 1187 1188 @Autowired 1189 public void init(SessionFactory sessionFactory) { 1190 super.setSessionFactory(sessionFactory); 1191 } 1192 1193 /** 1194 * 保存实体 1195 */ 1196 public T save(Object entity) { 1197 getHibernateTemplate().save(entity); 1198 return (T)entity; 1199 } 1200 1201 /** 1202 * 1203 */ 1204 public T saveOrUpdate(Object entity) { 1205 try { 1206 getHibernateTemplate().saveOrUpdate(entity); 1207 return (T)entity; 1208 } catch (Exception e) { 1209 logger.error(e); 1210 return null; 1211 } 1212 } 1213 1214 /** 1215 * 保存集合 1216 */ 1217 public void saveCollections(Collection cols) { 1218 if(cols!=null && cols.size()>0){ 1219 Iterator it = cols.iterator(); 1220 while(it.hasNext()){ 1221 save(it.next()); 1222 } 1223 } 1224 } 1225 1226 1227 1228 /** 1229 * 删除实体 1230 */ 1231 public boolean delete(Object entity) { 1232 getHibernateTemplate().delete(entity); 1233 return true; 1234 } 1235 1236 /** 1237 * 删除一批实体 1238 */ 1239 public boolean delete(List entityList) { 1240 getHibernateTemplate().deleteAll(entityList); 1241 return true; 1242 } 1243 1244 /** 1245 * 修改 1246 */ 1247 public T update(Object entity) { 1248 try { 1249 getHibernateTemplate().update(entity); 1250 return (T)entity; 1251 } catch (Exception e) { 1252 logger.error(e); 1253 return null; 1254 } 1255 } 1256 1257 /** 1258 * 根据实体对象查询实体 1259 */ 1260 public List<T>findByExample(Object value){ 1261 return getHibernateTemplate().findByExample(value); 1262 } 1263 1264 /** 1265 * 查询所有数据 1266 * <T>被实例化后可用 1267 */ 1268 public List<T> findAll() { 1269 String queryString = "from "+getTableName(); 1270 return getHibernateTemplate().find(queryString); 1271 } 1272 1273 1274 /** 1275 * 根据HQL查询 1276 */ 1277 public List<T> findAllByHql(String hql){ 1278 return getHibernateTemplate().find(hql); 1279 } 1280 1281 1282 /** 1283 * 根据ID获取实体 1284 */ 1285 public T findById(Class clazz,Integer id) { 1286 return (T) getHibernateTemplate().get(clazz, id); 1287 } 1288 /** 1289 * 1290 */ 1291 public T findById(Class clazz,Long id) { 1292 return (T) getHibernateTemplate().get(clazz, id); 1293 } 1294 /** 1295 * 1296 */ 1297 public T findById(Class clazz,String id) { 1298 return (T) getHibernateTemplate().get(clazz, id); 1299 } 1300 /** 1301 * 1302 */ 1303 public T findById(Class clazz,BigDecimal id){ 1304 return (T) getHibernateTemplate().get(clazz, id); 1305 } 1306 1307 /** 1308 * 1309 */ 1310 public T findById(Integer id) { 1311 return (T) getHibernateTemplate().get(getEntityClass(), id); 1312 } 1313 1314 /** 1315 * 1316 */ 1317 public T findById(Long id) { 1318 return (T) getHibernateTemplate().get(getEntityClass(), id); 1319 } 1320 1321 /** 1322 * 1323 */ 1324 public T findById(String id) { 1325 return (T) getHibernateTemplate().get(getEntityClass(), id); 1326 } 1327 /** 1328 * 1329 */ 1330 public T findById(BigDecimal id){ 1331 return (T) getHibernateTemplate().get(getEntityClass(), id); 1332 } 1333 1334 1335 1336 /** 1337 * 根据HQL查询唯一实体 1338 * 1339 */ 1340 @SuppressWarnings({ "unchecked", "hiding" }) 1341 public <T> T selectOnlyQuery(final String hql) { 1342 T only = (T)this.getHibernateTemplate().execute( 1343 new HibernateCallback() { 1344 public Object doInHibernate(Session session) 1345 throws HibernateException, SQLException { 1346 Query query = session.createQuery(hql); 1347 return (T)query.uniqueResult(); 1348 } 1349 }); 1350 return (T)only; 1351 } 1352 1353 1354 /** 1355 * 翻页查询 1356 * @param hql 1357 * @param page 1358 * @param pageSize 1359 * @return 1360 */ 1361 protected <T> PaginatedListHelper<T> queryPagedList(Hql hql,Integer page,Integer pageSize){ 1362 int totalItems = getTotalItems(hql); 1363 1364 int p = page!=null?page:1; 1365 int ps = pageSize!=null?pageSize:20; 1366 1367 PaginatedListHelper<T> pagedList = new PaginatedListHelper<T>(totalItems, ps, p); 1368 if (totalItems > 0) { 1369 Query query = hql.createQuery(getSession()); 1370 query.setFirstResult((pagedList.getPageNumber() - 1)* pagedList.getPageSize()); 1371 query.setMaxResults(pagedList.getPageSize()); 1372 @SuppressWarnings("unchecked") 1373 List<T> items = query.list(); 1374 pagedList.setList(items); 1375 } else { 1376 pagedList.setList(new ArrayList<T>(0)); 1377 } 1378 return pagedList; 1379 } 1380 1381 1382 1383 1384 /** 1385 * 1386 */ 1387 @SuppressWarnings({ "hiding", "unchecked" }) 1388 public <T> List<T> selectQueryInPage(final String hql,final int start,final int limit) { 1389 List<T> list = this.getHibernateTemplate().executeFind( 1390 new HibernateCallback() { 1391 public Object doInHibernate(Session session) 1392 throws HibernateException, SQLException { 1393 Query query = session.createQuery(hql); 1394 query.setFirstResult(start); 1395 query.setMaxResults(limit); 1396 List<T> list = query.list(); 1397 return list; 1398 } 1399 }); 1400 return list; 1401 } 1402 1403 1404 /** 1405 * 1406 */ 1407 @SuppressWarnings({ "hiding", "unchecked" }) 1408 public <T> List<T> selectQueryInPage(final String hql,final List parameter,final int start,final int limit) { 1409 List<T> list = this.getHibernateTemplate().executeFind( 1410 new HibernateCallback() { 1411 public Object doInHibernate(Session session) 1412 throws HibernateException, SQLException { 1413 Query query = session.createQuery(hql); 1414 if(parameter!=null&¶meter.size()>0){ 1415 for(int i=0;i<parameter.size();i++){ 1416 query.setParameter(i, parameter.get(i)); 1417 } 1418 } 1419 query.setFirstResult(start); 1420 query.setMaxResults(limit); 1421 List<T> list = query.list(); 1422 return list; 1423 } 1424 }); 1425 return list; 1426 } 1427 1428 1429 /** 1430 * 1431 */ 1432 @SuppressWarnings({ "hiding", "unchecked" }) 1433 public <T> List<T> selectSQLQueryInPage(final String sql,final int start,final int limit) { 1434 List<T> list = this.getHibernateTemplate().executeFind( 1435 new HibernateCallback() { 1436 public Object doInHibernate(Session session) 1437 throws HibernateException, SQLException { 1438 Query query = session.createSQLQuery(sql); 1439 query.setFirstResult(start); 1440 query.setMaxResults(limit); 1441 List<T> list = query.list(); 1442 return list; 1443 } 1444 }); 1445 return list; 1446 } 1447 1448 1449 /** 1450 * 1451 */ 1452 public int getRowCount(String fromAndWhere, List paramValues) { 1453 Object countObj = null; 1454 if(!CommonUtil.isEmpty(paramValues)){ 1455 countObj = this.getHibernateTemplate().find("select count(*) " + fromAndWhere, paramValues.toArray()).get(0); 1456 }else{ 1457 countObj = this.getHibernateTemplate().find("select count(*) " + fromAndWhere).get(0); 1458 } 1459 return ((Long) countObj).intValue(); 1460 } 1461 1462 /** 1463 * 查询所有记录 1464 * @param hql 1465 * @return 1466 */ 1467 protected <T> List<T> queryList(Hql hql){ 1468 Query query = hql.createQuery(getSession()); 1469 @SuppressWarnings("unchecked") 1470 List<T> items = query.list(); 1471 if(items == null){ 1472 items = new ArrayList<T>(0); 1473 } 1474 return items; 1475 } 1476 1477 /** 1478 * 查询所有记录 1479 * @param hql 1480 * @return 1481 */ 1482 protected <T> List<T> queryList(Hql hql,Map<String,Object> paramMap){ 1483 if(paramMap != null && paramMap.size()>0){ 1484 for(Map.Entry<String, Object> e:paramMap.entrySet()){ 1485 hql.setParameter(e.getKey(), e.getValue()); 1486 } 1487 } 1488 Query query = hql.createQuery(getSession()); 1489 @SuppressWarnings("unchecked") 1490 List<T> items = query.list(); 1491 if(items == null){ 1492 items = new ArrayList<T>(0); 1493 } 1494 return items; 1495 } 1496 1497 /** 1498 * 查询所有记录 1499 * @param hql 1500 * @return 1501 */ 1502 protected <T> List<T> queryList(Hql hql,String fieldName,Object fieldValue){ 1503 hql.setParameter(fieldName, fieldValue); 1504 Query query = hql.createQuery(getSession()); 1505 @SuppressWarnings("unchecked") 1506 List<T> items = query.list(); 1507 if(items == null){ 1508 items = new ArrayList<T>(0); 1509 } 1510 return items; 1511 } 1512 1513 /** 1514 * 查询hql的总条数 1515 * @param hql 1516 * @return 1517 */ 1518 protected int getTotalItems(Hql hql){ 1519 Validate.notNull(hql); 1520 1521 Query countQuery = hql.createCountQuery(getSession()); 1522 int totalItems = ((Number) countQuery.iterate().next()).intValue(); 1523 return totalItems; 1524 } 1525 1526 /** 1527 * 1528 * @param bean 1529 * @param entity 1530 * @param excluded 1531 */ 1532 protected void copy(T bean, T entity, String... excluded) { 1533 copy(bean, entity, null, excluded); 1534 } 1535 1536 /** 1537 * 1538 * @param bean 1539 * @param entity 1540 * @param included 1541 */ 1542 protected void copyOnly(T bean, T entity, String... included) { 1543 copy(bean, entity, included, null); 1544 } 1545 1546 /** 1547 * 1548 * @param bean 1549 * @param entity 1550 * @param included 1551 * @param excluded 1552 */ 1553 protected void copy(T bean, T entity, String[] included, String[] excluded) { 1554 Validate.notNull(bean); 1555 Validate.notNull(entity); 1556 Class<? extends Object> clazz = bean.getClass(); 1557 ClassMetadata metadata = getSessionFactory().getClassMetadata(clazz); 1558 Validate.notNull(metadata, 1559 "no such entity was mapped: " + clazz.getName()); 1560 Object value; 1561 Type type; 1562 for (String name : metadata.getPropertyNames()) { 1563 value = metadata.getPropertyValue(bean, name, EntityMode.POJO); 1564 type = metadata.getPropertyType(name); 1565 if (!(type.isAnyType() || type.isAssociationType() || type 1566 .isCollectionType())) { 1567 if (ArrayUtils.isNotEmpty(included)) { 1568 if (ArrayUtils.contains(included, name) 1569 && !ArrayUtils.contains(excluded, name)) { 1570 metadata.setPropertyValue(entity, name, value, 1571 EntityMode.POJO); 1572 } 1573 } else { 1574 if (!ArrayUtils.contains(excluded, name)) { 1575 metadata.setPropertyValue(entity, name, value, 1576 EntityMode.POJO); 1577 } 1578 } 1579 } 1580 } 1581 } 1582 1583 1584 /** 1585 * 1586 */ 1587 public List queryListBySql(String sql){ 1588 Query query = getSession().createSQLQuery(sql); 1589 @SuppressWarnings("unchecked") 1590 List<Object[]> items = query.list(); 1591 if(items == null){ 1592 items = new ArrayList<Object[]>(0); 1593 } 1594 return items; 1595 } 1596 1597 1598 /** 1599 * 1600 */ 1601 public List<T> queryList(Map<String,Object> paramMap){ 1602 Class<T> clazz = getEntityClass(); 1603 Hql hql = new Hql(" from " + clazz.getSimpleName()); 1604 if(paramMap!=null && paramMap.size()>0){ 1605 hql.append(" where 1=1 "); 1606 for(Map.Entry<String, Object> e:paramMap.entrySet()){ 1607 hql.append(" and " + e.getKey() + "=:" + e.getKey()); 1608 hql.setParameter(e.getKey(), e.getValue()); 1609 } 1610 } 1611 return queryList(hql); 1612 } 1613 1614 1615 /** 1616 * 取得泛型类型 1617 * @return 1618 */ 1619 @SuppressWarnings("unchecked") 1620 protected Class<T> getEntityClass() { 1621 return (Class<T>) ((ParameterizedType) getClass() 1622 .getGenericSuperclass()).getActualTypeArguments()[0]; 1623 } 1624 /** 1625 * 取得泛型tableName 1626 * @return 1627 */ 1628 private String getTableName() { 1629 return getEntityClass().getSimpleName(); 1630 } 1631 1632 } 1633 1634 package com.eqcp.framework.controller; 1635 1636 import java.io.IOException; 1637 import java.io.Writer; 1638 import java.text.SimpleDateFormat; 1639 import java.util.ArrayList; 1640 import java.util.Date; 1641 import java.util.Enumeration; 1642 import java.util.HashMap; 1643 import java.util.List; 1644 import java.util.Map; 1645 1646 import javax.servlet.http.HttpServletRequest; 1647 import javax.servlet.http.HttpServletResponse; 1648 1649 import net.sf.json.JSONObject; 1650 1651 import org.apache.log4j.Logger; 1652 import org.springframework.beans.factory.annotation.Autowired; 1653 import org.springframework.security.core.Authentication; 1654 import org.springframework.security.core.context.SecurityContext; 1655 import org.springframework.security.core.context.SecurityContextHolder; 1656 import org.springframework.security.core.userdetails.UserDetails; 1657 import org.springframework.ui.Model; 1658 import org.springframework.web.bind.annotation.ModelAttribute; 1659 1660 import com.eqcp.framework.common.util.JsonUtil; 1661 import com.eqcp.framework.common.util.StringUtil; 1662 import com.eqcp.framework.dao.UserDao; 1663 import com.eqcp.framework.model.DefColumnField; 1664 import com.eqcp.framework.model.SysUser; 1665 import com.eqcp.framework.model.SysUserRole; 1666 import com.eqcp.framework.service.DefColumnFieldService; 1667 import com.eqcp.framework.service.GenericService; 1668 1669 public class BaseController{ 1670 1671 protected Logger log = Logger.getLogger(this.getClass()); 1672 1673 protected final static String VIEW_PREFIX = "clc"; 1674 protected final static String VIEW = "view"; 1675 protected final static String EDIT = "edit"; 1676 protected final static String ADD = "add"; 1677 protected final static String LIST = "list"; 1678 1679 protected final static String ENTITY = "_ENTITY";//实体 1680 protected final static String ID = "_ID";//主键 1681 protected final static String IDS = "_Ids";//主键 逗号分隔 1682 1683 protected final static String PAGE = "page";//页号 1684 protected final static String PAGE_SIZE = "pageSize";//页数 1685 protected final static String RETURN_PAGE = "returnPage";//返回页面 1686 protected final static String ORDER_BY = "orderby";//排序 *_desc *_asc 1687 public static final String JSON = "application/json";//json 1688 1689 1690 @Autowired 1691 UserDao userDao; 1692 1693 1694 @Autowired 1695 GenericService genericService; 1696 @Autowired 1697 DefColumnFieldService defColumnFieldService; 1698 1699 /** 1700 * 输出一段字符串格式数据给JSP 1701 * @author yun.li 1702 * @param str 要输出的内容 1703 */ 1704 protected void writeStringToResponse(HttpServletResponse response, String str) { 1705 Writer out = null; 1706 try { 1707 response.setContentType("text/html;charaset=utf-8"); 1708 out = response.getWriter(); 1709 if(str!=null){ 1710 out.write(str); 1711 out.flush(); 1712 } 1713 } catch (IOException e) { 1714 e.printStackTrace(); 1715 }finally{ 1716 if(out!=null){ 1717 try { 1718 out.close(); 1719 } catch (IOException e) { 1720 e.printStackTrace(); 1721 } 1722 } 1723 } 1724 } 1725 1726 /** 1727 * 输出一段xml格式数据给JSP 1728 * @author yun.li 1729 * @param str 要输出的内容 1730 */ 1731 protected void writeXMLToResponse(HttpServletResponse response, String str) { 1732 Writer out = null; 1733 try { 1734 response.setContentType("text/xml; charset=UTF-8"); 1735 response.setHeader("Cache-Control", "no-cache"); 1736 out = response.getWriter(); 1737 if(str!=null){ 1738 out.write(str); 1739 out.flush(); 1740 } 1741 } catch (IOException e) { 1742 e.printStackTrace(); 1743 }finally{ 1744 if(out!=null){ 1745 try { 1746 out.close(); 1747 } catch (IOException e) { 1748 e.printStackTrace(); 1749 } 1750 } 1751 } 1752 } 1753 1754 protected void writeStringToResponse(HttpServletRequest request, 1755 HttpServletResponse response, String str) { 1756 Writer out = null; 1757 try { 1758 out = response.getWriter(); 1759 if(str!=null){ 1760 out.write(str); 1761 out.flush(); 1762 } 1763 } catch (IOException e) { 1764 e.printStackTrace(); 1765 }finally{ 1766 if(out!=null){ 1767 try { 1768 out.close(); 1769 } catch (IOException e) { 1770 e.printStackTrace(); 1771 } 1772 } 1773 } 1774 } 1775 1776 protected String getParameter(HttpServletRequest request,String key,boolean isRequired){ 1777 String param = request.getParameter(key); 1778 if(isRequired && (param == null || "".equals(param.trim()))){ 1779 throw new RuntimeException("[参数丢失:"+ key+"]"); 1780 } 1781 return param; 1782 } 1783 1784 @ModelAttribute("formBean") 1785 public Object createObject(Model model,String _entity){ 1786 if(_entity!=null&& !_entity.equals("")){ 1787 try { 1788 return Class.forName(_entity).newInstance(); 1789 } catch (Exception e) { 1790 e.printStackTrace(); 1791 } 1792 } 1793 return null; 1794 } 1795 1796 protected Map<String,String> getParameterMap(HttpServletRequest request,String prefix, String suffix) { 1797 return getParameterMap(request,prefix,suffix,false); 1798 } 1799 1800 protected Map<String,String> getParameterMap(HttpServletRequest request,String prefix, String suffix, boolean skipEmpty) { 1801 Map<String,String> map = new HashMap<String,String>(); 1802 if(prefix==null)prefix=""; 1803 if(suffix==null)suffix=""; 1804 Enumeration<String> parameterNames = request.getParameterNames(); 1805 while (parameterNames.hasMoreElements()) { 1806 String parameterName = parameterNames.nextElement(); 1807 String value = request.getParameter(parameterName); 1808 if (!StringUtil.isNotEmptyAndBlank(value) && skipEmpty) 1809 continue; 1810 if (parameterName.startsWith(prefix)) { 1811 if (suffix != null && suffix.length() > 0) { 1812 if (parameterName.endsWith(suffix)) { 1813 String key = parameterName.substring(prefix.length(),parameterName.length() - (suffix.length())); 1814 map.put(key, value); 1815 } 1816 } else { 1817 String key = parameterName.substring(prefix.length()); 1818 map.put(key, value); 1819 } 1820 } 1821 } 1822 return map; 1823 } 1824 1825 protected String getContextPath(HttpServletRequest request){ 1826 return request.getContextPath(); 1827 } 1828 /** 1829 * 获取user, 1830 * 获取session中的user,如果session为null,获取security中的, 1831 * 如果session失效,获取cas服务器中的。 1832 * @param request 1833 * @return 1834 */ 1835 public SysUser getSessionUser(HttpServletRequest request) { 1836 SysUser user = (SysUser)request.getSession().getAttribute("user"); 1837 try { 1838 if (user == null) { 1839 SecurityContext ctx = SecurityContextHolder.getContext(); 1840 Authentication auth = ctx.getAuthentication(); 1841 if (auth.getPrincipal() instanceof UserDetails) { 1842 user = (SysUser) auth.getPrincipal(); 1843 1844 }else{ 1845 String userId = request.getRemoteUser()==null?"":request.getRemoteUser(); 1846 if(!userId.equals("")){ 1847 user = (SysUser)userDao.loadUserByUsername(userId); 1848 } 1849 } 1850 request.getSession().setAttribute("user", user); 1851 1852 } else { 1853 user = (SysUser) request.getSession().getAttribute("user"); 1854 } 1855 1856 } catch (Exception e) {e.printStackTrace();} 1857 1858 if(user == null){ 1859 //throw new RuntimeException("当前登录已失效,请重新登录!"); 1860 } 1861 return user; 1862 } 1863 1864 protected String getOrderBy(HttpServletRequest request){ 1865 String orderby = getParameter(request, ORDER_BY, false); 1866 if(orderby!=null && !"".equals(orderby)){ 1867 request.setAttribute(ORDER_BY, orderby); 1868 if(orderby.endsWith("-desc")){ 1869 return orderby.replaceAll("-desc", "")+" desc"; 1870 }else if(orderby.endsWith("-asc")){ 1871 return orderby.replaceAll("-asc", "")+" asc"; 1872 }else{ 1873 return orderby; 1874 } 1875 } 1876 return null; 1877 } 1878 1879 /** 1880 * 把时间转换成相应格式的字符串 1881 * @param date 1882 * @param formart 1883 * @return 1884 */ 1885 public String getCurrentDateString(Date date,String formart){ 1886 SimpleDateFormat sd=new SimpleDateFormat(formart); 1887 return sd.format(date); 1888 } 1889 1890 1891 1892 1893 1894 1895 1896 /** 1897 * 通过用户帐号,查询用户名称 1898 * @param request 1899 * @return 1900 */ 1901 public String getUserName(String partyId){ 1902 String userName=""; 1903 if(StringUtil.isNotEmptyAndBlank(partyId)){ 1904 SysUser sysUser =(SysUser) genericService.getEntity(" from SysUser where partyId='"+partyId+"'"); 1905 if(sysUser!=null&&sysUser.getSysUserInfo()!=null){ 1906 userName = sysUser.getSysUserInfo().getLastName(); 1907 } 1908 1909 } 1910 return userName; 1911 } 1912 1913 /** 1914 * 通过用户帐号,查询用户名称 1915 * @param request 1916 * @return 1917 */ 1918 public String getUserName(String partyId,GenericService genericService){ 1919 String userName=""; 1920 if(StringUtil.isNotEmptyAndBlank(partyId)){ 1921 SysUser sysUser =(SysUser) genericService.getEntity(" from SysUser where partyId='"+partyId+"'"); 1922 if(sysUser!=null&&sysUser.getSysUserInfo()!=null){ 1923 userName = sysUser.getSysUserInfo().getLastName(); 1924 } 1925 1926 } 1927 return userName; 1928 } 1929 1930 1931 1932 1933 1934 1935 1936 /** 1937 * Simple function of the direct output. 1938 * 1939 * eg. render("text/plain", "hello", "encoding:GBK"); render("text/plain", "hello", "no-cache:false"); 1940 * render("text/plain", "hello", "encoding:GBK", "no-cache:false"); 1941 * 1942 */ 1943 public void render(HttpServletResponse response,String contentType, String content) { 1944 try { 1945 String encoding = "UTF-8"; 1946 String fullContentType = contentType + ";charset=" + encoding; 1947 response.setContentType(fullContentType); 1948 response.setHeader("Pragma", "No-cache"); 1949 response.setHeader("Cache-Control", "no-cache"); 1950 response.setDateHeader("Expires", 0); 1951 response.getWriter().write(content); 1952 response.getWriter().flush(); 1953 } catch (IOException e) { 1954 e.printStackTrace(); 1955 } 1956 } 1957 1958 /** 1959 * Direct output JSON. 1960 * 1961 * @param object 1962 * Java objects, will be transformed into json string. 1963 * @see #render(HttpServletResponse, String, String) 1964 */ 1965 public void renderJson(HttpServletResponse response,Object object) { 1966 String jsonString = JSONObject.fromObject(object).toString(); 1967 render(response,JSON, jsonString); 1968 } 1969 1970 /** 1971 * Direct output JSON. 1972 * 1973 * @param map 1974 * Map objects, will be transformed into json string. 1975 */ 1976 public void renderJson(HttpServletResponse response,Map map) { 1977 String jsonString = JSONObject.fromObject(map).toString(); 1978 render(response,JSON, jsonString); 1979 } 1980 1981 /** 1982 * Direct output JSON. 1983 * 1984 * @param map 1985 * Map objects, will be transformed into json string. 1986 */ 1987 public void renderJson(HttpServletResponse response,List list) { 1988 String jsonString = JsonUtil.list2json(list); 1989 render(response,JSON, jsonString); 1990 } 1991 1992 /** 1993 * 获取自定列 1994 * @param request 1995 */ 1996 public void getDefColumnField(HttpServletRequest request){ 1997 String entityName = request.getParameter("entityName"); 1998 String columnSelection = request.getParameter("columnSelection"); 1999 List<DefColumnField> defColumnFieldList = defColumnFieldService.getListByEntityName(entityName); 2000 List<DefColumnField> showDefColumnFieldList = new ArrayList<DefColumnField>(); 2001 for(DefColumnField field:defColumnFieldList){ 2002 if(!StringUtil.isNotEmptyAndBlank(columnSelection) || columnSelection.indexOf(field.getFieldId()) > -1){ 2003 field.setChecked("checked"); 2004 showDefColumnFieldList.add(field); 2005 }else{ 2006 field.setChecked(""); 2007 } 2008 } 2009 request.setAttribute("defColumnFieldList", defColumnFieldList); 2010 request.setAttribute("showDefColumnFieldList", showDefColumnFieldList); 2011 request.setAttribute("columnSelection", columnSelection); 2012 2013 } 2014 2015 /** 2016 * 查询指定用户是否属于指定角色 2017 * @param partyId 用户账号 2018 * @param roleName 角色名称 2019 * @return boolean 2020 */ 2021 public boolean checkUserInRole(String partyId,String roleName){ 2022 boolean flg=false; 2023 SysUserRole sysUserRole = (SysUserRole)genericService.getEntity(" from SysUserRole where sysUser.partyId='"+partyId+"' and sysRole.name='"+roleName+"'"); 2024 if(sysUserRole!=null&&sysUserRole.getId()!=null){ 2025 flg = true; 2026 } 2027 return flg; 2028 } 2029 }