EdiBusinessUtils.java 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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.edi.context.EdiBusinessSessionContext;
  49. import com.behosoft.edi.model.vo.EdiUserVO;
  50. import com.behosoft.framework.web.dto.UploadFileDto;
  51. import com.behosoft.framework.web.exception.CommonException;
  52. import com.behosoft.framework.web.model.RecordBO;
  53. import com.behosoft.lis.BusinessConstants;
  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 EdiBusinessUtils extends CommonUtils {
  83. /**
  84. * LOGGER
  85. */
  86. private static final Log LOGGER = LogFactory.getLog(EdiBusinessUtils.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. EdiUserVO userVO = (EdiUserVO)userObject;
  103. loginName = userVO.getUserLoginName();
  104. }
  105. }
  106. if( EdiBusinessSessionContext.getLoginName()!=null){
  107. loginName = String.valueOf(EdiBusinessSessionContext.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", EdiBusinessSessionContext.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", EdiBusinessSessionContext.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 = EdiBusinessSessionContext.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 (value != null && value instanceof BigDecimal) {
  293. PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).doubleValue());
  294. }
  295. else if (value != null && value instanceof BigInteger) {
  296. PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).longValue());
  297. }
  298. else if (value != null && property.getType().getReturnedClass().equals(Short.class)) {
  299. PropertyUtils.setProperty(instance, fieldName, ((Integer) value).shortValue());
  300. }
  301. else if (value != null && value instanceof Date) {
  302. if (dateMap != null) {
  303. for (Map.Entry<String, String> entry : dateMap.entrySet()) {
  304. if (fieldName.equals(entry.getKey())) {
  305. JsonDateValueProcessor jsonDateValueProcessor = new JsonDateValueProcessor();
  306. if (entry.getValue() != null || !"".equals(entry.getValue())) {
  307. jsonDateValueProcessor.setDateFormat(new SimpleDateFormat(entry.getValue()));
  308. }
  309. value = jsonDateValueProcessor.processArrayValue((value), null);
  310. break;
  311. }
  312. }
  313. }
  314. PropertyUtils.setProperty(instance, fieldName, value);
  315. }
  316. else if (value != null
  317. && (value instanceof byte[] || value instanceof InputStream || value instanceof Blob)) {
  318. value = rs.getBlob(i);
  319. PropertyUtils.setProperty(instance, fieldName, value);
  320. }
  321. else {
  322. PropertyUtils.setProperty(instance, fieldName, value);
  323. }
  324. }
  325. catch (NoSuchMethodException e) {
  326. LOGGER.debug("No Such Field: " + fieldName + " For " + pojo.getName());
  327. }
  328. catch (Exception e) {
  329. throw new CommonException("set property value error : " + fieldName + " in class " + pojo.getName(), e);
  330. }
  331. }
  332. return instance;
  333. }
  334. /**
  335. * <p>
  336. * Description:文件上传
  337. * </p>
  338. *
  339. * @param request
  340. * @param requestFile request对象中file的name
  341. * @param rootPath the root path to save
  342. * @param uniqueKey
  343. * @param moduleKey
  344. * @throws Exception
  345. */
  346. public static UploadFileDto fileUpload(HttpServletRequest request, String requestFile, String rootPath,
  347. String moduleKey) {
  348. MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
  349. String[] filenames = multiWrapper.getFileNames(requestFile);
  350. String[] localPaths = multiWrapper.getFileNames(requestFile);
  351. if (multiWrapper.hasErrors()) {
  352. throw new CommonException("io.fileuploaderror");
  353. }
  354. if (filenames == null) {
  355. return null;
  356. }
  357. if (filenames.length == 0) {
  358. throw new CommonException("io.unsupportmethod");
  359. }
  360. File[] files = multiWrapper.getFiles(requestFile);
  361. String path = rootPath + "\\" + moduleKey + "\\";
  362. String[] filePaths = new String[files.length];
  363. String[] serverNames = new String[files.length];
  364. if (!FileExposeUtil.checkFileExist(path)) {
  365. // create folder
  366. FileExposeUtil.createFile(path);
  367. }
  368. for (int i = 0; i < files.length; i++) {
  369. try {
  370. serverNames[i] = System.currentTimeMillis() + filenames[i];
  371. filePaths[i] = path + serverNames[i];
  372. // 如果上传文件大小为0,则新建文件
  373. if (!files[i].exists()) {
  374. files[i] = File.createTempFile(files[i].getName(), "", files[i].getParentFile());
  375. }
  376. FileExposeUtil.copyFile(files[i], filePaths[i]);
  377. }
  378. catch (Exception e) {
  379. throw new CommonException("io.unsupportmethod");
  380. }
  381. }
  382. UploadFileDto dto = new UploadFileDto(localPaths, filePaths, filenames, serverNames);
  383. return dto;
  384. }
  385. /**
  386. * <p>
  387. * Description:文件上传
  388. * </p>
  389. *
  390. * @param inputStream 输入流
  391. * @param fileName 文件名称
  392. * @param rootPath the root path to save
  393. * @param moduleKey 子目录名称
  394. * @throws Exception
  395. */
  396. public static String fileUpload(InputStream inputStream, String fileName, String rootPath, String moduleKey) {
  397. if (fileName == null) {
  398. throw new CommonException("io.unsupportmethod");
  399. }
  400. String path = rootPath + "\\" + moduleKey + "\\";
  401. if (!FileExposeUtil.checkFileExist(path)) {
  402. // create folder
  403. FileExposeUtil.createFile(path);
  404. }
  405. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-ms");
  406. String serverName = formatter.format(new Date()) + "-" + fileName;
  407. try {
  408. FileExposeUtil.saveFile(inputStream, path, serverName, true);
  409. }
  410. catch (Exception e) {
  411. throw new CommonException("io.unsupportmethod");
  412. }
  413. return path + "\\" + serverName;
  414. }
  415. /**
  416. * <p>
  417. * Description:文件上传
  418. * </p>
  419. *
  420. * @param request
  421. * @param requestFile request对象中file的name
  422. * @param moduleKey 子目录
  423. * @throws Exception
  424. */
  425. public static UploadFileDto fileUploadForFTP(HttpServletRequest request, String requestFile, String moduleKey) {
  426. MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
  427. String[] filenames = multiWrapper.getFileNames(requestFile);
  428. String[] localPaths = multiWrapper.getFileNames(requestFile);
  429. if (multiWrapper.hasErrors()) {
  430. throw new CommonException("io.fileuploaderror");
  431. }
  432. if (filenames == null) {
  433. return null;
  434. }
  435. if (filenames.length == 0) {
  436. throw new CommonException("io.unsupportmethod");
  437. }
  438. if (moduleKey == null || org.apache.commons.lang.StringUtils.isWhitespace(moduleKey)) {
  439. moduleKey = "default";
  440. }
  441. else {
  442. moduleKey = moduleKey.trim();
  443. }
  444. File[] files = multiWrapper.getFiles(requestFile);
  445. String[] localFileNameArrs = new String[files.length];
  446. String[] filePaths = new String[files.length];
  447. String[] serverNames = new String[files.length];
  448. String path = "\\" + moduleKey + "\\";
  449. for (int i = 0; i < files.length; i++) {
  450. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-ms");
  451. String localFileName = formatter.format(new Date()) + "-" + filenames[i];
  452. Integer stamp = 0;
  453. while (FTPUtil.fileExist(localFileName)) {
  454. stamp += 1;
  455. localFileName =
  456. formatter.format(new Date()) + stamp.toString() + "-"
  457. + FileExposeUtil.getFileName(localFileName);
  458. }
  459. serverNames[i] = localFileName;
  460. filePaths[i] = path.replaceAll("\\\\", "/") + localFileName;
  461. InputStream is = null;
  462. try {
  463. // FileExposeUtil.copyFile(documentSourceAddress,
  464. // documentTargetAddress);
  465. is = new FileInputStream(files[i]);
  466. FTPUtil.uploadFile(is, path, localFileName);
  467. localFileNameArrs[i] = localFileName;
  468. }
  469. catch (Exception e) {
  470. e.printStackTrace();
  471. FTPUtil.dirFile(localFileName);
  472. return null;
  473. }
  474. finally {
  475. try {
  476. if (is != null) {
  477. is.close();
  478. }
  479. }
  480. catch (IOException e) {
  481. e.printStackTrace();
  482. }
  483. }
  484. }
  485. UploadFileDto dto = new UploadFileDto(localPaths, filePaths, filenames, serverNames);
  486. return dto;
  487. }
  488. /**
  489. * <p>
  490. * Description:文件上传
  491. * </p>
  492. *
  493. * @param request
  494. * @param requestFile request对象中file的name
  495. * @throws Exception
  496. */
  497. public static UploadFileDto fileUploadForFTP(HttpServletRequest request, String requestFile) {
  498. return fileUploadForFTP(request, requestFile, null);
  499. }
  500. /**
  501. * <p>
  502. * Description:内存查询
  503. * </p>
  504. *
  505. * @param <T> 实体泛型
  506. * @param entity 实体类型
  507. * @param datas 数据集
  508. * @param sql SQL语句,面向实体类型
  509. * @param params 参数
  510. * @return
  511. */
  512. public static <T> Collection<T> findBySQL(Class<T> entity, Collection<T> datas, String sql, Object... params) {
  513. if (CollectionUtils.isEmpty(datas)) {
  514. return null;
  515. }
  516. sql = sql.replaceAll("#entity", entity.getName());
  517. Query query = new Query();
  518. try {
  519. query.parse(sql);
  520. }
  521. catch (QueryParseException e) {
  522. throw new UtilsException("parse sql error", e);
  523. }
  524. if (params != null) {
  525. for (int i = 0; i < params.length; i++) {
  526. query.setVariable(i + 1, params[i]);
  527. }
  528. }
  529. QueryResults qr = null;
  530. try {
  531. qr = query.execute(datas);
  532. }
  533. catch (QueryExecutionException e) {
  534. throw new UtilsException("mem query error", e);
  535. }
  536. Collection<T> tempColl = qr.getResults();
  537. if (tempColl == null) {
  538. tempColl = new ArrayList<T>();
  539. }
  540. return tempColl;
  541. }
  542. /**
  543. * <p>
  544. * Description:内存分页查询
  545. * </p>
  546. *
  547. * @param <T> 实体泛型
  548. * @param entity 实体类型
  549. * @param datas 数据集
  550. * @param sql SQL语句,面向实体类型
  551. * @param pageNo 页号
  552. * @param pageSize 页面容量
  553. * @param params 参数
  554. * @return
  555. */
  556. public static <T> Page findForMapBySQLWithPage(Class<T> entity, Collection<T> datas, String sql, int pageNo,
  557. int pageSize, Map<String, Object> params) {
  558. if (CollectionUtils.isEmpty(datas)) {
  559. return null;
  560. }
  561. int start = Page.getStartOfAnyPage(pageNo);
  562. sql = sql.replaceAll("#entity", entity.getName());
  563. sql = new StringBuffer(sql).append(" limit ").append(start).append(", ").append(pageSize).toString();
  564. Query query = new Query();
  565. try {
  566. query.parse(sql);
  567. }
  568. catch (QueryParseException e) {
  569. throw new UtilsException("parse sql error", e);
  570. }
  571. if (params != null) {
  572. for (Map.Entry<String, Object> entry : params.entrySet()) {
  573. query.setVariable(entry.getKey(), entry.getValue());
  574. }
  575. }
  576. QueryResults qr = null;
  577. try {
  578. qr = query.execute(datas);
  579. }
  580. catch (QueryExecutionException e) {
  581. throw new UtilsException("mem query error", e);
  582. }
  583. List<?> result = qr.getResults();
  584. Page page = null;
  585. if (result != null) {
  586. page = new Page(start, result.size(), datas.size(), pageSize, result);
  587. }
  588. else {
  589. page = new Page(0, 0, 0, pageSize, null);
  590. }
  591. return page;
  592. }
  593. /**
  594. * <p>
  595. * Description:[通过文件名称获取文件类型]
  596. * </p>
  597. *
  598. * @param fileName 文件名称
  599. * @return
  600. */
  601. public static String getFileType(String fileName) {
  602. String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
  603. if (suffix.equals("xls") || suffix.equals("xlsx")) {
  604. return "excel";
  605. }
  606. else if (suffix.equals("doc") || suffix.equals("docx")) {
  607. return "word";
  608. }
  609. return null;
  610. }
  611. /**
  612. * <p>
  613. * Description:产生具有前缀和后缀的唯一字符串,中间14位
  614. * </p>
  615. *
  616. * @param prefix
  617. * @param suffix
  618. * @return
  619. */
  620. public static String createUniqueKey(String prefix, String suffix) {
  621. int randomNumber = (int) (Math.random() * 9);
  622. Calendar cal = Calendar.getInstance();
  623. StringBuffer key = new StringBuffer();
  624. String year = String.valueOf(cal.get(Calendar.YEAR)).substring(3);
  625. int month = cal.get(Calendar.MONTH) + 1;
  626. int date = cal.get(Calendar.DATE);
  627. int hour = cal.get(Calendar.HOUR_OF_DAY);
  628. int minute = cal.get(Calendar.MINUTE);
  629. int second = cal.get(Calendar.SECOND);
  630. int millisecond = cal.get(Calendar.MILLISECOND);
  631. // System.out.println(millisecond);
  632. key.append(prefix).append(year).append(month < 10 ? "0" + month : month).append(date < 10 ? "0" + date : date)
  633. .append(hour < 10 ? "0" + hour : hour).append(minute < 10 ? "0" + minute : minute).append(
  634. second < 10 ? "0" + second : second).append(millisecond < 10 ? "0" + millisecond : millisecond)
  635. .append(randomNumber).append(suffix);
  636. return key.toString();
  637. }
  638. /**
  639. * <p>
  640. * Description:[产生具有前缀和后缀的唯一字符串,中间14位+自定义提示表名]
  641. * </p>
  642. *
  643. * @param prefix
  644. * @param suffix
  645. * @param gridConfigBean
  646. * @return
  647. * @throws Exception
  648. */
  649. public static String createUniqueKey(String prefix, String suffix, String prefix_support) {
  650. String csvName = getI18N(prefix_support);
  651. if (csvName == null || csvName.trim().length() == 0) {
  652. throw new CommonException("The ModuleCode of the FormBean is Empty");
  653. }
  654. int randomNumber = (int) (Math.random() * 9);
  655. Calendar cal = Calendar.getInstance();
  656. StringBuffer key = new StringBuffer();
  657. String year = String.valueOf(cal.get(Calendar.YEAR)).substring(3);
  658. int month = cal.get(Calendar.MONTH) + 1;
  659. int date = cal.get(Calendar.DATE);
  660. int hour = cal.get(Calendar.HOUR_OF_DAY);
  661. int minute = cal.get(Calendar.MINUTE);
  662. int second = cal.get(Calendar.SECOND);
  663. int millisecond = cal.get(Calendar.MILLISECOND);
  664. // System.out.println(millisecond);
  665. key.append(prefix).append(year).append(month < 10 ? "0" + month : month).append(date < 10 ? "0" + date : date)
  666. .append(hour < 10 ? "0" + hour : hour).append(minute < 10 ? "0" + minute : minute).append(
  667. second < 10 ? "0" + second : second).append(millisecond < 10 ? "0" + millisecond : millisecond)
  668. .append(randomNumber).append("——" + csvName).append(suffix);
  669. return key.toString();
  670. }
  671. /**
  672. * <p>
  673. * Description:[方法功能中文描述]
  674. * </p>
  675. *
  676. * @param key
  677. * @return
  678. */
  679. private static String getI18N(String key) {
  680. if (key == null || "".equals(key)) {
  681. return "null";
  682. }
  683. String value = CommonUtils.getLocalizedMsg(key);
  684. if (value == null) {
  685. return key;
  686. }
  687. return value;
  688. }
  689. /**
  690. * <p>
  691. * Description: 对query bean中的日期表达式进行转化
  692. * </p>
  693. *
  694. * @param queryBean
  695. */
  696. public static void parseQueryDateExpression(QueryBean queryBean) {
  697. if (queryBean != null) {
  698. List<ConditionRule> conditionRules = queryBean.getConditionRules();
  699. if (conditionRules != null) {
  700. for (ConditionRule rule : conditionRules) {
  701. // according to the searchwidge.js
  702. if ("@DateExpression".equals(rule.getExpression())) {
  703. String field = rule.getField();
  704. formatDateConditionRule(rule, field);
  705. if (rule.getAppend() != null) {
  706. formatDateConditionRule(rule.getAppend(), field);
  707. }
  708. }
  709. }
  710. }
  711. }
  712. }
  713. /**
  714. * <p>
  715. * Description: 对日期类型的查询条件进行转化
  716. * </p>
  717. *
  718. * @param rule
  719. * @param field
  720. */
  721. public static void formatDateConditionRule(ConditionRule rule, String field) {
  722. Date date = Expression.excute(rule.getValue());
  723. if (date != null) {
  724. String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
  725. rule.setExpression("Date(${" + field + "}) " + rule.getOperator() + " '" + formatDate + "'");
  726. rule.setField(null);
  727. }
  728. else {
  729. String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(0));
  730. rule.setExpression("Date(${" + field + "}) < '" + formatDate + "'");
  731. rule.setField(null);
  732. }
  733. }
  734. /**
  735. * <p>
  736. * Description: 对query bean中的新关键字:当前用户(loginName)、空(is null is not null)进行转化
  737. * </p>
  738. *
  739. * @param queryBean
  740. */
  741. public static void parseQuerySpecialKeyWords(QueryBean queryBean) {
  742. if (queryBean != null) {
  743. List<ConditionRule> conditionRules = queryBean.getConditionRules();
  744. if (conditionRules != null) {
  745. for (ConditionRule rule : conditionRules) {
  746. String swValue = rule.getValue();
  747. if (swValue != null && swValue.startsWith("{") && swValue.endsWith("}")) {
  748. String swValueString = swValue.substring(1, swValue.length() - 1);
  749. swValueString = StringUtils.trimAllWhitespace(swValueString);
  750. if (swValueString.equalsIgnoreCase(getLocalizedMsg("common.msg.currentUser"))) {
  751. rule.setValue(EdiBusinessSessionContext.getLoginName());
  752. }
  753. else if (swValueString.equalsIgnoreCase(getLocalizedMsg("common.msg.null"))) {
  754. rule.setValue(null);
  755. if (rule.getOperator().equalsIgnoreCase("=")) {
  756. rule.setOperator("is");
  757. }
  758. else if (rule.getOperator().equalsIgnoreCase("<>")) {
  759. rule.setOperator("is not");
  760. }
  761. }
  762. }
  763. // }
  764. }
  765. }
  766. }
  767. }
  768. /**
  769. * <p>
  770. * Description:[方法功能中文描述]
  771. * </p>
  772. *
  773. * @param message
  774. * @return
  775. */
  776. public static Long getMenuId(String message) {
  777. if (message == null)
  778. return null;
  779. String localizedMsg = PropertiesManager.getProperty(message);
  780. return localizedMsg != null ? Long.valueOf(localizedMsg) : -1L;
  781. }
  782. /**
  783. * <p>
  784. * Description:[当前日期转换成时间戳]
  785. * </p>
  786. *
  787. * @param message
  788. * @return
  789. */
  790. public static Timestamp dateChangeToTimestamp(Date date) {
  791. Timestamp timeStamp = new Timestamp(new Date().getTime());
  792. return timeStamp;
  793. }
  794. /**
  795. * <p>
  796. * Description:[生成明细行号]
  797. * </p>
  798. *
  799. * @param detailCount 明细数
  800. * @return
  801. */
  802. public static String generateDetailLineNo(Integer detailCount) {
  803. if (detailCount == null) {
  804. detailCount = 0;
  805. }
  806. return String.valueOf((BusinessConstants.GENERATE_DETAIL_LINE_NO + ++detailCount)).substring(1);
  807. }
  808. /**
  809. * <p>
  810. * Description:[得到第二天的时间]
  811. * </p>
  812. *
  813. * @param date 日期对象
  814. * @param formateTemplete 日期格式
  815. * @return
  816. */
  817. public static Date getNextDate(Date date) {
  818. Calendar cal = Calendar.getInstance();
  819. cal.add(Calendar.DATE, 1);
  820. return cal.getTime();
  821. }
  822. /**
  823. * 根据entity Class 得到其中的注解元素 我们可以得到对象的name和数据库中的字段相对应
  824. *
  825. * @param entityClass
  826. * @return
  827. */
  828. public static Map<String, String> createEntityColumnMap(Class entityClass) {
  829. Map<String, String> entityColumnMap = new HashMap<String, String>();
  830. PropertyDescriptor[] propDescs = PropertyUtils.getPropertyDescriptors(entityClass);
  831. for (PropertyDescriptor propDesc : propDescs) {
  832. // 取得注释的column
  833. Column column = propDesc.getReadMethod().getAnnotation(Column.class);
  834. if (column != null) {
  835. String columnName = column.name().toUpperCase();
  836. String propertyName = propDesc.getName();
  837. entityColumnMap.put(propertyName, columnName);
  838. }
  839. }
  840. return entityColumnMap;
  841. }
  842. /**
  843. * <p>
  844. * Description:[通过queyBean生成JoSQL]
  845. * </p>
  846. *
  847. * @param query
  848. * @param excludeFields 忽略字段
  849. * @return
  850. */
  851. public static String generateJoSQL(QueryBean query, String[] excludeFields) {
  852. StringBuffer sql = new StringBuffer("select * from #entity where 1=1 ");
  853. if (query != null) {
  854. if (query.getConditionRules() != null) {
  855. out1: for (ConditionRule con : query.getConditionRules()) {
  856. String filed = con.getField();
  857. for (String exludeFiled : excludeFields) {
  858. if (filed.equalsIgnoreCase(exludeFiled)) {
  859. continue out1;
  860. }
  861. }
  862. String value = con.getValue();
  863. sql.append("and ").append(filed).append(" ").append(con.getOperator());
  864. if (con.getOperator().equals("like")) {
  865. sql.append(" '%").append(value).append("%'");
  866. }
  867. else {
  868. sql.append("\'").append(value).append("\'");
  869. }
  870. }
  871. }
  872. if (query.getExtraConditionRules() != null) {
  873. out2: for (ConditionRule con : query.getExtraConditionRules()) {
  874. String filed = con.getField();
  875. for (String exludeFiled : excludeFields) {
  876. if (filed.equalsIgnoreCase(exludeFiled)) {
  877. continue out2;
  878. }
  879. }
  880. String value = con.getValue();
  881. sql.append("and ").append(filed).append(" ").append(con.getOperator());
  882. if (con.getOperator().equals("like")) {
  883. sql.append(" '%").append(value).append("%'");
  884. }
  885. else {
  886. sql.append("\'").append(value).append("\'");
  887. }
  888. }
  889. }
  890. }
  891. return sql.toString();
  892. }
  893. /**
  894. * <p>
  895. * Description:内存分页查询
  896. * </p>
  897. *
  898. * @param <T> 实体泛型
  899. * @param entity 实体类型
  900. * @param datas 数据集
  901. * @param queryBean 查询实体
  902. * @param pageNo 页号
  903. * @param pageSize 页面容量
  904. * @param excludeFields 过滤参数
  905. * @return
  906. */
  907. public static <T> Page findByJoSQLWithPage(Class<T> entity, Collection<T> datas, QueryBean queryBean, int pageNo,
  908. int pageSize, String[] excludeFields) {
  909. if (CollectionUtils.isEmpty(datas)) {
  910. return null;
  911. }
  912. String sql = generateJoSQL(queryBean, excludeFields);
  913. sql = sql.replaceAll("#entity", entity.getName());
  914. int start = Page.getStartOfAnyPage(pageNo, pageSize);
  915. sql = new StringBuffer(sql).append(" limit ").append(start).append(", ").append(pageSize).toString();
  916. Query query = new Query();
  917. try {
  918. query.parse(sql);
  919. }
  920. catch (QueryParseException e) {
  921. throw new UtilsException("parse sql error", e);
  922. }
  923. QueryResults qr = new QueryResults();
  924. try {
  925. qr = query.execute(datas);
  926. }
  927. catch (QueryExecutionException e) {
  928. throw new UtilsException("mem query error", e);
  929. }
  930. List<?> result = qr.getResults();
  931. Page page = null;
  932. if (result != null) {
  933. page = new Page(start, result.size(), datas.size(), pageSize, result);
  934. }
  935. else {
  936. page = new Page(0, 0, 0, pageSize, null);
  937. }
  938. return page;
  939. }
  940. /**
  941. * NULL值返回""
  942. */
  943. public static String checkNull(String value) {
  944. if (null == value) {
  945. return "";
  946. }
  947. else {
  948. return value;
  949. }
  950. }
  951. /**
  952. * <p>
  953. * Description:[数值空返回]
  954. * </p>
  955. *
  956. * @param value
  957. * @return
  958. */
  959. public static BigDecimal checkNum(Double value) {
  960. if (null == value) {
  961. return BigDecimal.ZERO;
  962. }
  963. else {
  964. return BigDecimal.valueOf(value);
  965. }
  966. }
  967. public static boolean isEmpty(Collection collection) {
  968. if (collection == null) {
  969. return true;
  970. }
  971. else {
  972. if (collection.size() == 0) {
  973. return true;
  974. }
  975. else {
  976. return false;
  977. }
  978. }
  979. }
  980. /**
  981. * <p>
  982. * Description:[方法功能中文描述]
  983. * </p>
  984. *
  985. * @param str
  986. * @return
  987. */
  988. public static boolean isBiaoDian(String str) {
  989. Pattern patPunc = Pattern.compile("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]");
  990. boolean flag = patPunc.matcher(str).matches();
  991. return flag;
  992. }
  993. }