LifeCenterFunction.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. package com.lemon.lifecenter.common;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.OutputStream;
  8. import java.io.OutputStreamWriter;
  9. import java.io.PrintWriter;
  10. import java.io.UnsupportedEncodingException;
  11. import java.net.HttpURLConnection;
  12. import java.net.MalformedURLException;
  13. import java.net.URL;
  14. import java.net.URLDecoder;
  15. import java.net.URLEncoder;
  16. import java.security.spec.AlgorithmParameterSpec;
  17. import java.text.DateFormat;
  18. import java.text.ParseException;
  19. import java.text.SimpleDateFormat;
  20. import java.util.ArrayList;
  21. import java.util.Base64;
  22. import java.util.Calendar;
  23. import java.util.Date;
  24. import java.util.HashMap;
  25. import java.util.Iterator;
  26. import java.util.Map;
  27. import java.util.Random;
  28. import java.util.UUID;
  29. import javax.crypto.Cipher;
  30. import javax.crypto.Mac;
  31. import javax.crypto.spec.IvParameterSpec;
  32. import javax.crypto.spec.SecretKeySpec;
  33. import javax.servlet.http.HttpServletRequest;
  34. import javax.servlet.http.HttpServletResponse;
  35. import org.json.JSONArray;
  36. import org.json.JSONException;
  37. import org.json.JSONObject;
  38. import org.slf4j.Logger;
  39. import org.slf4j.LoggerFactory;
  40. import com.lemon.lifecenter.dto.PatientDTO;
  41. public class LifeCenterFunction {
  42. public static String setURLEncode(String content, String lngType) throws UnsupportedEncodingException {
  43. return URLEncoder.encode(content, lngType);
  44. }
  45. public static String setURLDecode(String content, String lngType) throws UnsupportedEncodingException {
  46. return URLDecoder.decode(content, lngType);
  47. }
  48. public static String aesEncrypt(String encKey, byte[] iv, String paramInput) throws Exception {
  49. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  50. SecretKeySpec key = new SecretKeySpec(encKey.getBytes("UTF-8"), "AES");
  51. cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
  52. byte[] cipherText = cipher.doFinal(paramInput.getBytes("UTF-8"));
  53. return Base64.getEncoder().encodeToString(cipherText);
  54. }
  55. public static String aesDecrypt(String encKey, byte[] iv, String paramInput) throws Exception {
  56. byte[] textBytes = Base64.getDecoder().decode(paramInput);
  57. AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
  58. SecretKeySpec newKey = new SecretKeySpec(encKey.getBytes("UTF-8"), "AES");
  59. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  60. cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
  61. return new String(cipher.doFinal(textBytes), "UTF-8");
  62. }
  63. public static ArrayList<HashMap<String, String>> parseJSON(String jsonString) {
  64. ArrayList<HashMap<String, String>> rtn = new ArrayList<HashMap<String, String>>();
  65. try {
  66. JSONArray array = new JSONArray(jsonString);
  67. for (int i = 0; i < array.length(); i++) {
  68. HashMap<String, String> map = new HashMap<String, String>();
  69. JSONObject object = array.getJSONObject(i);
  70. Iterator<?> keys = object.keys();
  71. while (keys.hasNext()) {
  72. String key = (String) keys.next();
  73. String val = "";
  74. if (object.isNull(key)) {
  75. val = "";
  76. } else {
  77. if (object.get(key) instanceof Integer) {
  78. val = String.valueOf(object.getInt(key));
  79. } else if (object.get(key) instanceof Long) {
  80. val = String.valueOf(object.getLong(key));
  81. } else if (object.get(key) instanceof Double) {
  82. val = String.valueOf(object.getDouble(key));
  83. } else {
  84. val = object.getString(key).equals(null) ? "" : object.getString(key);
  85. }
  86. }
  87. map.put(key, val);
  88. }
  89. rtn.add(i, map);
  90. map = null;
  91. }
  92. } catch (JSONException e) {
  93. e.printStackTrace();
  94. }
  95. return rtn;
  96. }
  97. public static String getRandomUUID() {
  98. return UUID.randomUUID().toString().replaceAll("-", "");
  99. }
  100. public static String exportOnlyNumber(String input) {
  101. return input.replaceAll("[^0-9?!\\.]", "");
  102. }
  103. public static String getNow() {
  104. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  105. Date date = new Date();
  106. return dateFormat.format(date);
  107. }
  108. public static String getPrevDate( String ymd ) throws ParseException {
  109. DateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
  110. Date date = df.parse( ymd );
  111. Calendar cal = Calendar.getInstance();
  112. cal.setTime( date );
  113. cal.add( Calendar.DATE, -1 );
  114. return df.format( cal.getTime() );
  115. }
  116. public static String getNextDate( String ymd ) throws ParseException {
  117. DateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );
  118. Date date = df.parse( ymd );
  119. Calendar cal = Calendar.getInstance();
  120. cal.setTime( date );
  121. cal.add( Calendar.DATE, +1 );
  122. return df.format( cal.getTime() );
  123. }
  124. public static String getNow(String format) {
  125. DateFormat dateFormat = new SimpleDateFormat(format);
  126. Date date = new Date();
  127. return dateFormat.format(date);
  128. }
  129. public static long getNowUnixTimeStamp() {
  130. return System.currentTimeMillis() / 1000;
  131. }
  132. public static long setFormatUnixTimeStamp(String data) {
  133. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  134. long timeStamp = 0;
  135. try {
  136. long time = dateFormat.parse(data).getTime();
  137. timeStamp = time / 1000;
  138. } catch (ParseException e) {
  139. e.printStackTrace();
  140. }
  141. return timeStamp;
  142. }
  143. public static String setFormatDateFromUnixTimeStamp(Date data) {
  144. SimpleDateFormat transFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  145. return transFormat.format(data);
  146. }
  147. public static String getRandomNumber(int maxSize) {
  148. Random rand = new Random();
  149. String code = "";
  150. for (int i = 0; i < maxSize; i++) {
  151. code += rand.nextInt(9);
  152. }
  153. return code;
  154. }
  155. public static void scriptMessage(HttpServletResponse response, String script) {
  156. response.setContentType("text/html; charset=UTF-8");
  157. PrintWriter out;
  158. try {
  159. out = response.getWriter();
  160. out.println("<script>" + script + "</script>");
  161. out.flush();
  162. } catch (IOException e) {
  163. e.printStackTrace();
  164. }
  165. }
  166. public static String getRemoteAddr(HttpServletRequest request) {
  167. String ip = request.getHeader("X-Forwarded-For");
  168. if (ip == null) {
  169. ip = request.getHeader("Proxy-Client-IP");
  170. }
  171. if (ip == null) {
  172. ip = request.getHeader("WL-Proxy-Client-IP");
  173. }
  174. if (ip == null) {
  175. ip = request.getHeader("HTTP_CLIENT_IP");
  176. }
  177. if (ip == null) {
  178. ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  179. }
  180. if (ip == null) {
  181. ip = request.getRemoteAddr();
  182. }
  183. return ip;
  184. }
  185. public static String setPhoneFormat(String number) {
  186. StringBuilder sb = new StringBuilder(15);
  187. StringBuilder temp = new StringBuilder(number);
  188. int tempLength = temp.length();
  189. if (tempLength == 3) {
  190. sb.append(number);
  191. } else {
  192. while (tempLength < 10) {
  193. temp.insert(0, "0");
  194. }
  195. char[] chars = temp.toString().toCharArray();
  196. int size = chars.length;
  197. if (size < 11) {
  198. for (int i = 0; i < size; i++) {
  199. if (i == 3) {
  200. sb.append("-");
  201. } else if (i == 6) {
  202. sb.append("-");
  203. }
  204. sb.append(chars[i]);
  205. }
  206. } else {
  207. for (int i = 0; i < size; i++) {
  208. if (i == 3) {
  209. sb.append("-");
  210. } else if (i == 7) {
  211. sb.append("-");
  212. }
  213. sb.append(chars[i]);
  214. }
  215. }
  216. }
  217. return sb.toString();
  218. }
  219. public static String removeTag(String html) throws Exception {
  220. return html.replaceAll("<(/)?([a-zA-Z]*)(\\s[a-zA-Z]*=[^>]*)?(\\s)*(/)?>", "");
  221. }
  222. public static String getSalt() {
  223. String uniqId = "";
  224. Random randomGenerator = new Random();
  225. // length - set the unique Id length
  226. for (int length = 1; length <= 10; ++length) {
  227. int randomInt = randomGenerator.nextInt(10); // digit range from 0 - 9
  228. uniqId += randomInt + "";
  229. }
  230. return uniqId;
  231. }
  232. public static String getTimestamp() {
  233. long timestamp_long = System.currentTimeMillis() / 1000;
  234. String timestamp = Long.toString(timestamp_long);
  235. return timestamp;
  236. }
  237. private static final Logger logger = LoggerFactory.getLogger(LifeCenterFunction.class);
  238. public static String getSignature(String apiSecret, String salt, String timestamp) throws Exception {
  239. String signature = "";
  240. try {
  241. String temp = timestamp + salt;
  242. logger.error("temp -- > " + temp);
  243. SecretKeySpec keySpec = new SecretKeySpec(apiSecret.getBytes(), "HmacSHA256");
  244. Mac mac = Mac.getInstance("HmacSHA256");
  245. mac.init(keySpec);
  246. // 바이너리를 hex로 변환
  247. byte[] result = mac.doFinal(temp.getBytes());
  248. char[] hexArray = "0123456789ABCDEF".toCharArray();
  249. char[] hexChars = new char[result.length * 2];
  250. for (int i = 0; i < result.length; i++) {
  251. int positive = result[i] & 0xff;
  252. hexChars[i * 2] = hexArray[positive >>> 4];
  253. hexChars[i * 2 + 1] = hexArray[positive & 0x0F];
  254. }
  255. signature = new String(hexChars);
  256. } catch (Exception e) {
  257. e.printStackTrace();
  258. }
  259. return signature.toLowerCase();
  260. }
  261. public static String httpUrlConnection(String apiUrl, HashMap<String, String> hash) {
  262. String result = "";
  263. URL url;
  264. try {
  265. url = new URL(apiUrl);
  266. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  267. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  268. conn.setRequestProperty("Accept", "application/json");
  269. conn.setRequestMethod("POST"); // post방식 통신
  270. conn.setDoOutput(true); // 쓰기모드 지정
  271. conn.setDoInput(true); // 읽기모드 지정
  272. conn.setUseCaches(false); // 캐싱데이터를 받을지 안받을지
  273. conn.setDefaultUseCaches(false); // 캐싱데이터 디폴트 값 설정
  274. conn.setReadTimeout(10000); // 타임아웃 10초
  275. OutputStream os = conn.getOutputStream(); // 서버로 보내기 위한 출력 스트림
  276. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // UTF-8로 전송
  277. bw.write(getPostString(hash)); // 매개변수 전송
  278. bw.flush();
  279. bw.close();
  280. os.close();
  281. InputStream is = conn.getInputStream(); //데이타를 받기위 구멍을 열어준다
  282. StringBuilder builder = new StringBuilder(); //문자열을 담기 위한 객체
  283. BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); //문자열 셋 세팅
  284. String line;
  285. while ((line = reader.readLine()) != null) {
  286. builder.append(line+ "\n");
  287. }
  288. // logger.error("httpUrlConnection Result -- > " + builder.toString());
  289. result = builder.toString();
  290. conn.disconnect();
  291. } catch (MalformedURLException e) {
  292. // TODO Auto-generated catch block
  293. e.printStackTrace();
  294. } catch (IOException e) {
  295. // TODO Auto-generated catch block
  296. e.printStackTrace();
  297. }
  298. return result;
  299. }
  300. private static String getPostString(HashMap<String, String> map) {
  301. StringBuilder result = new StringBuilder();
  302. boolean first = true; // 첫 번째 매개변수 여부
  303. for (Map.Entry<String, String> entry : map.entrySet()) {
  304. if (first)
  305. first = false;
  306. else // 첫 번째 매개변수가 아닌 경우엔 앞에 &를 붙임
  307. result.append("&");
  308. try { // UTF-8로 주소에 키와 값을 붙임
  309. result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
  310. result.append("=");
  311. result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
  312. } catch (UnsupportedEncodingException ue) {
  313. ue.printStackTrace();
  314. } catch (Exception e) {
  315. e.printStackTrace();
  316. }
  317. }
  318. return result.toString();
  319. }
  320. public static String phone(String src) {
  321. if (src == null) {
  322. return "";
  323. }
  324. if (src.length() == 8) {
  325. return src.replaceFirst("^([0-9]{4})([0-9]{4})$", "$1-$2");
  326. } else if (src.length() == 12) {
  327. return src.replaceFirst("(^[0-9]{4})([0-9]{4})([0-9]{4})$", "$1-$2-$3");
  328. }
  329. return src.replaceFirst("(^02|[0-9]{3})([0-9]{3,4})([0-9]{4})$", "$1-$2-$3");
  330. }
  331. public static String getDisease(PatientDTO dto) {
  332. String highBloodPressureCheck = dto.getHighBloodPressureCheck().equals("Y") ? "고혈압" : "";
  333. String lowBloodPressureCheck = dto.getLowBloodPressureCheck().equals("Y") ? "저혈압" : "";
  334. String organTransplantCheck = dto.getOrganTransplantCheck().equals("Y") ? "장기이식(신장, 간 등)" : "";
  335. String diabetesCheck = dto.getDiabetesCheck().equals("Y") ? "당뇨" : "";
  336. String respiratoryDiseaseCheck = dto.getRespiratoryDiseaseCheck().equals("Y") ? "호흡기질환" : "";
  337. String immunologicalDiseaseCheck = dto.getImmunologicalDiseaseCheck().equals("Y") ? "면역질환(류마티스 등)" : "";
  338. String heartDisease = dto.getHeartDisease().equals("Y") ? "심장질환" : "";
  339. String liverDisease = dto.getLiverDisease().equals("Y") ? "간질환" : "";
  340. String operation = dto.getOperation().equals("Y") ? "수술(" + dto.getOperationContent() + ")" : "";
  341. String allergyCheck = dto.getAllergyCheck().equals("Y") ? "알레르기" : "";
  342. String kidneyDisease = dto.getKidneyDisease().equals("Y") ? "신장질환" : "";
  343. String cancerName = dto.getCancerName() == null ? "" : "(" + dto.getCancerName() + ")";
  344. String cancerCheck = dto.getCancerCheck().equals("Y") ? "암" + cancerName : "";
  345. String etcContent = dto.getEtcContentDisease() == null ? "" : dto.getEtcContentDisease();
  346. String ectCheckDisease = dto.getEtcCheckDisease().equals("Y") ? "기타(" + etcContent + ")" : "";
  347. ArrayList<String> disease = new ArrayList<String>();
  348. disease.add(highBloodPressureCheck);
  349. disease.add(lowBloodPressureCheck);
  350. disease.add(organTransplantCheck);
  351. disease.add(diabetesCheck);
  352. disease.add(respiratoryDiseaseCheck);
  353. disease.add(immunologicalDiseaseCheck);
  354. disease.add(heartDisease);
  355. disease.add(liverDisease);
  356. disease.add(operation);
  357. disease.add(allergyCheck);
  358. disease.add(kidneyDisease);
  359. disease.add(cancerCheck);
  360. disease.add(ectCheckDisease);
  361. String strDisease = "";
  362. for (int i = 0; i < disease.size(); i++) {
  363. String str = disease.get(i);
  364. if (!str.equals("")) {
  365. strDisease += str;
  366. strDisease += ", ";
  367. }
  368. }
  369. strDisease = strDisease.trim();
  370. if (!strDisease.equals("")) {
  371. strDisease = strDisease.substring(0, strDisease.length()-1);
  372. }
  373. return strDisease;
  374. }
  375. public static String getSymptom(PatientDTO dto) {
  376. String feverCheck = dto.getFeverCheck().equals("Y") ? "열감(열나는 느낌)" : "";
  377. String coughCheck = dto.getCoughCheck().equals("Y") ? "기침" : "";
  378. String colic = dto.getColic().equals("Y") ? "복통(배아픔)" : "";
  379. String coldFitCheck = dto.getColdFitCheck().equals("Y") ? "오한(추운 느낌)" : "";
  380. String sputumCheck = dto.getSputumCheck().equals("Y") ? "가래" : "";
  381. String ocinCheck = dto.getOcinCheck().equals("Y") ? "오심(구역질)" : "";
  382. String chestPain = dto.getChestPain().equals("Y") ? "흉통" : "";
  383. String noseCheck = dto.getNoseCheck().equals("Y") ? "콧물 또는 코 막힘" : "";
  384. String vomitingCheck = dto.getVomitingCheck().equals("Y") ? "구토" : "";
  385. String musclePainCheck = dto.getMusclePainCheck().equals("Y") ? "근육통(몸살)" : "";
  386. String soreThroatCheck = dto.getSoreThroatCheck().equals("Y") ? "인후통(목 아픔)" : "";
  387. String diarrheaCheck = dto.getDiarrheaCheck().equals("Y") ? "설사" : "";
  388. String headacheCheck = dto.getHeadacheCheck().equals("Y") ? "두통(머리아픔)" : "";
  389. String dyspneaCheck = dto.getDyspneaCheck().equals("Y") ? "호흡곤란(숨가쁨)" : "";
  390. String fatigueCheck = dto.getFatigueCheck().equals("Y") ? "권태감(피로감)" : "";
  391. String etcContent = dto.getEtcContentSymptom() == null ? "" : dto.getEtcContentSymptom();
  392. String ectCheckSymptom = dto.getEtcCheckSymptom().equals("Y") ? "기타(" + etcContent + ")" : "";
  393. String strSymptom = "";
  394. ArrayList<String> symptom = new ArrayList<String>();
  395. symptom.add(feverCheck);
  396. symptom.add(coughCheck);
  397. symptom.add(colic);
  398. symptom.add(coldFitCheck);
  399. symptom.add(sputumCheck);
  400. symptom.add(ocinCheck);
  401. symptom.add(chestPain);
  402. symptom.add(noseCheck);
  403. symptom.add(vomitingCheck);
  404. symptom.add(musclePainCheck);
  405. symptom.add(soreThroatCheck);
  406. symptom.add(diarrheaCheck);
  407. symptom.add(headacheCheck);
  408. symptom.add(dyspneaCheck);
  409. symptom.add(fatigueCheck);
  410. symptom.add(ectCheckSymptom);
  411. for (int i = 0; i < symptom.size(); i++) {
  412. String str = symptom.get(i);
  413. if (!str.equals("")) {
  414. strSymptom += str;
  415. strSymptom += ", ";
  416. }
  417. }
  418. strSymptom = strSymptom.trim();
  419. if (!strSymptom.equals("")) {
  420. strSymptom = strSymptom.substring(0, strSymptom.length() - 1);
  421. }
  422. return strSymptom;
  423. }
  424. }