Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.kcs.core.utilities; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import org.apache.commons.lang3.ObjectUtils; import org.apache.log4j.Logger; import org.springframework.util.ReflectionUtils; /** * * @author chawachote */ public class Utility { static Logger logger = Logger.getLogger("Utility"); public static Object clone(Object sourceObject, Object tarObject) { if (sourceObject != null) { Class theSourceClass = sourceObject.getClass(); Class targetClass = tarObject.getClass(); Method soruceMethods[] = theSourceClass.getMethods(); for (int i = 0; i < soruceMethods.length; i++) { Method method = soruceMethods[i]; try { if (method.getName().startsWith("get") && !"getClass".equalsIgnoreCase(method.getName())) { if (method.getName().equalsIgnoreCase("getId")) { Object idObj = method.invoke(sourceObject); Class idClass = idObj.getClass(); Method idMethods[] = idClass.getMethods(); for (int j = 0; j < idMethods.length; j++) { try { Method idMethod = idMethods[j]; if (idMethod.getName().startsWith("get") && !"getClass".equals(idMethod.getName())) { String setterName = idMethod.getName().substring(3); setterName = "set" + setterName.substring(0, 1).toUpperCase() + setterName.substring(1); Method setter = targetClass.getMethod(setterName, idMethod.getReturnType()); setter.invoke(tarObject, idMethod.invoke(idObj)); } } catch (Exception e) { } } } else { String setterName = method.getName().substring(3); setterName = "set" + setterName.substring(0, 1).toUpperCase() + setterName.substring(1); Method setter = targetClass.getMethod(setterName, method.getReturnType()); setter.invoke(tarObject, method.invoke(sourceObject)); } } } catch (Exception e) { //e.printStackTrace(); } } return tarObject; } else { return null; } } public static void traceObject(Object sourceObj) { try { Method idMethods[] = sourceObj.getClass().getMethods(); logger.debug("************************************************************"); for (int j = 0; j < idMethods.length; j++) { try { Method idMethod = idMethods[j]; if (idMethod.getName().startsWith("get") && !"getClass".equals(idMethod.getName())) { logger.debug(sourceObj.getClass().getName() + " " + idMethod.getName() + " = " + idMethod.invoke(sourceObj)); } } catch (Exception e) { } } } catch (Exception ex) { // } } public static boolean chkBooleanBlankNullStr(String str) { boolean b = false; if (str == null || str.trim().equals("")) { b = true; } return b; } public static String chkBlankNullStr(String str) { String strResult = ""; if (str == null || str.trim().equals("")) { strResult = ""; } else { strResult = str.trim(); } return strResult; } public static boolean isNotNull(Object o) { if (!isNull(o)) { return true; } return false; } public static boolean isNull(Object o) { if (null == o) { return true; } return false; } public static String createXmlFileName(String datasetName, String strDate) { String fileName = datasetName + (Utility.isNotNull(strDate) ? " " + strDate.replace("/", "-") : ""); fileName += ".xml"; return fileName; } public static OutputStream generate(Object jaxbElement, OutputStream output) throws Exception { JAXBContext jaxbContext = JAXBContext.newInstance(jaxbElement.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(jaxbElement, output); return output; } public static byte[] generateToBytes(Object jaxbElement) throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); generate(jaxbElement, output); output.flush(); output.close(); return output.toByteArray(); } public static XMLGregorianCalendar getXMLGregorianCalendarDate(String date, String pattern) throws DatatypeConfigurationException, ParseException { SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.ENGLISH); Date newDate = format.parse(date); return getXMLGregorianCalendarDate(newDate); } public static XMLGregorianCalendar getXMLGregorianCalendarDate(Date date) throws DatatypeConfigurationException { if (Utility.isNotNull(date)) { GregorianCalendar arrgCtrDate = new GregorianCalendar(); arrgCtrDate.setTime(date); DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendarDate( arrgCtrDate.get(Calendar.YEAR), arrgCtrDate.get(Calendar.MONTH) + 1, arrgCtrDate.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED); return xmlGregorianCalendar; } return null; } public static String getXmlDateFormatString(Date date) throws DatatypeConfigurationException { if (Utility.isNull(date)) { return StringUtil.BLANK; } else { XMLGregorianCalendar xMLGregorianCalendar = getXMLGregorianCalendarDate(date); return xMLGregorianCalendar.toXMLFormat(); } } public static String getXmlLongString(Long o) { if (Utility.isNull(o) || o.longValue() == 0) { return StringUtil.BLANK; } else { return o.toString(); } } public static float getXmlFloat(BigDecimal value) { if (isNull(value)) { return 0.0f; } else { return value.floatValue(); } } public static String getXmlString(Number number) { return (Utility.isNull(number) ? StringUtil.BLANK : number.toString()); } public static void analyze(final Object obj) { ReflectionUtils.doWithFields(obj.getClass(), new ReflectionUtils.FieldCallback() { @Override public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { field.setAccessible(true); logger.debug(field.getName() + " : " + field.get(obj)); } }); } public static void nullToEmptyString(final Object obj) { ReflectionUtils.doWithFields(obj.getClass(), new ReflectionUtils.FieldCallback() { @Override public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { field.setAccessible(true); if (Utility.isNull(field.get(obj))) { Class<?> clazz = field.getType(); if (clazz == String.class) { field.set(obj, StringUtil.BLANK); } } } }); } public static <T> boolean objEquals(T obj1, T obj2) { if (Utility.isNull(obj1) || Utility.isNull(obj2)) { return obj1 == obj2; } else { return ObjectUtils.equals(obj1, obj2); } } public static boolean isOverMaxLength(String text, int maxLength) { if (text.length() > maxLength) { return true; } return false; } public static String[] split(String value, String delim) { if (value == null) { return new String[0]; } if (value.trim().equals("")) { return new String[0]; } String[] ret = null; if (value.indexOf(delim) == -1) { ret = new String[1]; ret[0] = value; } else { StringTokenizer stoken = new StringTokenizer(value, delim); ret = new String[stoken.countTokens()]; int i = 0; while (stoken.hasMoreTokens()) { ret[i] = stoken.nextToken(); i++; } } return ret; } public static boolean checkNumbersOnly(String str) { if (str == null || str.length() == 0 || str == "null") { return false; } for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != '.' && str.charAt(i) != '-') { return false; } } return true; } public static boolean checkFormatDateDDMMYYYY(String str) { if (str == null || str.length() == 0 || str == "null") { return false; } for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } public static boolean checkFormatDateDDMMYYYYBackSlash(String str) { if (str == null || str.length() == 0 || str == "null") { return false; } for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != '/') { return false; } } return true; } public static boolean checkFormatDateDDMMYYYYHHMISS(String str) { if (str == null || str.length() == 0 || str == "null") { return false; } for (int i = 0; i < str.length(); i++) { if (i == 8) { if (str.charAt(i) != ' ') { return false; } } else { if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != ':') { return false; } } } return true; } public static boolean isInteger(String s) { if ((s == null) || s.equals("")) { return false; } try { Integer.parseInt(s); return true; } catch (NumberFormatException e) { return false; } } public static Date convertDateFromBatch(String data, int line, String variable) throws Exception { Date date = new Date(); try { if (StringUtil.isNotEmpty(data)) { if (data.length() == 8) { if (checkFormatDateDDMMYYYY(data)) { date = DateUtil.parsePattern(data, DateUtil.DATE_FORMAT_DDMMYYYY); } else { throw new Exception("Error occurred between process Read data file \"" + data + "\" is not Date Format.Variable >>> \"" + variable + "\" Line >>> \"" + line + "\""); } } if (data.length() == 10) { if (checkFormatDateDDMMYYYYBackSlash(data)) { date = DateUtil.parsePattern(data, DateUtil.DEFAULT_DATE_FORMAT); } else { throw new Exception("Error occurred between process Read data file \"" + data + "\" is not Date Format.Variable >>> \"" + variable + "\" Line >>> \"" + line + "\""); } } if (data.length() == 17) { if (checkFormatDateDDMMYYYYHHMISS(data)) { date = DateUtil.parsePattern(data, DateUtil.DATE_FORMAT_DDMMYYYY2); } else { throw new Exception("Error occurred between process Read data file \"" + data + "\" is not Date Format.Variable >>> \"" + variable + "\" Line >>> \"" + line + "\""); } } } else { return null; } } catch (Exception e) { e.printStackTrace(); throw e; } return date; } public static BigDecimal convertBigDecimalFromBatch(String data, int decimal, int line, String variable) throws Exception { String strBigDecimal = "0"; BigDecimal result = BigDecimal.ZERO; try { if (StringUtil.isNotEmpty(data) && data.length() > decimal) { data = data.replace(".", ""); if (data.matches(".*-.*")) { data = data.substring(data.indexOf("-"), data.length()); } // else if(data.matches(".*+.*")) { // data = data.replace("+", ""); // } strBigDecimal = data.substring(0, data.length() - decimal) + "." + data.substring(data.length() - decimal, data.length()); if (checkNumbersOnly(strBigDecimal)) { result = new BigDecimal(strBigDecimal.trim()); } else { throw new Exception("Error occurred between process Read data file \"" + data + "\" is not BigDecimal Format.Variable >>> \"" + variable + "\" Line >>> \"" + line + "\""); } } else { return null; } } catch (Exception e) { e.printStackTrace(); throw e; } return result; } public static Long convertLongFromBatch(String data, int line, String variable) throws Exception { Long result = new Long(0); try { if (StringUtil.isNotEmpty(data)) { if (checkNumbersOnly(data)) { result = NumberUtil.getLongValue(data); } else { throw new Exception("Error occurred between process Read data file \"" + data + "\" is not Long Format.Variable >>> \"" + variable + "\" Line >>> \"" + line + "\""); } } else { return null; } } catch (Exception e) { e.printStackTrace(); throw e; } return result; } }