BusinessUtils.java 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. /**
  2. *
  3. * Copyright (c) behosoft Co.,Ltd.
  4. * All Rights Reserved.
  5. *
  6. * This software is the confidential and proprietary information of behosoft.
  7. * (Social Security Department). You shall not disclose such
  8. * Confidential Information and shall use it only in accordance with
  9. * the terms of the license agreement you entered into with behosoft.
  10. *
  11. * Distributable under GNU LGPL license by gnu.org
  12. */
  13. package com.behosoft.util;
  14. import java.beans.PropertyDescriptor;
  15. import java.io.File;
  16. import java.io.FileInputStream;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.math.BigDecimal;
  20. import java.math.BigInteger;
  21. import java.sql.Blob;
  22. import java.sql.ResultSet;
  23. import java.sql.ResultSetMetaData;
  24. import java.sql.SQLException;
  25. import java.sql.Timestamp;
  26. import java.text.SimpleDateFormat;
  27. import java.util.ArrayList;
  28. import java.util.Calendar;
  29. import java.util.Collection;
  30. import java.util.Date;
  31. import java.util.HashMap;
  32. import java.util.List;
  33. import java.util.Map;
  34. import java.util.regex.Pattern;
  35. import javax.persistence.Column;
  36. import javax.servlet.http.HttpServletRequest;
  37. import net.sf.json.JSONNull;
  38. import org.apache.commons.beanutils.PropertyUtils;
  39. import org.apache.commons.logging.Log;
  40. import org.apache.commons.logging.LogFactory;
  41. import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
  42. import org.hibernate.mapping.Property;
  43. import org.josql.Query;
  44. import org.josql.QueryExecutionException;
  45. import org.josql.QueryParseException;
  46. import org.josql.QueryResults;
  47. import org.springframework.util.CollectionUtils;
  48. import com.behosoft.framework.web.dto.UploadFileDto;
  49. import com.behosoft.framework.web.exception.CommonException;
  50. import com.behosoft.framework.web.model.RecordBO;
  51. import com.behosoft.lis.BusinessConstants;
  52. import com.behosoft.lis.context.BusinessSessionContext;
  53. import com.behosoft.lis.model.vo.UserVO;
  54. import com.behosoft.lis.util.PDAContextUtil;
  55. import com.behosoft.util.ftputil.FTPUtil;
  56. import com.wondersgroup.framework.core.bo.Page;
  57. import com.wondersgroup.framework.core.web.vo.JsonDateValueProcessor;
  58. import com.wondersgroup.framework.util.preloadutil.AppContextUtils;
  59. import com.wondersgroup.saas.exception.UtilsException;
  60. import com.wondersgroup.saas.meta.query.ConditionRule;
  61. import com.wondersgroup.saas.meta.query.QueryBean;
  62. import com.wondersgroup.saas.sql.HibernateMetaSupport;
  63. import com.wondersgroup.saas.util.CommonUtils;
  64. import com.wondersgroup.saas.util.FileExposeUtil;
  65. import com.wondersgroup.saas.util.PropertiesManager;
  66. import dateparse.Expression;
  67. import dateparse.util.StringUtils;
  68. /**
  69. * <p>
  70. * Title: WMS_common_utils
  71. * </p>
  72. * <p>
  73. * Description: 公共工具类
  74. * </p>
  75. *
  76. * @author liudd
  77. * @version $Revision$ 2009-8-12
  78. * @author (lastest modification by $Author$)
  79. * @since 1.0
  80. */
  81. @SuppressWarnings("unchecked")
  82. public class BusinessUtils extends CommonUtils {
  83. /**
  84. * LOGGER
  85. */
  86. private static final Log LOGGER = LogFactory.getLog(BusinessUtils.class);
  87. /**
  88. * <p>
  89. * Description: 附加创建或更新信息
  90. * </p>
  91. *
  92. * @param bo BO对象
  93. */
  94. public static void appendRecordForBO(RecordBO bo) {
  95. String loginName = "system";
  96. Map<String,Object> params = PDAContextUtil.getParams();
  97. if (null != params)
  98. {
  99. Object userObject = params.get(BusinessConstants.USER_INFO);
  100. if (null != userObject)
  101. {
  102. UserVO userVO = (UserVO)userObject;
  103. loginName = userVO.getUserLoginName();
  104. }
  105. }
  106. if( BusinessSessionContext.getLoginName()!=null){
  107. loginName = String.valueOf(BusinessSessionContext.getLoginName());
  108. }
  109. appendRecordForBO(bo, loginName, BusinessConstants.PROCESS_MODE_WEB);
  110. }
  111. /**
  112. * <p>
  113. * Description: 清除创建或更新信息
  114. * </p>
  115. *
  116. * @param bo BO对象
  117. */
  118. public static void clearRecordForBO(RecordBO bo) {
  119. bo.setCreationMethod(null);
  120. bo.setCreationTime(null);
  121. bo.setCreatedBy(null);
  122. bo.setUpdatedBy(null);
  123. bo.setUpdateMethod(null);
  124. bo.setUpdateTime(null);
  125. }
  126. /**
  127. * <p>
  128. * Description:append some data for bo
  129. * </p>
  130. *
  131. * @param bo RecordBO
  132. * @param loginName loginName
  133. */
  134. public static void appendRecordForBO(RecordBO bo, String loginName) {
  135. appendRecordForBO(bo, loginName, BusinessConstants.PROCESS_MODE_WEB);
  136. }
  137. /**
  138. * <p>
  139. * Description:append some data for bo
  140. * </p>
  141. *
  142. * @param bo RecordBO
  143. * @param loginName 操作人
  144. * @param processMethod 处理方法
  145. */
  146. public static void appendRecordForBO(RecordBO bo, String loginName, String processMethod) {
  147. Date date = new Date();
  148. if (bo.getCreationTime() == null) {
  149. bo.setCreationTime(date);
  150. bo.setUpdateTime(date);
  151. }
  152. else {
  153. bo.setUpdateTime(date);
  154. }
  155. if (bo.getCreatedBy() == null) {
  156. bo.setCreatedBy(loginName);
  157. bo.setUpdatedBy(loginName);
  158. bo.setCreationMethod(processMethod);
  159. bo.setUpdateMethod(processMethod);
  160. }
  161. else {
  162. bo.setUpdatedBy(loginName);
  163. bo.setUpdateMethod(processMethod);
  164. }
  165. if (bo.getDeleteFlag() == null) {
  166. bo.setDeleteFlag(0);
  167. }
  168. }
  169. /**
  170. * <p>
  171. * Description: append some data for map
  172. * </p>
  173. *
  174. * @param map
  175. */
  176. public static void appendRecordForMap(Map<String, Object> map) {
  177. map.put("updatedBy", BusinessSessionContext.getLoginName());
  178. map.put("updateTime", new Date());
  179. map.put("updateMethod", BusinessConstants.PROCESS_MODE_WEB);
  180. }
  181. /**
  182. * <p>
  183. * Description: append some data for map
  184. * </p>
  185. *
  186. * @param map
  187. * @param processMode 处理方式(web、edi、ws)
  188. */
  189. public static void appendRecordForMap(Map<String, Object> map, String processMode) {
  190. if (processMode == null || processMode.length() == 0) {
  191. appendRecordForMap(map);
  192. }
  193. else {
  194. map.put("updatedBy", BusinessSessionContext.getLoginName());
  195. map.put("updateTime", new Date());
  196. map.put("updateMethod", BusinessConstants.PROCESS_MODE_WEB);
  197. }
  198. }
  199. /**
  200. * <p>
  201. * Description: append some data for map
  202. * </p>
  203. *
  204. * @param map
  205. * @param processMode 处理方式(web、edi、ws)
  206. */
  207. public static void appendRecordForMap(Map<String, Object> map, String processMode, String processor) {
  208. if (processMode == null || processMode.length() == 0) {
  209. processMode = BusinessConstants.PROCESS_MODE_WEB;
  210. }
  211. if (processor == null || processor.length() == 0) {
  212. processor = BusinessSessionContext.getLoginName();
  213. }
  214. map.put("updatedBy", processor);
  215. map.put("updateTime", new Date());
  216. map.put("updateMethod", processMode);
  217. }
  218. public static List<String> spilitArrayFromString(String str, String spliter) {
  219. List<String> list = new ArrayList<String>();
  220. if (isNotBlank(str)) {
  221. String[] spliteArray = str.split(spliter);
  222. for (String s : spliteArray) {
  223. if (isNotBlank(s)) {
  224. list.add(s.trim());
  225. }
  226. }
  227. }
  228. return list;
  229. }
  230. /**
  231. * <p>
  232. * Description:检查字符串不为NULL,也不为空字符串
  233. * </p>
  234. *
  235. * @param value
  236. * @return
  237. */
  238. public static boolean isNotBlank(Object value) {
  239. return !JSONNull.getInstance().equals(value)
  240. && !(value instanceof String && ((String) value).trim().equals(""));
  241. }
  242. public static <T> T mapRowDataToPojo(Class<T> pojo, Class<?> boClass, ResultSet rs,
  243. HibernateMetaSupport hibernateMetaSupport) throws SQLException {
  244. return mapRowDataToPojo(pojo, boClass, rs, hibernateMetaSupport, new HashMap<String, String>());
  245. }
  246. /**
  247. * <p>
  248. * Description: 将数据集中的行映射为POJO对象
  249. * </p>
  250. *
  251. * @param <T>
  252. * @param pojo
  253. * @param rs
  254. * @param hibernateMetaSupport
  255. * @return
  256. * @throws InstantiationException
  257. * @throws IllegalAccessException
  258. * @throws SQLException
  259. */
  260. public static <T> T mapRowDataToPojo(Class<T> pojo, Class<?> boClass, ResultSet rs,
  261. HibernateMetaSupport hibernateMetaSupport, Map<String, String> dateMap) throws SQLException {
  262. // if (dateFormat != null) {
  263. // jsonDateValueProcessor.setDateFormat(new
  264. // SimpleDateFormat(dateFormat));
  265. // }
  266. if (hibernateMetaSupport == null) {
  267. hibernateMetaSupport =
  268. (HibernateMetaSupport) AppContextUtils.getApplicationContext().getBean("hibernateMetaSupport");
  269. }
  270. T instance = null;
  271. try {
  272. instance = pojo.newInstance();
  273. }
  274. catch (Exception e) {
  275. throw new UtilsException(e.getMessage());
  276. }
  277. ResultSetMetaData resultSetMetaData = rs.getMetaData();
  278. for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
  279. String fieldName = resultSetMetaData.getColumnName(i);
  280. try {
  281. Property property = hibernateMetaSupport.getPropertyByColumnName(boClass, fieldName, false);
  282. if (property == null) {
  283. LOGGER.info("No Such Field: " + fieldName + " For " + pojo.getName());
  284. continue;
  285. }
  286. fieldName = property.getName();
  287. Object value = rs.getObject(i);
  288. if (property.getType().getReturnedClass() == Boolean.class
  289. || property.getType().getReturnedClass() == boolean.class) {
  290. value = rs.getBoolean(i);
  291. }
  292. if( fieldName.equalsIgnoreCase("deleteFlag")){
  293. System.out.println(property.getType().getReturnedClass());
  294. }
  295. if (value != null && value instanceof BigDecimal) {
  296. if( property.getType().getReturnedClass()==Integer.class ){
  297. PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).intValue());
  298. }else if(property.getType().getReturnedClass()==Double.class ){
  299. PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).doubleValue());
  300. }else if(property.getType().getReturnedClass()==Float.class ){
  301. PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).floatValue());
  302. }else if(property.getType().getReturnedClass()==Long.class ){
  303. PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).longValue());
  304. }else{
  305. PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).doubleValue());
  306. }
  307. }
  308. else if (value != null && value instanceof BigInteger) {
  309. if( property.getType().getReturnedClass()==Integer.class ){
  310. PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).intValue());
  311. }else if(property.getType().getReturnedClass()==Double.class ){
  312. PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).doubleValue());
  313. }else if(property.getType().getReturnedClass()==Float.class ){
  314. PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).floatValue());
  315. }else if(property.getType().getReturnedClass()==Long.class ){
  316. PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).longValue());
  317. }
  318. else{
  319. PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).longValue());
  320. }
  321. }
  322. else if (value != null && property.getType().getReturnedClass().equals(Short.class)) {
  323. PropertyUtils.setProperty(instance, fieldName, ((Integer) value).shortValue());
  324. }
  325. else if (value != null && value instanceof Date) {
  326. if (dateMap != null) {
  327. for (Map.Entry<String, String> entry : dateMap.entrySet()) {
  328. if (fieldName.equals(entry.getKey())) {
  329. JsonDateValueProcessor jsonDateValueProcessor = new JsonDateValueProcessor();
  330. if (entry.getValue() != null || !"".equals(entry.getValue())) {
  331. jsonDateValueProcessor.setDateFormat(new SimpleDateFormat(entry.getValue()));
  332. }
  333. value = jsonDateValueProcessor.processArrayValue((value), null);
  334. break;
  335. }
  336. }
  337. }
  338. PropertyUtils.setProperty(instance, fieldName, value);
  339. }
  340. else if (value != null
  341. && (value instanceof byte[] || value instanceof InputStream || value instanceof Blob)) {
  342. value = rs.getBlob(i);
  343. PropertyUtils.setProperty(instance, fieldName, value);
  344. }
  345. else {
  346. PropertyUtils.setProperty(instance, fieldName, value);
  347. }
  348. }
  349. catch (NoSuchMethodException e) {
  350. LOGGER.debug("No Such Field: " + fieldName + " For " + pojo.getName());
  351. }
  352. catch (Exception e) {
  353. throw new CommonException("set property value error : " + fieldName + " in class " + pojo.getName(), e);
  354. }
  355. }
  356. return instance;
  357. }
  358. /**
  359. * <p>
  360. * Description:文件上传
  361. * </p>
  362. *
  363. * @param request
  364. * @param requestFile request对象中file的name
  365. * @param rootPath the root path to save
  366. * @param uniqueKey
  367. * @param moduleKey
  368. * @throws Exception
  369. */
  370. public static UploadFileDto fileUpload(HttpServletRequest request, String requestFile, String rootPath,
  371. String moduleKey) {
  372. MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
  373. String[] filenames = multiWrapper.getFileNames(requestFile);
  374. String[] localPaths = multiWrapper.getFileNames(requestFile);
  375. if (multiWrapper.hasErrors()) {
  376. throw new CommonException("io.fileuploaderror");
  377. }
  378. if (filenames == null) {
  379. return null;
  380. }
  381. if (filenames.length == 0) {
  382. throw new CommonException("io.unsupportmethod");
  383. }
  384. File[] files = multiWrapper.getFiles(requestFile);
  385. String path = rootPath + "\\" + moduleKey + "\\";
  386. String[] filePaths = new String[files.length];
  387. String[] serverNames = new String[files.length];
  388. if (!FileExposeUtil.checkFileExist(path)) {
  389. // create folder
  390. FileExposeUtil.createFile(path);
  391. }
  392. for (int i = 0; i < files.length; i++) {
  393. try {
  394. serverNames[i] = System.currentTimeMillis() + filenames[i];
  395. filePaths[i] = path + serverNames[i];
  396. // 如果上传文件大小为0,则新建文件
  397. if (!files[i].exists()) {
  398. files[i] = File.createTempFile(files[i].getName(), "", files[i].getParentFile());
  399. }
  400. FileExposeUtil.copyFile(files[i], filePaths[i]);
  401. }
  402. catch (Exception e) {
  403. throw new CommonException("io.unsupportmethod");
  404. }
  405. }
  406. UploadFileDto dto = new UploadFileDto(localPaths, filePaths, filenames, serverNames);
  407. return dto;
  408. }
  409. /**
  410. * <p>
  411. * Description:文件上传
  412. * </p>
  413. *
  414. * @param inputStream 输入流
  415. * @param fileName 文件名称
  416. * @param rootPath the root path to save
  417. * @param moduleKey 子目录名称
  418. * @throws Exception
  419. */
  420. public static String fileUpload(InputStream inputStream, String fileName, String rootPath, String moduleKey) {
  421. if (fileName == null) {
  422. throw new CommonException("io.unsupportmethod");
  423. }
  424. String path = rootPath + "\\" + moduleKey + "\\";
  425. if (!FileExposeUtil.checkFileExist(path)) {
  426. // create folder
  427. FileExposeUtil.createFile(path);
  428. }
  429. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-ms");
  430. String serverName = formatter.format(new Date()) + "-" + fileName;
  431. try {
  432. FileExposeUtil.saveFile(inputStream, path, serverName, true);
  433. }
  434. catch (Exception e) {
  435. throw new CommonException("io.unsupportmethod");
  436. }
  437. return path + "\\" + serverName;
  438. }
  439. /**
  440. * <p>
  441. * Description:文件上传
  442. * </p>
  443. *
  444. * @param request
  445. * @param requestFile request对象中file的name
  446. * @param moduleKey 子目录
  447. * @throws Exception
  448. */
  449. public static UploadFileDto fileUploadForFTP(HttpServletRequest request, String requestFile, String moduleKey) {
  450. MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
  451. String[] filenames = multiWrapper.getFileNames(requestFile);
  452. String[] localPaths = multiWrapper.getFileNames(requestFile);
  453. if (multiWrapper.hasErrors()) {
  454. throw new CommonException("io.fileuploaderror");
  455. }
  456. if (filenames == null) {
  457. return null;
  458. }
  459. if (filenames.length == 0) {
  460. throw new CommonException("io.unsupportmethod");
  461. }
  462. if (moduleKey == null || org.apache.commons.lang.StringUtils.isWhitespace(moduleKey)) {
  463. moduleKey = "default";
  464. }
  465. else {
  466. moduleKey = moduleKey.trim();
  467. }
  468. File[] files = multiWrapper.getFiles(requestFile);
  469. String[] localFileNameArrs = new String[files.length];
  470. String[] filePaths = new String[files.length];
  471. String[] serverNames = new String[files.length];
  472. String path = "\\" + moduleKey + "\\";
  473. for (int i = 0; i < files.length; i++) {
  474. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-ms");
  475. String localFileName = formatter.format(new Date()) + "-" + filenames[i];
  476. Integer stamp = 0;
  477. while (FTPUtil.fileExist(localFileName)) {
  478. stamp += 1;
  479. localFileName =
  480. formatter.format(new Date()) + stamp.toString() + "-"
  481. + FileExposeUtil.getFileName(localFileName);
  482. }
  483. serverNames[i] = localFileName;
  484. filePaths[i] = path.replaceAll("\\\\", "/") + localFileName;
  485. InputStream is = null;
  486. try {
  487. // FileExposeUtil.copyFile(documentSourceAddress,
  488. // documentTargetAddress);
  489. is = new FileInputStream(files[i]);
  490. FTPUtil.uploadFile(is, path, localFileName);
  491. localFileNameArrs[i] = localFileName;
  492. }
  493. catch (Exception e) {
  494. e.printStackTrace();
  495. FTPUtil.dirFile(localFileName);
  496. return null;
  497. }
  498. finally {
  499. try {
  500. if (is != null) {
  501. is.close();
  502. }
  503. }
  504. catch (IOException e) {
  505. e.printStackTrace();
  506. }
  507. }
  508. }
  509. UploadFileDto dto = new UploadFileDto(localPaths, filePaths, filenames, serverNames);
  510. return dto;
  511. }
  512. /**
  513. * <p>
  514. * Description:文件上传
  515. * </p>
  516. *
  517. * @param request
  518. * @param requestFile request对象中file的name
  519. * @throws Exception
  520. */
  521. public static UploadFileDto fileUploadForFTP(HttpServletRequest request, String requestFile) {
  522. return fileUploadForFTP(request, requestFile, null);
  523. }
  524. /**
  525. * <p>
  526. * Description:内存查询
  527. * </p>
  528. *
  529. * @param <T> 实体泛型
  530. * @param entity 实体类型
  531. * @param datas 数据集
  532. * @param sql SQL语句,面向实体类型
  533. * @param params 参数
  534. * @return
  535. */
  536. public static <T> Collection<T> findBySQL(Class<T> entity, Collection<T> datas, String sql, Object... params) {
  537. if (CollectionUtils.isEmpty(datas)) {
  538. return null;
  539. }
  540. sql = sql.replaceAll("#entity", entity.getName());
  541. Query query = new Query();
  542. try {
  543. query.parse(sql);
  544. }
  545. catch (QueryParseException e) {
  546. throw new UtilsException("parse sql error", e);
  547. }
  548. if (params != null) {
  549. for (int i = 0; i < params.length; i++) {
  550. query.setVariable(i + 1, params[i]);
  551. }
  552. }
  553. QueryResults qr = null;
  554. try {
  555. qr = query.execute(datas);
  556. }
  557. catch (QueryExecutionException e) {
  558. throw new UtilsException("mem query error", e);
  559. }
  560. Collection<T> tempColl = qr.getResults();
  561. if (tempColl == null) {
  562. tempColl = new ArrayList<T>();
  563. }
  564. return tempColl;
  565. }
  566. /**
  567. * <p>
  568. * Description:内存分页查询
  569. * </p>
  570. *
  571. * @param <T> 实体泛型
  572. * @param entity 实体类型
  573. * @param datas 数据集
  574. * @param sql SQL语句,面向实体类型
  575. * @param pageNo 页号
  576. * @param pageSize 页面容量
  577. * @param params 参数
  578. * @return
  579. */
  580. public static <T> Page findForMapBySQLWithPage(Class<T> entity, Collection<T> datas, String sql, int pageNo,
  581. int pageSize, Map<String, Object> params) {
  582. if (CollectionUtils.isEmpty(datas)) {
  583. return null;
  584. }
  585. int start = Page.getStartOfAnyPage(pageNo);
  586. sql = sql.replaceAll("#entity", entity.getName());
  587. sql = new StringBuffer(sql).append(" limit ").append(start).append(", ").append(pageSize).toString();
  588. Query query = new Query();
  589. try {
  590. query.parse(sql);
  591. }
  592. catch (QueryParseException e) {
  593. throw new UtilsException("parse sql error", e);
  594. }
  595. if (params != null) {
  596. for (Map.Entry<String, Object> entry : params.entrySet()) {
  597. query.setVariable(entry.getKey(), entry.getValue());
  598. }
  599. }
  600. QueryResults qr = null;
  601. try {
  602. qr = query.execute(datas);
  603. }
  604. catch (QueryExecutionException e) {
  605. throw new UtilsException("mem query error", e);
  606. }
  607. List<?> result = qr.getResults();
  608. Page page = null;
  609. if (result != null) {
  610. page = new Page(start, result.size(), datas.size(), pageSize, result);
  611. }
  612. else {
  613. page = new Page(0, 0, 0, pageSize, null);
  614. }
  615. return page;
  616. }
  617. /**
  618. * <p>
  619. * Description:[通过文件名称获取文件类型]
  620. * </p>
  621. *
  622. * @param fileName 文件名称
  623. * @return
  624. */
  625. public static String getFileType(String fileName) {
  626. String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
  627. if (suffix.equals("xls") || suffix.equals("xlsx")) {
  628. return "excel";
  629. }
  630. else if (suffix.equals("doc") || suffix.equals("docx")) {
  631. return "word";
  632. }
  633. return null;
  634. }
  635. /**
  636. * <p>
  637. * Description:产生具有前缀和后缀的唯一字符串,中间14位
  638. * </p>
  639. *
  640. * @param prefix
  641. * @param suffix
  642. * @return
  643. */
  644. public static String createUniqueKey(String prefix, String suffix) {
  645. int randomNumber = (int) (Math.random() * 9);
  646. Calendar cal = Calendar.getInstance();
  647. StringBuffer key = new StringBuffer();
  648. String year = String.valueOf(cal.get(Calendar.YEAR)).substring(3);
  649. int month = cal.get(Calendar.MONTH) + 1;
  650. int date = cal.get(Calendar.DATE);
  651. int hour = cal.get(Calendar.HOUR_OF_DAY);
  652. int minute = cal.get(Calendar.MINUTE);
  653. int second = cal.get(Calendar.SECOND);
  654. int millisecond = cal.get(Calendar.MILLISECOND);
  655. // System.out.println(millisecond);
  656. key.append(prefix).append(year).append(month < 10 ? "0" + month : month).append(date < 10 ? "0" + date : date)
  657. .append(hour < 10 ? "0" + hour : hour).append(minute < 10 ? "0" + minute : minute).append(
  658. second < 10 ? "0" + second : second).append(millisecond < 10 ? "0" + millisecond : millisecond)
  659. .append(randomNumber).append(suffix);
  660. return key.toString();
  661. }
  662. /**
  663. * <p>
  664. * Description:[产生具有前缀和后缀的唯一字符串,中间14位+自定义提示表名]
  665. * </p>
  666. *
  667. * @param prefix
  668. * @param suffix
  669. * @param gridConfigBean
  670. * @return
  671. * @throws Exception
  672. */
  673. public static String createUniqueKey(String prefix, String suffix, String prefix_support) {
  674. String csvName = getI18N(prefix_support);
  675. if (csvName == null || csvName.trim().length() == 0) {
  676. throw new CommonException("The ModuleCode of the FormBean is Empty");
  677. }
  678. int randomNumber = (int) (Math.random() * 9);
  679. Calendar cal = Calendar.getInstance();
  680. StringBuffer key = new StringBuffer();
  681. String year = String.valueOf(cal.get(Calendar.YEAR)).substring(3);
  682. int month = cal.get(Calendar.MONTH) + 1;
  683. int date = cal.get(Calendar.DATE);
  684. int hour = cal.get(Calendar.HOUR_OF_DAY);
  685. int minute = cal.get(Calendar.MINUTE);
  686. int second = cal.get(Calendar.SECOND);
  687. int millisecond = cal.get(Calendar.MILLISECOND);
  688. // System.out.println(millisecond);
  689. key.append(prefix).append(year).append(month < 10 ? "0" + month : month).append(date < 10 ? "0" + date : date)
  690. .append(hour < 10 ? "0" + hour : hour).append(minute < 10 ? "0" + minute : minute).append(
  691. second < 10 ? "0" + second : second).append(millisecond < 10 ? "0" + millisecond : millisecond)
  692. .append(randomNumber).append("——" + csvName).append(suffix);
  693. return key.toString();
  694. }
  695. /**
  696. * <p>
  697. * Description:[方法功能中文描述]
  698. * </p>
  699. *
  700. * @param key
  701. * @return
  702. */
  703. private static String getI18N(String key) {
  704. if (key == null || "".equals(key)) {
  705. return "null";
  706. }
  707. String value = CommonUtils.getLocalizedMsg(key);
  708. if (value == null) {
  709. return key;
  710. }
  711. return value;
  712. }
  713. /**
  714. * <p>
  715. * Description: 对query bean中的日期表达式进行转化
  716. * </p>
  717. *
  718. * @param queryBean
  719. */
  720. public static void parseQueryDateExpression(QueryBean queryBean) {
  721. if (queryBean != null) {
  722. List<ConditionRule> conditionRules = queryBean.getConditionRules();
  723. if (conditionRules != null) {
  724. for (ConditionRule rule : conditionRules) {
  725. // according to the searchwidge.js
  726. if ("@DateExpression".equals(rule.getExpression())) {
  727. String field = rule.getField();
  728. formatDateConditionRule(rule, field);
  729. if (rule.getAppend() != null) {
  730. formatDateConditionRule(rule.getAppend(), field);
  731. }
  732. }
  733. }
  734. }
  735. }
  736. }
  737. /**
  738. * <p>
  739. * Description: 对日期类型的查询条件进行转化
  740. * </p>
  741. *
  742. * @param rule
  743. * @param field
  744. */
  745. public static void formatDateConditionRule(ConditionRule rule, String field) {
  746. Date date = Expression.excute(rule.getValue());
  747. if (date != null) {
  748. String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
  749. rule.setExpression("Date(${" + field + "}) " + rule.getOperator() + " '" + formatDate + "'");
  750. rule.setField(null);
  751. }
  752. else {
  753. String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(0));
  754. rule.setExpression("Date(${" + field + "}) < '" + formatDate + "'");
  755. rule.setField(null);
  756. }
  757. }
  758. /**
  759. * <p>
  760. * Description: 对query bean中的新关键字:当前用户(loginName)、空(is null is not null)进行转化
  761. * </p>
  762. *
  763. * @param queryBean
  764. */
  765. public static void parseQuerySpecialKeyWords(QueryBean queryBean) {
  766. if (queryBean != null) {
  767. List<ConditionRule> conditionRules = queryBean.getConditionRules();
  768. if (conditionRules != null) {
  769. for (ConditionRule rule : conditionRules) {
  770. String swValue = rule.getValue();
  771. if (swValue != null && swValue.startsWith("{") && swValue.endsWith("}")) {
  772. String swValueString = swValue.substring(1, swValue.length() - 1);
  773. swValueString = StringUtils.trimAllWhitespace(swValueString);
  774. if (swValueString.equalsIgnoreCase(getLocalizedMsg("common.msg.currentUser"))) {
  775. rule.setValue(BusinessSessionContext.getLoginName());
  776. }
  777. else if (swValueString.equalsIgnoreCase(getLocalizedMsg("common.msg.null"))) {
  778. rule.setValue(null);
  779. if (rule.getOperator().equalsIgnoreCase("=")) {
  780. rule.setOperator("is");
  781. }
  782. else if (rule.getOperator().equalsIgnoreCase("<>")) {
  783. rule.setOperator("is not");
  784. }
  785. }
  786. }
  787. // }
  788. }
  789. }
  790. }
  791. }
  792. /**
  793. * <p>
  794. * Description:[方法功能中文描述]
  795. * </p>
  796. *
  797. * @param message
  798. * @return
  799. */
  800. public static Long getMenuId(String message) {
  801. if (message == null)
  802. return null;
  803. String localizedMsg = PropertiesManager.getProperty(message);
  804. return localizedMsg != null ? Long.valueOf(localizedMsg) : -1L;
  805. }
  806. /**
  807. * <p>
  808. * Description:[当前日期转换成时间戳]
  809. * </p>
  810. *
  811. * @param message
  812. * @return
  813. */
  814. public static Timestamp dateChangeToTimestamp(Date date) {
  815. Timestamp timeStamp = new Timestamp(new Date().getTime());
  816. return timeStamp;
  817. }
  818. /**
  819. * <p>
  820. * Description:[生成明细行号]
  821. * </p>
  822. *
  823. * @param detailCount 明细数
  824. * @return
  825. */
  826. public static String generateDetailLineNo(Integer detailCount) {
  827. if (detailCount == null) {
  828. detailCount = 0;
  829. }
  830. return String.valueOf((BusinessConstants.GENERATE_DETAIL_LINE_NO + ++detailCount)).substring(1);
  831. }
  832. /**
  833. * <p>
  834. * Description:[得到第二天的时间]
  835. * </p>
  836. *
  837. * @param date 日期对象
  838. * @param formateTemplete 日期格式
  839. * @return
  840. */
  841. public static Date getNextDate(Date date) {
  842. Calendar cal = Calendar.getInstance();
  843. cal.add(Calendar.DATE, 1);
  844. return cal.getTime();
  845. }
  846. /**
  847. * 根据entity Class 得到其中的注解元素 我们可以得到对象的name和数据库中的字段相对应
  848. *
  849. * @param entityClass
  850. * @return
  851. */
  852. public static Map<String, String> createEntityColumnMap(Class entityClass) {
  853. Map<String, String> entityColumnMap = new HashMap<String, String>();
  854. PropertyDescriptor[] propDescs = PropertyUtils.getPropertyDescriptors(entityClass);
  855. for (PropertyDescriptor propDesc : propDescs) {
  856. // 取得注释的column
  857. Column column = propDesc.getReadMethod().getAnnotation(Column.class);
  858. if (column != null) {
  859. String columnName = column.name().toUpperCase();
  860. String propertyName = propDesc.getName();
  861. entityColumnMap.put(propertyName, columnName);
  862. }
  863. }
  864. return entityColumnMap;
  865. }
  866. /**
  867. * <p>
  868. * Description:[通过queyBean生成JoSQL]
  869. * </p>
  870. *
  871. * @param query
  872. * @param excludeFields 忽略字段
  873. * @return
  874. */
  875. public static String generateJoSQL(QueryBean query, String[] excludeFields) {
  876. StringBuffer sql = new StringBuffer("select * from #entity where 1=1 ");
  877. if (query != null) {
  878. if (query.getConditionRules() != null) {
  879. out1: for (ConditionRule con : query.getConditionRules()) {
  880. String filed = con.getField();
  881. for (String exludeFiled : excludeFields) {
  882. if (filed.equalsIgnoreCase(exludeFiled)) {
  883. continue out1;
  884. }
  885. }
  886. String value = con.getValue();
  887. sql.append("and ").append(filed).append(" ").append(con.getOperator());
  888. if (con.getOperator().equals("like")) {
  889. sql.append(" '%").append(value).append("%'");
  890. }
  891. else {
  892. sql.append("\'").append(value).append("\'");
  893. }
  894. }
  895. }
  896. if (query.getExtraConditionRules() != null) {
  897. out2: for (ConditionRule con : query.getExtraConditionRules()) {
  898. String filed = con.getField();
  899. for (String exludeFiled : excludeFields) {
  900. if (filed.equalsIgnoreCase(exludeFiled)) {
  901. continue out2;
  902. }
  903. }
  904. String value = con.getValue();
  905. sql.append("and ").append(filed).append(" ").append(con.getOperator());
  906. if (con.getOperator().equals("like")) {
  907. sql.append(" '%").append(value).append("%'");
  908. }
  909. else {
  910. sql.append("\'").append(value).append("\'");
  911. }
  912. }
  913. }
  914. }
  915. return sql.toString();
  916. }
  917. /**
  918. * <p>
  919. * Description:内存分页查询
  920. * </p>
  921. *
  922. * @param <T> 实体泛型
  923. * @param entity 实体类型
  924. * @param datas 数据集
  925. * @param queryBean 查询实体
  926. * @param pageNo 页号
  927. * @param pageSize 页面容量
  928. * @param excludeFields 过滤参数
  929. * @return
  930. */
  931. public static <T> Page findByJoSQLWithPage(Class<T> entity, Collection<T> datas, QueryBean queryBean, int pageNo,
  932. int pageSize, String[] excludeFields) {
  933. if (CollectionUtils.isEmpty(datas)) {
  934. return null;
  935. }
  936. String sql = generateJoSQL(queryBean, excludeFields);
  937. sql = sql.replaceAll("#entity", entity.getName());
  938. int start = Page.getStartOfAnyPage(pageNo, pageSize);
  939. sql = new StringBuffer(sql).append(" limit ").append(start).append(", ").append(pageSize).toString();
  940. Query query = new Query();
  941. try {
  942. query.parse(sql);
  943. }
  944. catch (QueryParseException e) {
  945. throw new UtilsException("parse sql error", e);
  946. }
  947. QueryResults qr = new QueryResults();
  948. try {
  949. qr = query.execute(datas);
  950. }
  951. catch (QueryExecutionException e) {
  952. throw new UtilsException("mem query error", e);
  953. }
  954. List<?> result = qr.getResults();
  955. Page page = null;
  956. if (result != null) {
  957. page = new Page(start, result.size(), datas.size(), pageSize, result);
  958. }
  959. else {
  960. page = new Page(0, 0, 0, pageSize, null);
  961. }
  962. return page;
  963. }
  964. /**
  965. * NULL值返回""
  966. */
  967. public static String checkNull(String value) {
  968. if (null == value) {
  969. return "";
  970. }
  971. else {
  972. return value;
  973. }
  974. }
  975. /**
  976. * <p>
  977. * Description:[数值空返回]
  978. * </p>
  979. *
  980. * @param value
  981. * @return
  982. */
  983. public static BigDecimal checkNum(Double value) {
  984. if (null == value) {
  985. return BigDecimal.ZERO;
  986. }
  987. else {
  988. return BigDecimal.valueOf(value);
  989. }
  990. }
  991. public static boolean isEmpty(Collection collection) {
  992. if (collection == null) {
  993. return true;
  994. }
  995. else {
  996. if (collection.size() == 0) {
  997. return true;
  998. }
  999. else {
  1000. return false;
  1001. }
  1002. }
  1003. }
  1004. /**
  1005. * <p>
  1006. * Description:[方法功能中文描述]
  1007. * </p>
  1008. *
  1009. * @param str
  1010. * @return
  1011. */
  1012. public static boolean isBiaoDian(String str) {
  1013. Pattern patPunc = Pattern.compile("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]");
  1014. boolean flag = patPunc.matcher(str).matches();
  1015. return flag;
  1016. }
  1017. }