CommonUtils.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. package com.telerobot.fs.utils;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.auth0.jwt.JWT;
  4. import com.auth0.jwt.algorithms.Algorithm;
  5. import com.auth0.jwt.interfaces.DecodedJWT;
  6. import com.auth0.jwt.interfaces.JWTVerifier;
  7. import com.telerobot.fs.config.SystemConfig;
  8. import com.telerobot.fs.entity.bo.InboundDetail;
  9. import com.telerobot.fs.entity.po.FunAsrResultEntity;
  10. import com.telerobot.fs.entity.po.HangupCause;
  11. import com.telerobot.fs.wshandle.MessageResponse;
  12. import com.telerobot.fs.wshandle.RespStatus;
  13. import link.thingscloud.freeswitch.esl.EslConnectionUtil;
  14. import link.thingscloud.freeswitch.esl.transport.message.EslMessage;
  15. import org.apache.commons.lang.StringUtils;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. import javax.servlet.http.HttpServletRequest;
  19. import javax.servlet.http.HttpServletResponse;
  20. import java.io.*;
  21. import java.math.BigDecimal;
  22. import java.math.BigInteger;
  23. import java.net.URLDecoder;
  24. import java.util.*;
  25. import java.util.concurrent.TimeUnit;
  26. import java.util.zip.ZipEntry;
  27. import java.util.zip.ZipOutputStream;
  28. /**
  29. * 工具类
  30. */
  31. public class CommonUtils<T> {
  32. private static final Logger logger = LoggerFactory.getLogger(CommonUtils.class);
  33. public static String execSystemCommand(String command) {
  34. Runtime runtime = Runtime.getRuntime();
  35. StringBuilder output = new StringBuilder();
  36. try {
  37. Process p = runtime.exec(command);
  38. // 启动另一个进程来执行命令
  39. BufferedInputStream in = new BufferedInputStream(p.getInputStream());
  40. BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
  41. String lineStr;
  42. //获得命令执行后在控制台的输出信息
  43. while ((lineStr = inBr.readLine()) != null) {
  44. output.append(lineStr).append("\n");
  45. }
  46. if (p.waitFor(11, TimeUnit.SECONDS)) {
  47. // p.exitValue()==0表示正常结束,1:非正常结束
  48. if (p.exitValue() == 1) {
  49. logger.error("exec system command error: {}", command);
  50. }
  51. }
  52. } catch (Throwable e) {
  53. logger.error("exec system command error: {} {} {}", command, e.toString(), CommonUtils.getStackTraceString(e.getStackTrace()));
  54. }
  55. return output.toString();
  56. }
  57. public static String getIpFromFullAddress(String clientFullAddr){
  58. String ip = clientFullAddr;
  59. if(clientFullAddr.contains(":")){
  60. ip = clientFullAddr.substring(0, clientFullAddr.indexOf(":")) ;
  61. };
  62. return ip.replace("/","");
  63. }
  64. public static void hangupCallSession(String uuid, String reason){
  65. EslConnectionUtil.sendExecuteCommand("hangup", reason, uuid);
  66. }
  67. public static void setHangupCauseDetail(InboundDetail callDetail, HangupCause cause, String details){
  68. JSONObject jsonObject = new JSONObject();
  69. jsonObject.put("code", cause.getCode());
  70. jsonObject.put("details", details);
  71. String json = jsonObject.toJSONString();
  72. if(callDetail.getOutboundPhoneInfo() != null) {
  73. if(com.telerobot.fs.utils.StringUtils.isNullOrEmpty(callDetail.getOutboundPhoneInfo().getHangupCause())) {
  74. callDetail.getOutboundPhoneInfo().setHangupCause(json);
  75. }
  76. }
  77. if(com.telerobot.fs.utils.StringUtils.isNullOrEmpty(callDetail.getHangupCause())) {
  78. callDetail.setHangupCause(json);
  79. }
  80. }
  81. public static void setHangupCauseDetail(InboundDetail callDetail, String cause, String details){
  82. JSONObject jsonObject = new JSONObject();
  83. jsonObject.put("code", cause);
  84. jsonObject.put("details", details);
  85. String json = jsonObject.toJSONString();
  86. if(callDetail.getOutboundPhoneInfo() != null) {
  87. callDetail.getOutboundPhoneInfo().setHangupCause(json);
  88. }
  89. callDetail.setHangupCause(json);
  90. }
  91. /**
  92. * 查询反向注册分机的 Contact(ip:port),默认先查 internal。
  93. */
  94. public static String getDynamicGatewayAddr(String extensionNumber, String traceId){
  95. return getDynamicGatewayAddr(extensionNumber, traceId, "internal");
  96. }
  97. /**
  98. * 按指定 sofia profile 查询已注册分机的 Contact(ip:port)。
  99. * 反向注册线路通常在 external;查不到时再回退 external / internal。
  100. */
  101. public static String getDynamicGatewayAddr(String extensionNumber, String traceId, String profileName){
  102. if(StringUtils.isBlank(extensionNumber)){
  103. logger.warn("{} 反向注册 authUsername 为空,无法查询 Contact", traceId);
  104. return "";
  105. }
  106. List<String> profiles = new ArrayList<String>(3);
  107. if(StringUtils.isNotBlank(profileName)){
  108. profiles.add(profileName.trim());
  109. }
  110. if(!profiles.contains("external")){
  111. profiles.add("external");
  112. }
  113. if(!profiles.contains("internal")){
  114. profiles.add("internal");
  115. }
  116. for(String profile : profiles){
  117. EslMessage response = EslConnectionUtil.sendSyncApiCommand(
  118. "sofia", "xmlstatus profile " + profile + " reg");
  119. if(response == null || response.getBodyLines() == null){
  120. logger.warn("{} 查询反向注册 Contact:profile={} 无响应,authUsername={}",
  121. traceId, profile, extensionNumber);
  122. continue;
  123. }
  124. StringBuilder xml = new StringBuilder();
  125. for(String s : response.getBodyLines()){
  126. xml.append(s);
  127. }
  128. logger.info("{} 查询反向注册 Contact:sofia xmlstatus profile {} reg,响应长度={}, authUsername={}",
  129. traceId, profile, xml.length(), extensionNumber);
  130. String contact = XmlUtils.parseFsOnlineUserListXml(xml.toString(), extensionNumber);
  131. if(StringUtils.isNotBlank(contact)){
  132. logger.info("{} 已找到反向注册 Contact:authUsername={}, profile={}, contact={}",
  133. traceId, extensionNumber, profile, contact);
  134. return contact;
  135. }
  136. logger.info("{} 当前 profile 未找到 Contact:profile={}, authUsername={}",
  137. traceId, profile, extensionNumber);
  138. }
  139. logger.warn("{} 反向注册 Contact 为空,authUsername={},已查 profiles={},不再 originate 空地址",
  140. traceId, extensionNumber, profiles);
  141. return "";
  142. }
  143. /**
  144. * Randomly obtain a outbound display number
  145. * @return
  146. */
  147. public static String getCallerNumberRandomly(String callers){
  148. if(callers.contains("\n")){
  149. String[] array = callers.split("\\n");
  150. int index = RandomUtils.getRandomByRange(0, array.length - 1);
  151. return array[index].trim();
  152. }else{
  153. return callers.trim();
  154. }
  155. }
  156. public static boolean safeCreateDirectory(String dir){
  157. File directory = new File(dir);
  158. if(!directory.exists()){
  159. synchronized (dir.intern()){
  160. if(!directory.exists()){
  161. return directory.mkdirs();
  162. }
  163. }
  164. }
  165. return true;
  166. }
  167. /**
  168. * 校验客户端 http 请求的 token
  169. * @param request
  170. * @return
  171. */
  172. public static String validateHttpHeaderToken(HttpServletRequest request, HttpServletResponse response) {
  173. String sysToken = SystemConfig.getValue("call-center-api-token", "");
  174. String token = request.getHeader("Authorization");
  175. // remove start string: "Bearer "
  176. if (!StringUtils.isEmpty(token) && token.length() > 7) {
  177. token = token.substring(7);
  178. }
  179. if (!sysToken.equals(token)) {
  180. response.setStatus(400);
  181. return "{ \"code\": 400, \"msg\" : \"validate token error.\" }";
  182. }
  183. return "";
  184. }
  185. public static Map<String, String> parseUrlQueryString(String queryString) throws UnsupportedEncodingException {
  186. Map<String, String> queryPairs = new HashMap<>(16);
  187. String[] pairs = queryString.split("&");
  188. for (String pair : pairs) {
  189. int idx = pair.indexOf("=");
  190. String key = URLDecoder.decode(pair.substring(0, idx), "UTF-8");
  191. String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : "";
  192. queryPairs.put(key, value);
  193. }
  194. return queryPairs;
  195. }
  196. private static final String FUN_ASR_MODE_ONLINE = "2pass-online";
  197. private static final String FUN_ASR_MODE_OFFLINE = "2pass-offline";
  198. public static FunAsrResultEntity parseFunAsrResponse(String msg){
  199. FunAsrResultEntity resultEntity = new FunAsrResultEntity();
  200. JSONObject jsonObject = JSONObject.parseObject(msg);
  201. boolean isFinal = jsonObject.getBoolean("is_final");
  202. resultEntity.setFinal_flag(isFinal);
  203. String mode = jsonObject.getString("mode");
  204. String text = jsonObject.getString("text");
  205. String vadType = "";
  206. if(!StringUtils.isEmpty(text)){
  207. if(mode.equals(FUN_ASR_MODE_ONLINE)) {
  208. vadType = "middle";
  209. }else if(mode.equals(FUN_ASR_MODE_OFFLINE)) {
  210. vadType = "vad";
  211. }
  212. resultEntity.setVad_type(vadType);
  213. resultEntity.setText(text);
  214. return resultEntity;
  215. }
  216. return null;
  217. }
  218. public static String joinTtsFiles(String traceId, String ttsFiles, boolean with_prefix, boolean checkExists){
  219. StringBuilder ttsFileUnion = new StringBuilder();
  220. if(!StringUtils.isEmpty(ttsFiles)){
  221. if(ttsFiles.contains(";")) {
  222. String[] fileArrs = ttsFiles.split(";");
  223. if(with_prefix) {
  224. ttsFileUnion.append("file_string://");
  225. }
  226. for (int i = 0; i <= fileArrs.length - 1; i++) {
  227. if (checkExists && !new File(fileArrs[i]).exists()) {
  228. logger.error("{} 录音文件不存在,跳过放音: {} ", traceId, fileArrs[i]);
  229. }else{
  230. if(i != fileArrs.length - 1){
  231. ttsFileUnion.append(fileArrs[i]).append("!");
  232. }else{
  233. ttsFileUnion.append(fileArrs[i]);
  234. }
  235. }
  236. }
  237. }else{
  238. // 只有一个wav文件;
  239. ttsFileUnion.append(ttsFiles);
  240. }
  241. }
  242. return ttsFileUnion.toString();
  243. }
  244. public static String getStackTraceString(StackTraceElement[] stackTraceElements){
  245. StringBuilder stringBuilder = new StringBuilder();
  246. for (int i = 0; i < stackTraceElements.length; i++) {
  247. stringBuilder.append("ClassName:");
  248. stringBuilder.append(stackTraceElements[i].getClassName());
  249. stringBuilder.append("\n FileName:");
  250. stringBuilder.append(stackTraceElements[i].getFileName());
  251. stringBuilder.append("\n LineNumber:");
  252. stringBuilder.append(stackTraceElements[i].getLineNumber());
  253. stringBuilder.append("\n MethodName:");
  254. stringBuilder.append(stackTraceElements[i].getMethodName());
  255. }
  256. return stringBuilder.toString();
  257. }
  258. /**
  259. * 已知的拨号错误
  260. */
  261. public static String[] KNOWN_DIAL_FAIL_CASE_TABLES = new String[]{
  262. "DESTINATION_OUT_OF_ORDER",
  263. "NO_ANSWER",
  264. "USER_BUSY",
  265. "NO_USER_RESPONSE",
  266. "RECOVERY_ON_TIMER_EXPIRE",
  267. "INCOMPATIBLE_DESTINATION"
  268. };
  269. /**
  270. * 检测拨号错误是否命中已知的错误类型
  271. * @param callResponseStr
  272. * @return 命中返回true,否则false
  273. */
  274. public static boolean checkTransferFailCase(String callResponseStr){
  275. boolean hitCase = false;
  276. for (String caseStr : KNOWN_DIAL_FAIL_CASE_TABLES) {
  277. if(callResponseStr.contains(caseStr)){
  278. hitCase = true;
  279. break;
  280. }
  281. }
  282. return hitCase;
  283. }
  284. /**
  285. * 解析外呼时的分机错误;
  286. * @param callResponseStr
  287. * @param extnum
  288. * @return
  289. */
  290. public static MessageResponse sendExtensionErrorInfo(String callResponseStr, String extnum) {
  291. MessageResponse response = null;
  292. if (callResponseStr.contains("USER_BUSY")) {
  293. response = (new MessageResponse(RespStatus.CALLER_BUSY, "呼叫失败,分机忙,请先挂断上一通电话。"));
  294. } else if (callResponseStr.contains("USER_NOT_REGISTERED")) {
  295. response = (new MessageResponse(RespStatus.CALLER_NOT_LOGIN, "分机没有登录,请打开软电话,确保软电话号码是" + extnum));
  296. } else if (callResponseStr.contains("SUBSCRIBER_ABSENT")) {
  297. response = (new MessageResponse(RespStatus.CALLER_NOT_LOGIN, "分机没有登录,请打开软电话,确保软电话号码是" + extnum));
  298. } else if (callResponseStr.contains("NO_USER_RESPONSE")) {
  299. response = (new MessageResponse(RespStatus.CALLER_RESPOND_TIMEOUT, "分机无响应,请重新打开电话或者刷新页面后重试。"));
  300. } else if (callResponseStr.contains("RECOVERY_ON_TIMER_EXPIRE")) {
  301. response = (new MessageResponse(RespStatus.CALLER_RESPOND_TIMEOUT, "操作超时,请检查分机是否已经登录,稍后重试。"));
  302. } else if (callResponseStr.contains("NO_ANSWER")) {
  303. response = (new MessageResponse(RespStatus.CALLER_RESPOND_TIMEOUT, "外呼超时"));
  304. } else if (callResponseStr.contains("INCOMPATIBLE_DESTINATION")) {
  305. response = (new MessageResponse(RespStatus.SERVER_ERROR_AUDIO_CODEC_NOT_MATCH, "外呼失败,可能是语音编码不匹配。 INCOMPATIBLE_DESTINATION"));
  306. } else if (callResponseStr.trim().length() != 0) {
  307. response = (new MessageResponse(RespStatus.SERVER_ERROR, "操作失败,请稍后重试,详情:" + callResponseStr));
  308. }
  309. return response;
  310. }
  311. public static Map<String,String> validateToken(String token, String traceId){
  312. try {
  313. //创建验证对象,这里使用的加密算法和密钥必须与生成TOKEN时的相同否则无法验证
  314. JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(
  315. SystemConfig.getValue("ws-server-auth-token-secret").trim()
  316. )).build();
  317. //验证JWT
  318. DecodedJWT decodedJwt = jwtVerifier.verify(token);
  319. Map<String,String> map = new HashMap<>(10);
  320. map.put("extnum", decodedJwt.getClaim("extnum").asString());
  321. map.put("opnum", decodedJwt.getClaim("opnum").asString());
  322. map.put("groupId", decodedJwt.getClaim("groupId").asString());
  323. map.put("skillLevel", decodedJwt.getClaim("skillLevel").asString());
  324. map.put("calleePrefix", decodedJwt.getClaim("calleePrefix").asString());
  325. map.put("callerNumber", decodedJwt.getClaim("callerNumber").asString());
  326. map.put("gatewayAddress", decodedJwt.getClaim("gatewayAddress").asString());
  327. map.put("projectId", decodedJwt.getClaim("projectId").asString());
  328. map.put("sipProfile", decodedJwt.getClaim("sipProfile").asString());
  329. return map;
  330. //获取JWT中的数据,注意数据类型一定要与添加进去的数据类型一致,否则取不到数据
  331. // System.out.println(decodedJwt.getExpiresAt());
  332. } catch (Throwable err) {
  333. logger.warn("{} token 校验失败: {}", traceId, err.toString());
  334. return null;
  335. }
  336. }
  337. /**
  338. * String Scramble Tool Class
  339. * @param input
  340. * @return
  341. */
  342. public static String shuffleString(String input) {
  343. // 将字符串转换为字符数组以便随机交换
  344. char[] chars = input.toCharArray();
  345. Random random = new Random();
  346. // Fisher-Yates洗牌算法
  347. for (int i = chars.length - 1; i > 0; i--) {
  348. int j = random.nextInt(i + 1); // 生成0到i之间的随机索引
  349. // 交换字符
  350. char temp = chars[i];
  351. chars[i] = chars[j];
  352. chars[j] = temp;
  353. }
  354. return new String(chars);
  355. }
  356. /**
  357. * 禁止jsp页面被客户端浏览器缓存
  358. * @param response
  359. */
  360. public static void setPageNoCache(HttpServletResponse response){
  361. response.setHeader("Pragma","no-cache");
  362. response.setHeader("Cache-Control","no-cache");
  363. response.setDateHeader("Expires", 0);
  364. }
  365. public static String hiddenPhoneNumber(String phone) {
  366. if (phone == null || phone.length() == 0) {
  367. return "";
  368. }
  369. if (phone.length() < 10) {
  370. return phone;
  371. }
  372. return phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
  373. }
  374. /**
  375. * 设置页面缓存为指定的分钟数后过期
  376. * @param response
  377. * @param minutes
  378. */
  379. public static void setPageCacheByTime(HttpServletResponse response, int minutes){
  380. Date d = new Date();
  381. String modDate = d.toGMTString();
  382. String expireDate = (new Date(d.getTime() + minutes * 60 * 1000)).toGMTString();
  383. response.setHeader("Last-Modified", modDate);
  384. response.setHeader("Expires", expireDate);
  385. response.setHeader("Cache-Control", "public");
  386. }
  387. /**
  388. * 过滤数组中重复的元素
  389. *
  390. * @param array 输入需要去重的数组
  391. * @return 返回去重后数组
  392. */
  393. public List<T> uniqueArray(T[] array) {
  394. if (array.length == 0) {
  395. return null;
  396. }
  397. List<T> list = new ArrayList<T>();;
  398. int length = array.length;
  399. for (int i = 0, len = length; i < len; i++) {
  400. if (!list.contains(array[i])) {
  401. list.add(array[i]);
  402. }
  403. }
  404. return list;
  405. }
  406. public static void main(String[] args) {
  407. }
  408. public static Boolean createZipFile(String sourceFile, String zipFilePath) {
  409. try{
  410. File file = new File(zipFilePath);
  411. if(!file.exists())
  412. file.createNewFile();
  413. String string= FileUtils.ReadFile(sourceFile, "utf-8");
  414. byte[] buffer =string.getBytes();
  415. FileOutputStream fOutputStream = new FileOutputStream(file);
  416. ZipOutputStream zoutput = new ZipOutputStream(fOutputStream);
  417. ZipEntry zEntry = new ZipEntry(new File(sourceFile).getName());
  418. zoutput.putNextEntry(zEntry);
  419. zoutput.write(buffer);
  420. zoutput.closeEntry();
  421. zoutput.close();
  422. return true;
  423. }
  424. catch(Throwable e){
  425. return false;
  426. }
  427. }
  428. /**
  429. * 格式化double类型为2位小数
  430. *
  431. * @return
  432. */
  433. public static Double formatDoubleWithTwo(Double f) {
  434. BigDecimal bg = new BigDecimal(f);
  435. return bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
  436. }
  437. /**把http请求参数转换为Map
  438. *
  439. * @param request
  440. * @return
  441. */
  442. public static Map<String, String> getHttpRequestHeaders(HttpServletRequest request) {
  443. Map<String, String> map = new HashMap<String, String>();
  444. @SuppressWarnings("rawtypes")
  445. Enumeration headerNames = request.getHeaderNames();
  446. while (headerNames.hasMoreElements()) {
  447. String key = (String) headerNames.nextElement();
  448. String value = request.getHeader(key);
  449. map.put(key, value);
  450. }
  451. return map;
  452. }
  453. public static Map<String, String> processRequestParameter(String data) {
  454. Map<String, String> params = new HashMap<String, String>();
  455. String[] keyValues;
  456. if (data.indexOf("&") != -1) {
  457. keyValues = data.split("&");
  458. } else {
  459. keyValues = new String[] { data };
  460. }
  461. for (String item : keyValues) {
  462. if (item.indexOf("=") != -1) {
  463. String[] tmp = item.split("=");
  464. if (tmp.length != 0) {
  465. if (tmp.length == 1) {
  466. params.put(tmp[0], "");
  467. }
  468. if (tmp.length == 2) {
  469. params.put(tmp[0], tmp[1]);
  470. }
  471. }
  472. }
  473. }
  474. return params;
  475. }
  476. /**
  477. * Integer转为long
  478. *
  479. * @author: easycallcenter365@126.com
  480. * @param data
  481. * @return
  482. * @date: 2016年12月17日 上午10:17:26
  483. */
  484. public static Long integer2long(Object data) {
  485. try {
  486. return ((Integer) (data == null ? new Integer(0) : data)).longValue();
  487. } catch (Exception e) {
  488. e.printStackTrace();
  489. return null;
  490. }
  491. }
  492. /**
  493. * BigInteger转为long
  494. *
  495. * @author: easycallcenter365@126.com
  496. * @param data
  497. * @return
  498. * @date: 2016年12月16日 上午10:50:31
  499. */
  500. public static Long biginteger2long(Object data) {
  501. try {
  502. return ((BigInteger) (data == null ? new BigInteger("0") : data)).longValue();
  503. } catch (Exception e) {
  504. e.printStackTrace();
  505. return null;
  506. }
  507. }
  508. /**
  509. * BigInteger转为int
  510. *
  511. * @author: easycallcenter365@126.com
  512. * @param data
  513. * @return
  514. * @date: 2016年12月19日 下午1:41:19
  515. */
  516. public static Integer biginteger2int(Object data) {
  517. try {
  518. return ((BigInteger) (data == null ? new BigInteger("0") : data)).intValue();
  519. } catch (Exception e) {
  520. e.printStackTrace();
  521. return null;
  522. }
  523. }
  524. /**
  525. * BigDecimal转为Double
  526. *
  527. * @author: easycallcenter365@126.com
  528. * @param data
  529. * @return
  530. * @date: 2016年12月16日 上午10:31:47
  531. */
  532. public static Double bigdecimal2double(Object data) {
  533. try {
  534. return ((BigDecimal) (data == null ? BigDecimal.valueOf(0.0) : data)).doubleValue();
  535. } catch (Exception e) {
  536. e.printStackTrace();
  537. return null;
  538. }
  539. }
  540. /**
  541. * BigDecimal转为long
  542. *
  543. * @author: easycallcenter365@126.com
  544. * @param data
  545. * @return
  546. * @date: 2016年12月17日 上午10:25:27
  547. */
  548. public static Long bigdecimal2long(Object data) {
  549. try {
  550. return ((BigDecimal) (data == null ? BigDecimal.valueOf(0.0) : data)).longValue();
  551. } catch (Exception e) {
  552. e.printStackTrace();
  553. return null;
  554. }
  555. }
  556. /**
  557. * BigDecimal转为int
  558. *
  559. * @author: easycallcenter365@126.com
  560. * @param data
  561. * @return
  562. * @date: 2016年12月19日 下午1:44:58
  563. */
  564. public static Integer bigdecimal2int(Object data) {
  565. try {
  566. return ((BigDecimal) (data == null ? BigDecimal.valueOf(0.0) : data)).intValue();
  567. } catch (Exception e) {
  568. e.printStackTrace();
  569. return null;
  570. }
  571. }
  572. /**
  573. * String转为Long
  574. *
  575. * @author: easycallcenter365@126.com
  576. * @param data
  577. * @return
  578. * @date: 2016年12月29日 下午4:11:58
  579. */
  580. public static Long string2long(String data) {
  581. try {
  582. return (data == null || "".equals(data)) ? null : Long.parseLong(data);
  583. } catch (Exception e) {
  584. e.printStackTrace();
  585. return null;
  586. }
  587. }
  588. /**
  589. * String转为Double
  590. *
  591. * @author: easycallcenter365@126.com
  592. * @param data
  593. * @return
  594. * @date: 2016年12月29日 下午4:11:58
  595. */
  596. public static Double string2double(String data) {
  597. try {
  598. return (data == null || "".equals(data)) ? 0.0 : Double.parseDouble(data);
  599. } catch (Exception e) {
  600. e.printStackTrace();
  601. return 0.0;
  602. }
  603. }
  604. public static boolean string2boolean(String data) {
  605. try {
  606. return (data == null || "".equals(data)) ? false : Boolean.valueOf(data);
  607. } catch (Exception e) {
  608. e.printStackTrace();
  609. return false;
  610. }
  611. }
  612. /**
  613. * 转为Date
  614. *
  615. * @author: easycallcenter365@126.com
  616. * @param data
  617. * @return
  618. * @date: 2017年2月4日 下午1:34:53
  619. */
  620. public static Date obj2date(Object data) {
  621. try {
  622. return (data == null || "".equals(data)) ? null : (Date) (data);
  623. } catch (Exception e) {
  624. e.printStackTrace();
  625. return null;
  626. }
  627. }
  628. /**
  629. * 转为int
  630. *
  631. * @author: easycallcenter365@126.com
  632. * @param data
  633. * @return
  634. * @date: 2017年2月8日 下午4:24:46
  635. */
  636. public static Integer obj2int(Object data, int defalutInt) {
  637. try {
  638. return (data == null || "".equals(data)) ? defalutInt : (Integer) (data);
  639. } catch (Exception e) {
  640. e.printStackTrace();
  641. return null;
  642. }
  643. }
  644. /**
  645. * 转为double
  646. *
  647. * @author: easycallcenter365@126.com
  648. * @param data
  649. * @return
  650. * @date: 2017年2月8日 下午4:24:46
  651. */
  652. public static Double obj2double(Object data, double defalutDouble) {
  653. try {
  654. return (data == null || "".equals(data)) ? defalutDouble : (Double) (data);
  655. } catch (Exception e) {
  656. e.printStackTrace();
  657. return null;
  658. }
  659. }
  660. /**
  661. * 转为string
  662. *
  663. * @author: easycallcenter365@126.com
  664. * @param data
  665. * @param defalutStr
  666. * @return
  667. * @date: 2017年2月8日 下午4:30:19
  668. */
  669. public static String obj2string(Object data, String defalutStr) {
  670. try {
  671. return (data == null || "".equals(data)) ? defalutStr : (String) (data);
  672. } catch (Exception e) {
  673. e.printStackTrace();
  674. return null;
  675. }
  676. }
  677. /**
  678. * 转为bigdecimal
  679. *
  680. * @author: easycallcenter365@126.com
  681. * @param value
  682. * @return
  683. * @date: 2017年2月26日 下午3:05:13
  684. */
  685. public static BigDecimal obj2bigdecimal(Object value) {
  686. BigDecimal ret = null;
  687. if (value != null) {
  688. if (value instanceof BigDecimal) {
  689. ret = (BigDecimal) value;
  690. } else if (value instanceof String) {
  691. ret = new BigDecimal((String) value);
  692. } else if (value instanceof BigInteger) {
  693. ret = new BigDecimal((BigInteger) value);
  694. } else if (value instanceof Number) {
  695. ret = BigDecimal.valueOf(((Number) value).doubleValue());
  696. } else {
  697. throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass()
  698. + " into a BigDecimal.");
  699. }
  700. }
  701. return ret;
  702. }
  703. /**
  704. * 获取挂断类型
  705. *
  706. * @author: easycallcenter365@126.com
  707. * @param typeId
  708. * @return
  709. * @date: 2016年12月4日 下午3:11:10
  710. */
  711. public static String getHangupType(Integer typeId) {
  712. if (null == typeId || typeId < 0) {
  713. return "";
  714. } else if (typeId == 0) {
  715. return "振铃挂断";
  716. } else if (typeId == 1) {
  717. return "坐席挂断";
  718. } else if (typeId == 2) {
  719. return "客户挂断";
  720. } else {
  721. return "";
  722. }
  723. }
  724. /**
  725. * 将秒转为时分秒
  726. *
  727. * @author: easycallcenter365@126.com
  728. * @param t
  729. * 单位秒
  730. * @return hh:mm:ss
  731. * @date: 2017年1月24日 上午9:42:46
  732. */
  733. public static String formatTime(Long t) {
  734. String str = "";
  735. if (null == t || t <= 0) {
  736. return "0:0:0";
  737. }
  738. str = t / 3600 + ":" + (t % 3600) / 60 + ":" + t % 60;
  739. return str;
  740. }
  741. /**
  742. * 将秒转为时分秒
  743. *
  744. * @author: easycallcenter365@126.com
  745. * @param t
  746. * 单位秒
  747. * @return hh:mm:ss
  748. * @date: 2017年1月24日 上午9:42:46
  749. */
  750. public static String formatTime2(Long t) {
  751. String str = "";
  752. if (null == t || t <= 0) {
  753. return "0:0:0";
  754. }
  755. str += t / 3600 + ":";
  756. if ((t % 3600) / 60 < 10) {
  757. str += "0" + (t % 3600) / 60 + ":";
  758. } else {
  759. str += (t % 3600) / 60 + ":";
  760. }
  761. if (t % 60 < 10) {
  762. str += "0" + t % 60;
  763. } else {
  764. str += t % 60;
  765. }
  766. return str;
  767. }
  768. /**
  769. * 电话号码隐藏中间部分
  770. *
  771. * @author: easycallcenter365@126.com
  772. * @param num
  773. * @return
  774. * @date: 2017年3月16日 下午2:43:53
  775. */
  776. public static String formatPhoneNum(String num) {
  777. int sub_start = 3;
  778. int sub_end = num.length() - 4;
  779. String hide_str = "";
  780. for (int i = 0; i < (sub_end - sub_start); i++) {
  781. hide_str += "*";
  782. }
  783. if (sub_start > sub_end) {
  784. return num;
  785. } else {
  786. return num.substring(0, sub_start) + hide_str + num.substring(sub_end, num.length());
  787. }
  788. }
  789. /**
  790. * 比较2个list是否相同(逗号隔开)
  791. *
  792. * @author: easycallcenter365@126.com
  793. * @time 下午2:35:10
  794. * @param list1
  795. * @param list2
  796. * @return
  797. */
  798. public static boolean equalsList(String list1, String list2) {
  799. if (null == list1 || "".equals(list1)) {
  800. return false;
  801. }
  802. if (null == list2 || "".equals(list2)) {
  803. return false;
  804. }
  805. if (list1.split(",").length != list2.split(",").length) {
  806. return false;
  807. }
  808. for (String obj : list1.split(",")) {
  809. if (list2.indexOf(obj) < 0) {
  810. return false;
  811. }
  812. }
  813. return true;
  814. }
  815. /**
  816. * 从HttpServletRequest参数中获取用户请求参数值
  817. *
  818. * @param request
  819. * @param key
  820. * @return
  821. */
  822. public static int getRequestParameterInt(HttpServletRequest request, String key) {
  823. String idValue = request.getParameter(key);
  824. if (idValue != null && idValue.trim() != "") {
  825. return Integer.valueOf(idValue);
  826. }
  827. return 0;
  828. }
  829. /**
  830. * 从HttpServletRequest参数中获取用户请求参数值
  831. *
  832. * @param request
  833. * @param key
  834. * @return
  835. */
  836. public static String getRequestParameterStr(HttpServletRequest request, String key) {
  837. String idValue = request.getParameter(key);
  838. if (idValue != null && idValue.trim() != "") {
  839. return String.valueOf(idValue);
  840. }
  841. return "";
  842. }
  843. /**
  844. * 格式化idList为List<Integer> 类型的对象;
  845. *
  846. * @param idListStr
  847. * 例如"521,352,523"
  848. * @return
  849. */
  850. public static List<Integer> parseIdList(String idListStr) {
  851. if (!StringUtils.isNotBlank(idListStr))
  852. return null;
  853. List<Integer> list = new ArrayList<Integer>(10);
  854. String[] array = idListStr.split(",");
  855. for (String ele : array) {
  856. list.add(Integer.valueOf(ele));
  857. }
  858. return list;
  859. }
  860. /**
  861. * uuid的正则表达式
  862. */
  863. public static final String uuidRegExpPattern = "[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}";
  864. public static String ListToString(List<?> objectList) {
  865. if(objectList.size() == 0) {
  866. return "";
  867. }
  868. return ListToString(objectList, true);
  869. }
  870. /**
  871. * ListToString,是否使用逗号分隔符
  872. ***/
  873. public static String ListToString(List<?> objectList, boolean useSpe) {
  874. StringBuilder sb = new StringBuilder("");
  875. for (Object ele : objectList) {
  876. sb.append(ele);
  877. if (useSpe) {
  878. sb.append(",");
  879. }
  880. }
  881. String result = sb.toString();
  882. if (useSpe) {
  883. result = result.substring(0, result.length() - 1);
  884. }
  885. return result;
  886. }
  887. /* 把计费周期转换为对应的秒数
  888. * @param period
  889. * @return
  890. */
  891. public static Long calcRentTime(Integer rentType){
  892. Long secs = 0L;
  893. switch(String.valueOf(rentType)){
  894. case "0":
  895. secs = 24L * 3600L; //天
  896. break;
  897. case "1":
  898. secs = 30L* 24L * 3600L; //月
  899. break;
  900. case "2":
  901. secs = 360L * 30L* 24L * 3600L; //年
  902. break;
  903. }
  904. return secs;
  905. }
  906. }