package com.pms.common.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.sql.Clob; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.ss.usermodel.Cell; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.springframework.context.ApplicationContext; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletWebRequest; import com.pms.common.bean.PersonBean; import jxl.BooleanFormulaCell; import jxl.CellType; import jxl.DateCell; import jxl.NumberCell; public class CommonUtils { private static final Log logger = LogFactory.getLog(CommonUtils.class); private static final ApplicationContext applicationContext = ContextLoaderListener.getCurrentWebApplicationContext(); public static final String DATE_FORMAT1 = "yyyy-MM-dd"; public static final String DATE_FORMAT2 = "yyyyMMdd"; public static final String DATE_FORMAT_YYYY = "yyyy"; public static final String DATE_FORMAT_YYYYMM = "yyyyMM"; public static final String DATE_FORMAT_YYYY_MM = "yyyy-MM"; public static final String DATE_FORMAT_MM = "MM"; public static Object getBean(String beanId) { return applicationContext.getBean(beanId); } public static Object getBeanType(String beanType) { return applicationContext.getType(beanType); } public static String getActiveProfie() { return applicationContext.getEnvironment().getActiveProfiles()[0]; } public static boolean isBlank(Object obj) { if (obj == null || "".equals(obj.toString().trim())) return true; return false; } public static boolean isNotBlank(Object obj) { return !isBlank(obj); } public static boolean isEmpty(Object obj) { if (obj == null) return true; return false; } public static boolean isNotEmpty(Object obj) { return !isEmpty(obj); } public static boolean isEmpty(Object[] obj) { if (obj == null || obj.length == 0) return true; return false; } /** * Map의 모든 value값 null이 비어있으면 true리턴 * * @param paramMap * @param defaultvalue */ public static boolean isEmptyMap(Map paramMap) { if (isEmpty(paramMap)) { return true; } Iterator it = paramMap.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); if (isEmpty(paramMap.get(key))) { return true; } else { return false; } } return true; } public static boolean isDateInvalidFormat(String in, String format) { SimpleDateFormat simpleDataFormat = new SimpleDateFormat(format); try { simpleDataFormat.parse(in); } catch (ParseException e) { return true; } return false; } public static String nvl(String sTarget, String sReplace) { if (sTarget == null || sTarget.isEmpty()) { return sReplace; } return sTarget; } /** * 특정 object 의 Null 처리 * null일경우는 ""를 리턴 * @param o * @return */ public static String checkNull(Object o) { if (o == null|| "null".equals(o) || "".equals(o)) return ""; else return o.toString().trim(); } public static String nullToEmpty(String str) { if( str == null || str.equals(null) || "null".equals(str) ){ str = ""; } return str; } /** * 주어진 문자로 주어진 자리수만큼 왼쪽부터 채우기 * * @param str * @param len * @param chr * @return * @throws Exception */ public static String lpad(String str, int len, String chr) throws Exception { try { if (str.length() > len) { str = str.substring(0, len); } else { while (str.length() < len) str = chr + str; } return str; } catch (Exception e) { throw e; } } /** * 특정 object 의 Null 처리 * null일경우는 defaultvalue를 리턴 * @param o * @return */ public static String checkNull(Object o, String defaultvalue) { if (o == null || "null".equals(o) || "".equals(o)) return defaultvalue; else return o.toString(); } /** * Map의 모든 value값 null체크처리 * * @param paramMap * @param defaultvalue */ public static void checkNullMap(Map paramMap) { if (isEmpty(paramMap)) { return; } Iterator it = paramMap.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); if (isEmpty(paramMap.get(key))) { paramMap.put(key, CommonUtils.checkNull(paramMap.get(key))); } } } /** * Map의 모든 value값 null체크처리 * * @param paramMap * @param defaultvalue */ public static void checkNullMap(Map paramMap, String defaultvalue) { if (isEmpty(paramMap)) { return; } Iterator it = paramMap.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); if (isEmpty(paramMap.get(key))) { if (isEmpty(defaultvalue)) { paramMap.put(key, CommonUtils.checkNull(paramMap.get(key))); } else { paramMap.put(key, CommonUtils.checkNull(paramMap.get(key), defaultvalue)); } } } } /** * Map의 모든 value값 null체크처리 * * @param paramMap * @param defaultvalue */ public static void checkNullMap(Map paramMap, String defaultvalue, String[] targetKeys) { if (isEmpty(paramMap) || isEmpty(targetKeys)) { return; } Iterator it = paramMap.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); if (isEmpty(paramMap.get(key))) { for (String targetKey : targetKeys) { if (targetKey.equals(targetKey)) { if (isEmpty(defaultvalue)) { paramMap.put(key, CommonUtils.checkNull(paramMap.get(key))); } else { paramMap.put(key, CommonUtils.checkNull(paramMap.get(key), defaultvalue)); } } } } } } /** * Map에 담겨있는 값이 전부 0이면 null을 반환 * 그게 아니라면 해당 map을 반환 * @param map * @return */ public static Map checkZeroMap(Map map){ if(map == null || map.isEmpty()) return null; boolean flag = true; Iterator it = map.keySet().iterator(); while(it.hasNext()){ String key = checkNull(it.next()); String value = checkNull(map.get(key)); if(!"0".equals(value)){ flag = false; } } if(flag) return null; else return map; } /** * List>의 모든 key값 대문자로 변경 * * @param paramMap * @param defaultvalue */ public static List> toUpperCaseMapKey(List> list) { List> resultList = new ArrayList>(); List> paramList = list; if (isEmpty(list) || list.size() < 1) { return list; } for (Map map : paramList) { Map rowMap = new HashMap(); Iterator it = map.keySet().iterator(); while (it.hasNext()) { String key = checkNull((String) it.next()); rowMap.put(key.toUpperCase(), map.get(key)); } resultList.add(rowMap); } return resultList; } /** * ArrayList>의 모든 key값 대문자로 변경 * 기존에 ArrayList> 형태로 작업된 부분이 많아 추가 * @param paramMap * @param defaultvalue */ public static ArrayList> toUpperCaseMapKey(ArrayList> list) { ArrayList> resultList = new ArrayList(); if (isEmpty(list) || list.size() < 1) { return resultList; } for (HashMap map : list) { HashMap rowMap = new HashMap(); Iterator it = map.keySet().iterator(); while (it.hasNext()) { String key = checkNull((String) it.next()); rowMap.put(key.toUpperCase(), map.get(key)); } resultList.add(rowMap); } return resultList; } /** * Map의 모든 key값 대문자로 변경 * * @param paramMap * @param defaultvalue */ public static Map toUpperCaseMapKey(Map dataMap) { Map resultMap = new HashMap(); Map paramMap = dataMap; if (isEmpty(dataMap) || null == dataMap) { return dataMap; } Iterator it = paramMap.keySet().iterator(); while (it.hasNext()) { String key = checkNull((String) it.next()); resultMap.put(key.toUpperCase(), paramMap.get(key)); } return resultMap; } /** * Map의 모든 key값 대문자로 변경 * * @param paramMap * @param defaultvalue */ public static HashMap toUpperCaseMapKey(HashMap dataMap) { HashMap resultMap = new HashMap(); if (isEmpty(dataMap) || null == dataMap) { return dataMap; } Iterator it = dataMap.keySet().iterator(); while (it.hasNext()) { String key = checkNull((String) it.next()); resultMap.put(key.toUpperCase(), dataMap.get(key)); } return resultMap; } /** * List>의 모든 key값 소문자로 변경 * * @param paramMap * @param defaultvalue */ public static List> toLowerCaseMapKey(List> list) { List> resultList = new ArrayList>(); if (isEmpty(list) || list.size() < 1) { return resultList; } for (Map map : list) { Map rowMap = new HashMap(); Iterator it = map.keySet().iterator(); while (it.hasNext()) { String key = checkNull((String) it.next()); rowMap.put(key.toLowerCase(), map.get(key)); } resultList.add(rowMap); } return resultList; } /** * Map에 없는키값 추가 * * @param paramMap * @param defaultvalue * @param targetKeys */ public static void putNotExistKeys(Map paramMap, String defaultvalue, String[] targetKeys) { if (isEmpty(paramMap) || isEmpty(targetKeys)) { return; } for (String targetKey : targetKeys) { if (!paramMap.containsKey(targetKey)) { if (isEmpty(defaultvalue)) { paramMap.put(targetKey, ""); } else { paramMap.put(targetKey, defaultvalue); } } } } /** * Map의 모든 property 복사 * * @param sourceMap * @param paramMap * @param onlyNotEmpty * - empty value도 복사할지 여부 * @param onlyStringValue * - string value만 복사할지 여부 */ public static void copyMap(Map targetMap, Map sourceMap, boolean onlyNotEmpty, boolean onlyStringValue) { if (isEmpty(sourceMap) || isEmpty(targetMap)) { return; } Iterator it = sourceMap.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); Object value = sourceMap.get(key); // if (onlyStringValue) { // System.out.println("copyMap ---" + String.valueOf((value instanceof String)) + ":" + String.valueOf((value instanceof BigDecimal)) + ":" + key + ":" + value + ":" + value.getClass()); if (value instanceof String) { if (onlyNotEmpty) { if (!org.springframework.util.StringUtils.isEmpty(value)) { targetMap.put(key, value); } } else { targetMap.put(key, value); } } else if (value instanceof Integer) { if (onlyNotEmpty) { if (((Integer) value) != 0) { targetMap.put(key, value); } } else { targetMap.put(key, value); } } else if (value instanceof BigDecimal) { if (onlyNotEmpty) { if ((((BigDecimal) value).compareTo(BigDecimal.ZERO)) != 0) { targetMap.put(key, value); } } else { targetMap.put(key, value); } }else{ if (onlyNotEmpty) { if (!isEmpty(value)) { targetMap.put(key, value); } } else { targetMap.put(key, value); } } }// end of while } public static int getRandNum(int max, int min) { return (int) Math.floor(Math.random() * (max - min + 1) + min); } public static Map ConverObjectToMap(Object obj) { try { Field[] fields = obj.getClass().getDeclaredFields(); Map resultMap = new HashMap(); for (int i = 0; i <= fields.length - 1; i++) { fields[i].setAccessible(true); resultMap.put(fields[i].getName(), fields[i].get(obj)); } return resultMap; } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } public static String getDateQuarter(){ String today = CommonUtils.getDateToday(DATE_FORMAT_MM); int quarter = (Integer.parseInt(today)-1)/3+1; return quarter+""; } public static String getDateQuarter(String today){ int quarter = (Integer.parseInt(today)-1)/3+1; return quarter+""; } public static String getDateHalf(){ String today = CommonUtils.getDateToday(DATE_FORMAT_MM); int quarter = (Integer.parseInt(today)-1)/6+1; return quarter+""; } public static String getDateAddMonth(int addMonth, String format){ String yyyyMMdd = getDateToday(DATE_FORMAT2); String year = yyyyMMdd.substring(0,4); String month = yyyyMMdd.substring(4,6); String day = yyyyMMdd.substring(6,8); Calendar cal = Calendar.getInstance(); cal.set(Integer.parseInt(year),Integer.parseInt(month)-1 + addMonth, Integer.parseInt(day)); Date date = cal.getTime(); SimpleDateFormat simpleFomat = new SimpleDateFormat(format); return simpleFomat.format(date); } public static String getDateAddMonth(String yyyyMMdd, int addMonth, String format){ String year = yyyyMMdd.substring(0,4); String month = yyyyMMdd.substring(4,6); String day = yyyyMMdd.substring(6,8); Calendar cal = Calendar.getInstance(); cal.set(Integer.parseInt(year),Integer.parseInt(month)-1 + addMonth, Integer.parseInt(day)); Date date = cal.getTime(); SimpleDateFormat simpleFomat = new SimpleDateFormat(format); return simpleFomat.format(date); } public static String getDateToday(String format){ Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); SimpleDateFormat simpleFomat = new SimpleDateFormat(format); return simpleFomat.format(date); } public static String getFirstDateOfMonth(String yyyyMMdd) { String year = yyyyMMdd.substring(0,4); String month = yyyyMMdd.substring(4,6); String date = "01";//yyyyMMdd.substring(6,8); String lastDay = year+month+date; return lastDay; } public static String getLastDateOfMonth(String yyyyMMdd) { String year = yyyyMMdd.substring(0,4); String month = yyyyMMdd.substring(4,6); Calendar cal = Calendar.getInstance(); cal.set(Integer.parseInt(year),Integer.parseInt(month)-1,1); String lastDay = year+month+Integer.toString(cal.getActualMaximum(Calendar.DAY_OF_MONTH)); return lastDay; } public static String getDateTime(Date date, String format) { SimpleDateFormat simpleFomat = new SimpleDateFormat(format); return simpleFomat.format(date); } public static String getDateFormat(String yyyyMMdd, String format) throws Exception { String year = yyyyMMdd.substring(0,4); String month = yyyyMMdd.substring(4,6); String day = yyyyMMdd.substring(6,8); Calendar cal = Calendar.getInstance(); cal.set(Integer.parseInt(year),Integer.parseInt(month)-1, Integer.parseInt(day)); Date date = cal.getTime(); SimpleDateFormat simpleFomat = new SimpleDateFormat(format); return simpleFomat.format(date); } public static Date getDate(String date, String format) throws Exception { SimpleDateFormat simpleFomat = new SimpleDateFormat(format); return simpleFomat.parse(date); } public static String getDiffTime(Date fromDate, Date toDate) { return (isNotEmpty(fromDate) && isNotEmpty(fromDate)) ? String.valueOf(toDate.getTime() - fromDate.getTime()) : "-1"; } public static HttpServletRequest getRequest() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } public static HttpServletResponse getResponse() { return ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse(); } /*public static boolean isAdmin() { boolean isAdmin = false; PersonBean personBean = getUserObject(); Map accessRoleMap = personBean.getAccessRoleMap(); if (logger.isDebugEnabled()) { logger.debug(" >>> isAdmin : " + accessRoleMap); } isAdmin = accessRoleMap.containsKey(Constants.SYSTEM_ADMINISTRATOR); return isAdmin; }*/ /** * 권한보유여부 체크 * * @param roleNm * @return */ /*public static boolean haveRole(String roleNm) { boolean haveRole = false; PersonBean personBean = getUserObject(); Map accessRoleMap = personBean.getAccessRoleMap(); if (logger.isDebugEnabled()) { logger.debug(" >>> haveRole : " + accessRoleMap); } haveRole = accessRoleMap.containsKey(roleNm); return haveRole; }*/ /** * paramMap에 부서코드(timsItemGroup) 셋팅 * * @param request * @param paramMap * @throws Exception */ /*public static void setMyDeptTimsItemGroup(ModelMap modelMap, Map paramMap, String adminKey, String deptKey) throws Exception { if (isAdmin()) { modelMap.put(checkNull(adminKey, "isAdmin"), true); } else { // 권한처리(같은부서) Map roleMap = getUserObject().getAccessRoleMap(); // Map timsItemGroupMap = (Map)roleMap.get("timsItemGroup_재료연구"); // System.out.println("roleMaproleMap:" + roleMap); // System.out.println("roleMaproleMap:" + roleMap.get("timsItemGroup_재료연구")); // System.out.println("roleMaproleMap:" + timsItemGroupMap.get("ROLEOBJID")); String teamItemGroupId = ""; String teamItemGroupName = ""; for (Iterator itr = roleMap.keySet().iterator(); itr.hasNext();) { String key = (String) itr.next(); if (key.startsWith("timsItemGroup")) { Map timsItemGroupMap = (Map) roleMap.get(key); teamItemGroupId = (String) timsItemGroupMap.get("ROLEOBJID"); teamItemGroupName = (String) timsItemGroupMap.get("ROLEDESC"); break; } } if (logger.isDebugEnabled()) { logger.debug(" >>> teamItemGroupIdteamItemGroupId : " + teamItemGroupId); } // paramMap.put(CommonUtils.checkNull(deptKey, "deptId"), CommonUtils.getUserObject().getDeptId()); paramMap.put(checkNull(deptKey, "deptId"), teamItemGroupId); } }*/ /** * role 확인후 modelMap에 roleNm으로 권한셋팅 * * @param modelMap * @param roleNm * @return */ /*public static Boolean checkRole(String roleNm) { Boolean haveRole = CommonUtils.haveRole(roleNm); haveRole = CommonUtils.isAdmin() ? true : haveRole; return haveRole; }*/ /** * role 확인후 modelMap에 roleNm으로 권한셋팅 * * @param modelMap * @param roleNm * @return */ /*public static Boolean checkAndSetRole(ModelMap modelMap, String roleNm) { Boolean haveRole = CommonUtils.haveRole(roleNm); haveRole = CommonUtils.isAdmin() ? true : haveRole; if (isNotEmpty(modelMap)) modelMap.addAttribute(roleNm, haveRole); return haveRole; }*/ /** * 관리자여부 확인후 modelMap에 roleNm으로 권한셋팅 * * @param modelMap * @param roleNm * @param idList * @return */ /*public static Boolean checkAndSetRoleManager(ModelMap modelMap, String roleNm, List idList) { Boolean haveRole = false; PersonBean personBean = getUserObject(); String loginUserId = checkNull(personBean.getUserId()); for (String managerId : idList) { if (logger.isDebugEnabled()) { logger.debug("haveRolehaveRole:" + managerId + " : " + loginUserId); } if (!StringUtils.isEmpty(loginUserId) && !StringUtils.isEmpty(managerId) && managerId.indexOf(loginUserId) > -1) { // 관리자에 속하면 권한 부여 haveRole = true; break; } } if (logger.isDebugEnabled()) { logger.debug("haveRolehaveRole:" + haveRole); } haveRole = CommonUtils.isAdmin() ? true : haveRole; modelMap.addAttribute(roleNm, haveRole); return haveRole; }*/ // Session 에서 User Object 리턴 /*public static PersonBean getUserObject() { return (PersonBean) (getRequest().getSession(false).getAttribute(Constants.USER_PERSON_BEAN)); }*/ /*@SuppressWarnings("unchecked") public static String getPersonRoleString() { String result = ""; Map roleMap = getUserObject().getAccessRoleMap(); for(Entry role : roleMap.entrySet()) { Map valueMap = (Map) role.getValue(); if(valueMap.containsKey("ROLEOBJID")) { String value = CommonUtils.checkNull(valueMap.get("ROLEOBJID")); result = result + ",'" + value.substring(0, value.indexOf(".")) + "'"; } } return result.replaceFirst(",", ""); }*/ public static String getRequestParamString() { StringBuilder params = new StringBuilder(); Iterator it = getRequest().getParameterMap().keySet().iterator(); while (it.hasNext()) { String key = it.next(); params.append("\n " + key + "=" + Arrays.toString((String[]) getRequest().getParameterMap().get(key))); } return params.toString().replaceFirst("&", ""); } public static String htmlTagRemove(String contents) { if (StringUtils.isNotBlank(contents)) { contents = contents.replaceAll("<(/)?([a-zA-Z0-9]*)(\\s[a-zA-Z0-9]*=[^>]*)?(\\s)*(/)?>", ""); contents = contents.replaceAll("\r|\n|&|#9702;", ""); contents = contents.replaceAll(" ", " "); } return contents; } public static String HtmlTagRecovery(String contents) { if (StringUtils.isNotBlank(contents)) { if (logger.isDebugEnabled()) { logger.debug("origin string : " + contents); } contents = contents.replaceAll("<", "<"); contents = contents.replaceAll(">", ">"); contents = contents.replaceAll("(", "\\("); contents = contents.replaceAll(")", "\\)"); contents = contents.replaceAll(""", "\""); contents = contents.replaceAll("'", "'"); contents = contents.replaceAll("/", "\\/"); contents = contents.replaceAll("&", "&"); contents = contents.replaceAll("#", "#"); contents = contents.replaceAll("\n", "
"); if (logger.isDebugEnabled()) { logger.debug("modify string : " + contents); } } return contents; } public static void copyProperty(Object toObj, Map fromMap) throws Exception { for (Map.Entry entry : fromMap.entrySet()) { Object value = entry.getValue(); if (CommonUtils.isNotEmpty(value)) { System.out.println(entry.getKey() + " = "+value); System.out.println("PropertyUtils.isWriteable(toObj, entry.getKey()) = "+PropertyUtils.isWriteable(toObj, entry.getKey())); if (PropertyUtils.isWriteable(toObj, entry.getKey())) { BeanUtils.copyProperty(toObj, entry.getKey(), value); } } } } /** * 트리를 위한 컨버터 * @param resultList => 트리를 만들어줄 리스트 * @param rootNm => 루트 키 컬럼 * @param rootVal -> 루트 값 * @param key => 키 컬럼 * @param upkey => 부모키 컬럼 * @return */ public static ArrayList> convertTree_list(ArrayList> resultList, String rootNm, String rootVal, String key, String upkey) throws Exception { // List 생성 ArrayList> treeList = new ArrayList>(); try { //조회결과가 있으면 if (resultList != null && resultList.size() > 0) { // Map 생성 Map listItem = null; // 조회결과 만큼 반복 for (int g = 0; g < resultList.size(); g++) { // Map에 g번째 Row 넣기 listItem = resultList.get(g); // 1 Level Node if (listItem.get(rootNm).equals(rootVal)) { listItem.put("expanded", "true"); listItem.put("classes", "important"); // g번째 Map에 children 컬럼 생성 listItem.put("children", new ArrayList>()); // Tree에 g번째 Map 추가 treeList.add(listItem); } // Others Node else { new InnerClass_list() { // 현재까지 만들어진 Tree, public void getParentNode(ArrayList> treeList, Map listItem, String key, String upkey) { // 현재까지 만들어진 Tree 만큼 반복 for (int t = 0; t < treeList.size(); t++) { // Map에 t번째 Tree Row 넣기 Map treeItem = (Map) treeList.get(t); // g번째 List가 t번째 Tree 자식이면 if (treeItem.get(key).equals(listItem.get(upkey))) { // Map에 g번째 List 넣기 Map view = listItem; // g번째 Map에 children 컬럼 생성 view.put("children", new ArrayList>()); view.put("expanded", true); // g번째 Map을 Tree의 자식으로 추가 ((ArrayList>) treeItem.get("children")).add(view); break; } // t번째 자식이 아니면 t번째 자식의 자식일수 있음 else { // t번째 Tree 자식이 존재하면 if (((ArrayList>) treeItem.get("children")).size() > 0) { getParentNode((ArrayList>) treeItem.get("children"), listItem, key, upkey); } } }//for문종료 } // getParentNode 종료 }.getParentNode(treeList, listItem, key, upkey); } } } } catch (Exception e) { e.printStackTrace(); } return treeList; } public interface InnerClass_list { public void getParentNode(ArrayList> treeList, Map listItem, String key, String upkey); } /** * Map을 요소로 가지는 List의 정렬 * * @param arrayList - ArrayList contaions hashmap * @param key - key of map * @param direction - direction of sorting * @param type - data type */ public static void sortMapList(List> mapList, String key, String direction, String type) { Map hashMap = new HashMap(); hashMap.put("name", key); if (direction == null) { hashMap.put("dir", "ascending"); } else { hashMap.put("dir", direction.toLowerCase()); } if (type == null) { hashMap.put("type", "string"); } else { hashMap.put("type", type.toLowerCase()); } List> keyList = new ArrayList>(); keyList.add(hashMap); Collections.sort(mapList, new MapComparator(keyList)); } public static Locale getLocale() { return LocaleContextHolder.getLocale(); } public static boolean hasHangul(String str) { String digitRegEx = ".*[ㄱ-ㅎㅏ-ㅣ가-힣]+.*"; Pattern pattern = Pattern.compile(digitRegEx); Matcher matcher = pattern.matcher(str); return matcher.find(); } public static ArrayList getParameters(HttpServletRequest request, String paramName){ ArrayList result = new ArrayList(); try{ String[] paramObject = request.getParameterValues(paramName); if(paramObject != null){ for(int i=0; i< paramObject.length; i++){ result.add(paramObject[i]); } } }catch(Exception ex){ result.add(request.getParameter(paramName)); } return result; } public static String getExcelData(Cell cell) { String cellValue = ""; if (cell != null) { switch (cell.getCellType()) { // cell에서 가져온값이 String값일경우. case HSSFCell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_FORMULA: cellValue = cell.getStringCellValue(); break; // cell에서 가져온값이 number값일경우. case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); cellValue = formatter.format(cell.getDateCellValue()); } else { cellValue = Integer.toString((int) cell.getNumericCellValue()); } break; // cell에서 가져온값이 공백일경우. case HSSFCell.CELL_TYPE_BLANK: cellValue = ""; break; // cell에서 가져온값이 boolean형일 경우. case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = Boolean.toString(cell.getBooleanCellValue()); break; // cell에서 가져온값이 Error값일 경우 case HSSFCell.CELL_TYPE_ERROR: cellValue = Byte.toString(cell.getErrorCellValue()); break; default: } } else { cellValue = ""; } return cellValue; } public static String getJxlExcelData(jxl.Cell cell) { String cellValue = ""; if (cell != null) { //System.out.println("cell.getType() ="+cell.getType()); if(cell.getType() == CellType.BOOLEAN || cell.getType() == CellType.BOOLEAN_FORMULA){ BooleanFormulaCell boolFormulaCell = (BooleanFormulaCell) cell; boolean value = boolFormulaCell.getValue(); cellValue = String.valueOf(value).trim(); }else if(cell.getType() == CellType.DATE || cell.getType() == CellType.DATE_FORMULA){ DateCell dateCell = (DateCell) cell; Date date = dateCell.getDate(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); cellValue = formatter.format(date); }else if (cell.getType() == CellType.NUMBER) { NumberCell numCell = (NumberCell) cell; //double num = numCell.getValue(); int num = Integer.parseInt(String.valueOf(Math.round(numCell.getValue()))); cellValue = String.valueOf(num).trim(); }else{ cellValue = CommonUtils.checkNull(cell.getContents()).trim(); } } else { cellValue = ""; } return cellValue; } public static ArrayList getJsonArray(List sourceList){ return getJsonArray((ArrayList)sourceList); } /** * ArrayList 의 List를 받아 JSON 형태의 ArrayList를 반환한다. * @param sourceList * @return */ public static ArrayList getJsonArray(ArrayList sourceList){ ArrayList resultList = new ArrayList(); if(sourceList == null) return resultList; for(int i = 0 ; i < sourceList.size() ; i++){ HashMap map = (HashMap)sourceList.get(i); String jsonStr = ""; Iterator it = map.keySet().iterator(); while(it.hasNext()){ String key = (String)it.next(); if("".equals(jsonStr)) jsonStr += "{"; else jsonStr += ","; jsonStr += "\""+key+"\":\""+CommonUtils.checkNull(map.get(key)).replaceAll("\"", "\\\\\"")+"\""; } jsonStr += "}"; resultList.add(jsonStr); } //System.out.println("getJsonArray(resultList.size()):"+resultList.size()); return resultList; } /** * String key, value를 받아 json string으로 반환. * @param key * @param data * @return */ public static String getJsonString(String key, String data){ if(data == null || "".equals(checkNull(data))) return ""; return "{\""+key+"\":\""+data+"\"}"; } /** * Map을 받아 json String으로 반환. * @param map * @return */ public static String getJsonMap(Map map){ String result = ""; if(map != null){ if(!map.isEmpty()){ Iterator it = map.keySet().iterator(); while(it.hasNext()){ String key = checkNull(it.next()); String value = checkNull(map.get(key)); if("".equals(result)) result += "{"; else result += ","; result += "\""+key+"\":\""+value+"\""; } result += "}"; } } if("".equals(result)) result = "{\"\":\"\"}"; return result; } /** * paramMap을 받아 page를 확인한다. * @param paramMap * @return */ public static Map checkPage(Map paramMap){ if(paramMap == null){ paramMap = new HashMap(); paramMap.put("page", "1"); }else{ if("".equals(checkNull(paramMap.get("page")))) paramMap.put("page", "1"); } return paramMap; } /** * java uuid를 통해 Object Id를 생성한다. * @return */ public static String createObjId(){ String objectId = ""; UUID uuid = new UUID(0,9); objectId = CommonUtils.checkNull(uuid.randomUUID().toString().replaceAll("-", "").hashCode()); return objectId; } /** * request에 처리에 대한 결과를 setAttribute 한다. * @param request * @param message 화면에 보여질 알람 문구 * @param resultFlag 처리에 대한 구분 */ public static HashMap setReqAttrResultMsg(HttpServletRequest request,String message,String resultFlag,Exception e,HashMap paramMap){ if(null == paramMap){ paramMap = new HashMap(); } String exceptionMessage = ""; if(!"".equals(CommonUtils.checkNull(message))){ request.setAttribute("message", message); } if(!"".equals(CommonUtils.checkNull(resultFlag))){ request.setAttribute("resultFlag", resultFlag); } if(null != e){ exceptionMessage = checkNull(e.getMessage()); request.setAttribute("exception", exceptionMessage); } paramMap.put("message", message); paramMap.put("resultFlag", resultFlag); paramMap.put("exception", exceptionMessage); return paramMap; } public static Map setReqResult(HttpServletRequest request, String message, String resultFlag, Exception e, Map paramMap){ if(null == paramMap){ paramMap = new HashMap(); } String exceptionMessage = ""; if(!"".equals(CommonUtils.checkNull(message))){ request.setAttribute("message", message); } if(!"".equals(CommonUtils.checkNull(resultFlag))){ request.setAttribute("resultFlag", resultFlag); } if(null != e){ exceptionMessage = checkNull(e.getMessage()); request.setAttribute("exception", exceptionMessage); } paramMap.put("MSG", CommonUtils.checkNull(CommonUtils.checkNull(message, e != null ? e.getMessage().replace("java.lang.Exception:", "") : ""), com.pms.common.Message.SYSTEM_ERROR)); paramMap.put("RESULT", resultFlag); paramMap.put("EXCEPTION", exceptionMessage); return paramMap; } /** * 페이징 관련 정보를 설정한다. * @param request * @param pagingMap * @return */ public static Map setPagingInfo(HttpServletRequest request, Map infoMap){ //int page = Integer.parseInt(checkNull(request.getParameter("page"),"1")); //int page = Integer.parseInt( checkNull(request.getParameter("page"), checkNull(request.getParameter("PAGE_T"),"1") ) );//tabulator용 int page = Integer.parseInt( checkNull(infoMap.get("page"), checkNull(infoMap.get("PAGE_T"),"1") ) );//tabulator용 int maxPage = (int) Double.parseDouble(checkNull(infoMap.get("MAX_PAGE_SIZE"), checkNull(infoMap.get("max_page_size"),"1"))); int cntPerPage = Integer.parseInt(checkNull(request.getParameter("countPerPage"),""+Constants.ADMIN_COUNT_PER_PAGE+"")); int nextPage = page+1; int prevPage = page-1; int startIdx = 1; int endIdx = cntPerPage; if(1 < page){ startIdx = ((page-1)*cntPerPage)+1; endIdx = cntPerPage*page; } if(maxPage < nextPage){ nextPage = maxPage; } if(prevPage <= 0){ prevPage = 1; } infoMap.put("PAGE_T", page); infoMap.put("COUNT_PER_PAGE", cntPerPage); infoMap.put("PAGE_START", startIdx); infoMap.put("PAGE_END", endIdx); infoMap.put("MAX_PAGE_SIZE", maxPage); request.setAttribute("countPerPage", cntPerPage); request.setAttribute("MAX_PAGE_SIZE", maxPage); request.setAttribute("TOTAL_COUNT", checkNull(infoMap.get("total_cnt"),"0")); request.setAttribute("NEXT_PAGE", nextPage); request.setAttribute("PREV_PAGE", prevPage); return infoMap; } public static String getPageingHtml(HttpServletRequest request, List list, boolean isHideIfEmpty){ //int nPage = Integer.parseInt(checkNull(request.getParameter("page"),"1")); int nPage = Integer.parseInt( checkNull(request.getParameter("page"), checkNull(request.getParameter("PAGE_T"),"1") ) );//tabulator용 int maxPage = Integer.parseInt(checkNull(request.getAttribute("MAX_PAGE_SIZE"),"1")); int totalCount = Integer.parseInt(checkNull(request.getAttribute("TOTAL_COUNT"),"0")); int prevPage = Integer.parseInt(checkNull(request.getAttribute("PREV_PAGE"),"1")); int nextPage = Integer.parseInt(checkNull(request.getAttribute("NEXT_PAGE"),"1")); StringBuffer sb = new StringBuffer(); sb.append(""); if(!(isHideIfEmpty && list.size() == 0)){ sb.append("
"); sb.append(" "); sb.append(" "); if(nPage > 1){ sb.append(" "); sb.append(" "); }else{ sb.append(" "); sb.append(" "); } for(int i=(nPage>5?nPage-5:1); i<(nPage>5?nPage+4:10); i++){ if(i-1 < maxPage){ if(i == nPage){ sb.append(" "); sb.append(" "); }else{ sb.append(" "); sb.append(" "); } } } if(nPage < maxPage){ sb.append(" "); }else{ sb.append(" "); } sb.append(" "); sb.append("
prev   prev   "+nPage+"   "+i+"   nextnext
"); sb.append("

총 "+totalCount+"건

"); sb.append("
"); } return sb.toString(); } //tabul용 페이징 public static String getPageingHtml2(HttpServletRequest request, List list, boolean isHideIfEmpty, Map pageMap){ boolean isTest = true; //int nPage = Integer.parseInt(checkNull(request.getParameter("page"),"1")); //int nPage = Integer.parseInt(checkNull(request.getParameter("PAGE_T"),"1")); //tabulator용 int nPage = Integer.parseInt(checkNull(pageMap.get("PAGE_T"),"1")); //tabulator용 int maxPage = Integer.parseInt(checkNull(request.getAttribute("MAX_PAGE_SIZE"),"1")); int totalCount = Integer.parseInt(checkNull(request.getAttribute("TOTAL_COUNT"),"0")); int prevPage = Integer.parseInt(checkNull(request.getAttribute("PREV_PAGE"),"1")); int nextPage = Integer.parseInt(checkNull(request.getAttribute("NEXT_PAGE"),"1")); int countPerPage = Integer.parseInt(checkNull(request.getAttribute("countPerPage"),"1")); //COUNT_PER_PAGE StringBuffer sb2 = new StringBuffer(); sb2.append(""); if(!(isHideIfEmpty && list.size() == 0)){ //new version sb2.append("
"); sb2.append("
"); sb2.append("
"); sb2.append(" "); sb2.append(" / 총"); sb2.append(" "+maxPage+""); sb2.append(" 페이지"); sb2.append(" go"); sb2.append("
"); //sb2.append(" "); //sb2.append(" "); for(int i=(nPage>5?nPage-5:1); i<(nPage>5?nPage+6:11); i++){ if(i-1 < maxPage){ if(i == nPage){ //sb2.append(" "+nPage+""); //sb2.append("    "); sb2.append(" "); }else{ //sb2.append(" "+i+""); //sb2.append("    "); sb2.append(" "); } } } //sb2.append(" "); //sb2.append(" "); //sb2.append(" "); //sb2.append(" "); //sb2.append(" "); //sb2.append(" "); //sb2.append(" "); //sb2.append(" "); //sb2.append(" "); //sb2.append(" "); //sb2.append(" "); //sb2.append("
"); sb2.append("
"); //sb2.append(" "); //sb2.append(" "); sb2.append("
"); sb2.append("
"); sb2.append(" "+numberFormat(totalCount)+"
"); sb2.append(""); sb2.append("
"); sb2.append(""); } //return sb.toString(); return sb2.toString(); } /** * 페이징 관련 정보를 설정한다. * @param request * @param pagingMap * @return */ public static Map setPagingInfo(HttpServletRequest request, Map infoMap,String countPerPage){ //int page = Integer.parseInt(checkNull(request.getParameter("page"),"1")); int page = Integer.parseInt( checkNull(request.getParameter("page"), checkNull(request.getParameter("PAGE_T"),"1") ) );//tabulator용 int maxPage = (int) Double.parseDouble(checkNull(infoMap.get("MAX_PAGE_SIZE"), checkNull(infoMap.get("max_page_size"),"1"))); int cntPerPage = Integer.parseInt(checkNull(countPerPage,""+Constants.ADMIN_COUNT_PER_PAGE+"")); int nextPage = page+1; int prevPage = page-1; int startIdx = 1; int endIdx = cntPerPage; if(1 < page){ startIdx = ((page-1)*cntPerPage)+1; endIdx = cntPerPage*page; } if(maxPage < nextPage){ nextPage = maxPage; } if(prevPage <= 0){ prevPage = 1; } infoMap.put("PAGE_START", startIdx); infoMap.put("PAGE_END", endIdx); request.setAttribute("countPerPage", countPerPage); request.setAttribute("MAX_PAGE_SIZE", maxPage); request.setAttribute("TOTAL_COUNT", checkNull(infoMap.get("total_cnt"),"0")); request.setAttribute("NEXT_PAGE", nextPage); request.setAttribute("PREV_PAGE", prevPage); return infoMap; } /** * 다음 Revision Code를 반환한다.
* 최소값 : A
* 최대값 : ZZ
* 대문자로만 반환한다. * @param prevRevision * @return */ public static String getNextRevision(String prevRevision){ String result = ""; prevRevision = prevRevision.toUpperCase(); if(prevRevision.length() >= 3 || "ZZ".equals(prevRevision)) return "ZZ"; try{ char[] chars = prevRevision.toCharArray(); if(chars.length == 2){ char c = chars[1]; if((int)c < 90){ //정상범주 int ascii = (int)c+1; result = chars[0]+""+(char)ascii; }else if((int)c == 90){ //revision : Z int ascii = (int)chars[0]+1; result = (char)ascii+"A"; } }else if(chars.length == 1){ char c = chars[0]; if((int)c < 90){ //정상범주 int ascii = (int)c+1; result = (char)ascii+""; }else if((int)c == 90){ //revision : Z result = "AA"; } } }catch(Exception e){ e.printStackTrace(); } return result; } /** * select된 정보 중 CLOB에 해당하는 데이터를 String으로 반환한다. * @param clob * @return */ public static String getClobToString(Clob clob){ String resultString = ""; try{ if(null == clob){ resultString = ""; }else{ StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(clob.getCharacterStream()); String tempStr = ""; while(null != (tempStr = br.readLine())){ //System.out.println("tempStr : "+tempStr); sb.append(tempStr+"\n"); } resultString = CommonUtils.checkNull(sb.toString()); } }catch(Exception e){ e.printStackTrace(); } return resultString; } /** * 관리자 이거 작성자일 경우 true를 반환한다. * @param request * @param targetMap * @param resultMap * @param keyName * @return */ public static boolean setWriterChecker(HttpServletRequest request,String targetId){ boolean authFlag = false; try{ PersonBean person = (PersonBean)request.getSession().getAttribute(Constants.PERSON_BEAN); String writer = CommonUtils.checkNull(person.getUserId()); if(writer.equals(CommonUtils.checkNull(targetId)) || "plm_admin".equals(writer)){ authFlag = true; } }catch(Exception e){ e.printStackTrace(); } return authFlag; } /** * 시간 확인 * @param time * @return */ public static String setFormatTime(long time){ Calendar c = Calendar.getInstance(); c.setTimeInMillis(time); String rtnTime = (c.get(Calendar.HOUR_OF_DAY) + "시 " + c.get(Calendar.MINUTE) + "분 " + c.get(Calendar.SECOND) + "." + c.get(Calendar.MILLISECOND) + "초"); return rtnTime; } /** * 소요시간 확인 * @param startTime * @param endTime */ public static void checkProcessingTime(long startTime, long endTime){ System.out.println("----------------------------------------------------"); System.out.println("측정 시작 시간 : "+setFormatTime(startTime)); System.out.println("측정 종료 시간 : "+setFormatTime(endTime)); System.out.println("측정 소요 시간 : "+setFormatTime(endTime-startTime)); System.out.println("----------------------------------------------------"); } public static String encodeURIComponent(String s) { String result = null; try { result = URLEncoder.encode(s, "UTF-8") .replaceAll("\\+", "%20") .replaceAll("\\%21", "!") .replaceAll("\\%27", "'") .replaceAll("\\%28", "(") .replaceAll("\\%29", ")") .replaceAll("\\%7E", "~"); } // This exception should never occur. catch (UnsupportedEncodingException e) { result = s; } return result; } public static HashMap keyChangeUpperHashMap(Map param) { if(param == null){ return null; } Iterator iteratorKey = param.keySet().iterator(); // 키값 오름차순 HashMap newMap = new HashMap(); // //키값 내림차순 정렬 while (iteratorKey.hasNext()) { String key = iteratorKey.next(); newMap.put(key.toUpperCase(), param.get(key)); } return newMap; } public static Map keyChangeUpperMap(Map param) { Iterator iteratorKey = param.keySet().iterator(); // 키값 오름차순 HashMap newMap = new HashMap(); // //키값 내림차순 정렬 while (iteratorKey.hasNext()) { String key = iteratorKey.next(); newMap.put(key.toUpperCase(), param.get(key)); } return newMap; } //리스트 받아서 맵 대문자로 바꾸기 public static List keyChangeUpperList(List param) { Map _result = new HashMap(); List resultList = new ArrayList(); for(Map result:param){ _result = keyChangeUpperMap(result); resultList.add(_result); } return resultList; } //리스트 받아서 맵 대문자로 바꾸기 public static ArrayList keyChangeUpperArrayList(ArrayList param) { Map _result = new HashMap(); ArrayList resultList = new ArrayList(); for(Map result:param){ _result = keyChangeUpperMap(result); resultList.add(_result); } return resultList; } /** * 파일 목록을 파일하나로 압축해서 반환 * @param zipFilePath 압축파일 저장경로 * @param zipFileName 압축파일명 * @param fileList 압축할 파일 목록 * 필수KEY1 Constants.Db.COL_FILE_PATH * 필수KEY2 Constants.Db.COL_FILE_SAVED_NAME * 필수KEY3 Constants.Db.COL_FILE_REAL_NAME * @author 악당밧밧이 */ @SuppressWarnings("rawtypes") public static File zipFileList(String zipFilePath, String zipFileName, ArrayList fileList){ File zipFile = null; ZipOutputStream zos = null; FileInputStream fis = null; try { if(fileList != null){ File fpath = new File(zipFilePath); if(!fpath.exists()){ //System.out.println("폴더없음 ["+fpath.getAbsolutePath()+"]"); if(fpath.mkdirs()){ //zip파일 생성할 폴더가 없으면 생성 //System.out.println("폴더생성완료"); }else{ System.out.println("CommonUtils.zipFileList ###폴더생성실패["+zipFilePath+"]"); } } byte[] bf = new byte[4096]; zipFile = new File(zipFilePath, zipFileName); zos = new ZipOutputStream(new FileOutputStream(zipFile)); for(HashMap hm_f : fileList){ String filePath = CommonUtils.checkNull(hm_f.get(Constants.Db.COL_FILE_PATH)) +"\\"+ CommonUtils.checkNull(hm_f.get(Constants.Db.COL_FILE_SAVED_NAME)); String fileName = CommonUtils.checkNull(hm_f.get(Constants.Db.COL_FILE_REAL_NAME)); File _f = new File(filePath); fis = new FileInputStream(_f); //zOut.putNextEntry(new ZipEntry(_f.getName())); zos.putNextEntry(new ZipEntry(fileName)); int len; while((len = fis.read(bf)) > 0){ zos.write(bf, 0, len); } zos.closeEntry(); fis.close(); } zos.close(); } } catch (Exception e) { System.out.println("CommonUtils.zipFileList ERR ::"+ e.getMessage()); } finally { if(zos != null){ zos = null; } if(fis != null){ fis = null; } } return zipFile; } public static String numberFormat(String num) { if(isBlank(num)) return num; //DecimalFormat formatter = new DecimalFormat("###,###"); DecimalFormat formatter = new DecimalFormat("#,##0.###"); return formatter.format(Double.parseDouble(num)); } public static String numberFormat(int num) { //DecimalFormat formatter = new DecimalFormat("###,###"); DecimalFormat formatter = new DecimalFormat("#,##0.###"); return formatter.format(num); } public static String numberFormat(long num) { //DecimalFormat formatter = new DecimalFormat("###,###"); DecimalFormat formatter = new DecimalFormat("#,##0.###"); return formatter.format(num); } public static Map requestLogApi(HttpServletRequest request,Map paramMap,String useType){ Map resultMap = new HashMap(); HttpURLConnection conn = null; try { PersonBean person = (PersonBean)request.getSession().getAttribute(Constants.PERSON_BEAN); String userId = person.getUserId(); String remoteAddr = CommonUtils.checkNull(request.getRemoteAddr()); Date now = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); String fNow = formatter.format(now); String paramStr = ""; // JSON 형식의 데이터 셋팅 끝 JSONObject params = new JSONObject(); params.put("crtfcKey", Constants.LOG_API_KEY); params.put("logDt", fNow); params.put("useSe", useType); params.put("sysUser", userId); params.put("conectIp", remoteAddr); params.put("dataUsgqty", ""); paramStr = URLEncoder.encode(params.toString(),"UTF-8"); //URL 설정 URL url = new URL("https://log.smart-factory.kr/apisvc/sendLogDataJSON.do?logData="+paramStr); conn = (HttpURLConnection) url.openConnection(); // type의 경우 POST, GET, PUT, DELETE 가능 conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Transfer-Encoding", "chunked"); conn.setRequestProperty("Connection", "keep-alive"); // 보내고 결과값 받기 int responseCode = conn.getResponseCode(); if (responseCode == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } String jsonStr = sb.toString(); JSONParser parser = new JSONParser(); resultMap = (Map)parser.parse(jsonStr); resultMap = (Map)resultMap.get("result"); } paramMap.put("recptnDt", CommonUtils.checkNull(resultMap.get("recptnDt"))); paramMap.put("recptnRsltDtl", CommonUtils.checkNull(resultMap.get("recptnRsltDtl"))); paramMap.put("recptnRslt", CommonUtils.checkNull(resultMap.get("recptnRslt"))); paramMap.put("recptnRsltCd", CommonUtils.checkNull(resultMap.get("recptnRsltCd"))); } catch (Exception e) { e.printStackTrace(); } // 결과 예제 // resultMap:{ // "recptnDt":"2023-03-30 17:40:07.663", // "recptnRsltDtl":"", // "recptnRslt":"데이터 이관 완료", // "recptnRsltCd":"AP1002" // } return resultMap; } public static String getValueInArray(int idx, String [] paramArr){ String val = ""; if(!isEmpty(paramArr) && paramArr.length > idx){ val = paramArr[idx]; } return val; } static boolean checkExistsFile(File file){ //파일이 존재하고 if(file.exists()){ //그 파일이 파일이고, 읽을 수 있다면 true를 리턴한다. if(file.isFile() && file.canRead()){ return true; } } return false; } public static String getParametersAddText(HttpServletRequest request, String paramName){ StringBuilder result = new StringBuilder(); String concatenatedValues =""; try{ String[] paramObject = request.getParameterValues(paramName); if(paramObject != null){ for (String value : paramObject) { result.append(value); result.append(","); } } concatenatedValues = result.toString(); if (concatenatedValues.endsWith(",")) { concatenatedValues = concatenatedValues.substring(0, concatenatedValues.length() - 1); } }catch(Exception ex){ result = result.append(request.getParameter(paramName)); concatenatedValues = result.toString(); } return concatenatedValues; } }