- 浏览: 1562532 次
- 性别:
- 来自: 吉林
文章分类
- 全部博客 (624)
- C/C++ (33)
- Java (181)
- 网络相关 (7)
- 我爱篮球 (3)
- 也爱足球 (4)
- 杂谈 (1)
- 系统架构 (3)
- Web Service (14)
- Framework (3)
- 系统命令 (8)
- 管理平台相关 (8)
- 其它 (35)
- Websphere (1)
- Struts2 (24)
- Hibernate (16)
- Spring (23)
- javascript (20)
- jquery (23)
- html/css/div (28)
- 数据库 (40)
- JavaWeb (27)
- 设计模式 (2)
- 文档编写 (3)
- SVN (5)
- Ant (1)
- Maven (13)
- 软件项目管理 (8)
- AOP (1)
- kindeditor (1)
- JSON (2)
- Servlt/JSP (4)
- WordXML (2)
- XML (12)
- 面试相关 (7)
- Tomcat (11)
- 性能与调优 (29)
- 职业发展 (2)
- 操作系统 (7)
- AJAX (2)
- DWR (1)
- Eclipse (12)
- 持续集成 (3)
- 批处理命令 (1)
- Mozilla Rhino (2)
- 新鲜技术 (18)
- Apache mina (2)
- 底层技术 (18)
- Linux (22)
- 新鲜技术,IT历史 (1)
- 敏捷开发 (1)
- 版本控制 (5)
- 较火技术 (7)
- 集群 (2)
- Web前端 (13)
- 报表工具 (3)
- 网站架构 (5)
- 大数据 (8)
- 分布式存储 (5)
- 云计算 (8)
- TCP/IP协议 (1)
- 负载均衡 (3)
- 硬件 (1)
- 表现层技术 (3)
- Velocity (3)
- jvm (6)
- 并发编程 (10)
- hadoop (8)
- 数据结构和算法 (12)
- 计算机原理 (1)
- 测试驱动开发-TDD (3)
- 开发技巧 (1)
- 分词器 (1)
- 项目构建工具 (2)
- JMX (4)
- RMI (1)
- 测试技术 (22)
- 网络完全 (1)
- Git (4)
- apache开源包 (4)
- Java常用 (1)
- mock (2)
- OSGi (2)
- MongoDB (1)
- JBPM (1)
- Storm (3)
- mysql (2)
- telnet (1)
- 正则表达式 (1)
- bootstrap (4)
- Apache ActiveMQ (1)
- redis (9)
- Nginx (2)
- rsync+inotify文件同步 (2)
- testng (1)
- 原型设计工具 (1)
- 工程能力 (1)
- 风险控制 (3)
- ibatis (1)
- 分布式 (4)
- 安全技术 (1)
- 计算机基础 (4)
- 消息中间件 (1)
- UML (2)
最新评论
-
u012236967:
java命令执行jar包(里面的main函数)的方式(包括依赖其它的jar包问题) -
世界尽头没有你:
Selenium自动化测试从入门到精通(Java版)百度网盘地 ...
自动化测试工具 Selenium WebDriver 入门教程(针对主流浏览器) -
小小西芹菜:
我喜欢代码简洁易读,服务稳定的推送服务,前段时间研究了一下go ...
dwr实现Reverse Ajax推送技术的三种方式 -
hellozhouqiao:
楼主,请教一点问题.现在我们需要在excel 的页脚里面加上图 ...
FreeMaker + xml 导出word(处理目录,图片和页眉页脚问题) -
乱在长安:
使用Timer会有各种各样的问题好嘛?!书上推荐使用Sched ...
DelayQueue (ScheduledThreadPoolExecutor调度的实现)
收藏列表
- 全部 [32]
- spring [2]
- ubuntu [1]
- jquery [2]
- java [2]
- hadoop [1]
- java excel [2]
- java email [1]
- java io [1]
- java xml [4]
- java zip [1]
- java date [2]
- java image [1]
- java linux [1]
- java svn [1]
- kindeditor [1]
- java properties [1]
- java json [1]
- jquery table [1]
- guava [1]
- java telnet [1]
- java windows [1]
- java charset [1]
- java ast [1]
- java 字符串\消息工具类 [2]
- 好的工具类 [1]
- 工作积累好代码 [1]
标题 | 标签 | 来源 | |
序列化并压缩请求表单,根据流水号再反序列化完成交易(用于工单审核交易) | 工作积累好代码 | ||
//1. 序列化 @Override public void write(CoreContext context, Object request) { Map<String, String> productMap = this.parmQueryAdapter.queryParmByProdCode(context .getProductId()); if (null == productMap) { return; } //将map转换成bean BankProduct product = (BankProduct) BeanHelper .map2BeanStrict(productMap, new BankProduct()); //不需要审批的交易不记录序列化表 if (ProductAttribute.PRODUCT_FALSE.equals(product.getCheckFlag())) { return; } TransParamsDO transParamsDO = new TransParamsDO(); transParamsDO.setCmpId(context.getCmpId()); transParamsDO.setTntInstId(context.getTntInstId()); transParamsDO.setId(context.getRequestJnlNo()); //将bean转换成map(仅提取可读写的属性) Map<String, Object> requestMap = BeanHelper.bean2MapStrict(request); requestMap.remove(MyBankDict.ENCRYPT_DATA_LOWERCASE); //可以通过选项 DisableCircularReferenceDetect来禁止循环引用检测,避免出现$ref String jnlData = JSONArray.toJSONString(requestMap, SerializerFeature.DisableCircularReferenceDetect); try { //压缩数据并存入数据库 transParamsDO.setParams(ZipUtil.zip(jnlData)); } catch (IOException e) { throw new EBankException(EBankErrorEnum.UNKNOWN_EXCEPTION, "com.mybank.bkebank.jnl.impl.JNLDataServiceImpl.write", e); } this.transactionExtraDAO.insert(transParamsDO); } //反序列化交易数据 /** * 恢复序列化日志 * @see com.mybank.bkebank.jnl.IJNLDataService#restore(java.lang.Long, java.lang.String, java.lang.Class) */ @Override public Object restore(String tntInstId, String cmpId, String jnlSeq, Class<?> clazz) { TransParamsDO extraDo = this.transactionExtraDAO.queryTransactionExtra(tntInstId, cmpId, jnlSeq); if (null == extraDo) { throw new EBankException(EBankErrorEnum.TRANSACTION_NOFUND); } String jnlDate = null; try { jnlDate = (String) ZipUtil.unzip(extraDo.getParams()); } catch (IOException e) { throw new EBankException(EBankErrorEnum.UNKNOWN_EXCEPTION, "com.mybank.bkebank.jnl.impl.JNLDataServiceImpl.restore", e); } Object response = JSON.parseObject(jnlDate, clazz); return response; } |
|||
Spring对bean的属性进行操作 | spring | ||
/** * 将map转换成bean方法 传入参数类型{Map<String, ?>,T} */ public static <T> Object map2Bean(final Map<String, ?> map, final T obj) { BeanWrapper bw = new BeanWrapperImpl(obj); PropertyDescriptor[] props = bw.getPropertyDescriptors(); for (PropertyDescriptor pd : props) { String name = pd.getName(); if (bw.isWritableProperty(name) && bw.isReadableProperty(name)) { Class<?> class0 = pd.getPropertyType(); if (Enum.class.isAssignableFrom(class0)) { String convertedName = Character .toUpperCase(name.charAt(0)) + name.substring(1); Object value = map.get(convertedName); if (value != null) { if (value.getClass() == class0) { bw.setPropertyValue(name, value); } /*else { String enumValue = String.valueOf(value); // if (enumValue.length() > 0) { // // Enum<?> v = Enum.valueOf(Enum<?>.class, enumValue); // // bw.setPropertyValue(name, v); // } }*/ } } else { String convertedName = Character .toUpperCase(name.charAt(0)) + name.substring(1); Object value = map.get(convertedName); if (value != null) { bw.setPropertyValue(name, value); } } } } return bw.getWrappedInstance(); } /** * 将map转换成bean方法 传入参数类型{Map<String, Object>,Class<T>} */ public static <T> T map2Bean(final Map<String, Object> map, final Class<T> clazz) { BeanWrapper bw = new BeanWrapperImpl(clazz); PropertyDescriptor[] props = bw.getPropertyDescriptors(); for (PropertyDescriptor pd : props) { String name = pd.getName(); if (bw.isWritableProperty(name) && bw.isReadableProperty(name)) { Class<?> class0 = pd.getPropertyType(); if (Enum.class.isAssignableFrom(class0)) { String convertedName = Character .toUpperCase(name.charAt(0)) + name.substring(1); Object value = map.get(convertedName); if (value != null) { if (value.getClass() == class0) { bw.setPropertyValue(name, value); } /*else { String enumValue = String.valueOf(value); // if (enumValue.length() > 0) { // // Enum v = Enum.valueOf(class0, String.valueOf(value)); // // bw.setPropertyValue(name, v); // } }*/ } } else { String convertedName = Character .toUpperCase(name.charAt(0)) + name.substring(1); Object value = map.get(convertedName); if (value != null) { bw.setPropertyValue(name, value); } } } } return (T) bw.getWrappedInstance(); } /** * 对象属性转换成为MAP<name,value> * * @param beanObject 对象 * @return map */ public static Map<String, Object> bean2Map(final Object beanObject) { BeanWrapperImpl bean = new BeanWrapperImpl(beanObject); PropertyDescriptor desc[] = bean.getPropertyDescriptors(); Map<String, Object> dataMap = new HashMap<String, Object>(desc.length); for (int i = 0; i < desc.length; i++) { String name = desc[i].getName(); // 只提取可读写的属性 if (bean.isWritableProperty(name) && bean.isReadableProperty(name)) { Object object = bean.getPropertyValue(name); if (null == object) { continue; } String convertedName = Character.toUpperCase(name.charAt(0)) + name.substring(1); dataMap.put(convertedName, object); } } return dataMap; } |
|||
好的工具类 | 好的工具类 | ||
//1. apache包中的将对象打印出来的类 import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; ReflectionToStringBuilder.reflectionToString(context.getUser().getMemberInfo() , ToStringStyle.SHORT_PREFIX_STYLE) //2.spring中对于bean属性的操作 public static <T> Object map2Bean(final Map<String, ?> map, final T obj) { BeanWrapper bw = new BeanWrapperImpl(obj); PropertyDescriptor[] props = bw.getPropertyDescriptors(); |
|||
DateUtil | java date | ||
public class DateUtil { private final static Logger log = LoggerFactory.getLogger(DateUtil.class); public final static long ONE_DAY_SECONDS = 86400; /* * private static DateFormat dateFormat = null; private static DateFormat * longDateFormat = null; private static DateFormat dateWebFormat = null; */ public final static String shortFormat = "yyyyMMdd"; public final static String longFormat = "yyyyMMddHHmmss"; public final static String webFormat = "yyyy-MM-dd"; public final static String timeFormat = "HHmmss"; public final static String monthFormat = "yyyyMM"; public final static String chineseDtFormat = "yyyy��MM��dd��"; public final static String newFormat = "yyyy-MM-dd HH:mm:ss"; public final static String noSecondFormat = "yyyy-MM-dd HH:mm"; public final static long ONE_DAY_MILL_SECONDS = 86400000; public static DateFormat getNewDateFormat(String pattern) { DateFormat df = new SimpleDateFormat(pattern); df.setLenient(false); return df; } public static String format(Date date, String format) { if (date == null) { return null; } return new SimpleDateFormat(format).format(date); } public static Date parseDateNoTime(String sDate) throws ParseException { DateFormat dateFormat = new SimpleDateFormat(shortFormat); if ((sDate == null) || (sDate.length() < shortFormat.length())) { throw new ParseException("length too little", 0); } if (!StringUtils.isNumeric(sDate)) { throw new ParseException("not all digit", 0); } return dateFormat.parse(sDate); } public static Date parseDateNoTime(String sDate, String format) throws ParseException { if (StringUtils.isBlank(format)) { throw new ParseException("Null format. ", 0); } DateFormat dateFormat = new SimpleDateFormat(format); if ((sDate == null) || (sDate.length() < format.length())) { throw new ParseException("length too little", 0); } return dateFormat.parse(sDate); } public static Date parseDateNoTimeWithDelimit(String sDate, String delimit) throws ParseException { sDate = sDate.replaceAll(delimit, ""); DateFormat dateFormat = new SimpleDateFormat(shortFormat); if ((sDate == null) || (sDate.length() != shortFormat.length())) { throw new ParseException("length not match", 0); } return dateFormat.parse(sDate); } public static Date parseDateLongFormat(String sDate) { DateFormat dateFormat = new SimpleDateFormat(longFormat); Date d = null; if ((sDate != null) && (sDate.length() == longFormat.length())) { try { d = dateFormat.parse(sDate); } catch (ParseException ex) { return null; } } return d; } public static Date parseDateNewFormat(String sDate) { DateFormat dateFormat = new SimpleDateFormat(newFormat); Date d = null; dateFormat.setLenient(false); if ((sDate != null) && (sDate.length() == newFormat.length())) { try { d = dateFormat.parse(sDate); } catch (ParseException ex) { return null; } } return d; } /** * ���㵱ǰʱ�伸Сʱ֮���ʱ�� * * @param date * @param hours * * @return */ public static Date addHours(Date date, long hours) { return addMinutes(date, hours * 60); } /** * ���㵱ǰʱ�伸����֮���ʱ�� * * @param date * @param minutes * * @return */ public static Date addMinutes(Date date, long minutes) { return addSeconds(date, minutes * 60); } /** * @param date1 * @param secs * * @return */ public static Date addSeconds(Date date1, long secs) { return new Date(date1.getTime() + (secs * 1000)); } /** * �ж�������ַ��Ƿ�Ϊ�Ϸ���Сʱ * * @param hourStr * * @return true/false */ public static boolean isValidHour(String hourStr) { if (!StringUtil.isEmpty(hourStr) && StringUtil.isNumeric(hourStr)) { int hour = new Integer(hourStr).intValue(); if ((hour >= 0) && (hour <= 23)) { return true; } } return false; } /** * �ж�������ַ��Ƿ�Ϊ�Ϸ��ķֻ��� * * @param minuteStr * * @return true/false */ public static boolean isValidMinuteOrSecond(String str) { if (!StringUtil.isEmpty(str) && StringUtil.isNumeric(str)) { int hour = new Integer(str).intValue(); if ((hour >= 0) && (hour <= 59)) { return true; } } return false; } /** * ȡ���µ����� * * @param date1 ���� * @param days ���� * * @return �µ����� */ public static Date addDays(Date date1, long days) { return addSeconds(date1, days * ONE_DAY_SECONDS); } public static String getTomorrowDateString(String sDate) throws ParseException { Date aDate = parseDateNoTime(sDate); aDate = addSeconds(aDate, ONE_DAY_SECONDS); return getDateString(aDate); } public static String getLongDateString(Date date) { DateFormat dateFormat = new SimpleDateFormat(longFormat); return getDateString(date, dateFormat); } public static String getNewFormatDateString(Date date) { DateFormat dateFormat = new SimpleDateFormat(newFormat); return getDateString(date, dateFormat); } public static String getDateString(Date date, DateFormat dateFormat) { if (date == null || dateFormat == null) { return null; } return dateFormat.format(date); } public static String getYesterDayDateString(String sDate) throws ParseException { Date aDate = parseDateNoTime(sDate); aDate = addSeconds(aDate, -ONE_DAY_SECONDS); return getDateString(aDate); } /** * @return �����ʱ���ʽ��Ϊ"yyyyMMdd" */ public static String getDateString(Date date) { DateFormat df = getNewDateFormat(shortFormat); return df.format(date); } public static String getWebDateString(Date date) { DateFormat dateFormat = getNewDateFormat(webFormat); return getDateString(date, dateFormat); } /** * ȡ�á�X��X��X�ա������ڸ�ʽ * * @param date * * @return */ public static String getChineseDateString(Date date) { DateFormat dateFormat = getNewDateFormat(chineseDtFormat); return getDateString(date, dateFormat); } public static String getTodayString() { DateFormat dateFormat = getNewDateFormat(shortFormat); return getDateString(new Date(), dateFormat); } public static String getTimeString(Date date) { DateFormat dateFormat = getNewDateFormat(timeFormat); return getDateString(date, dateFormat); } public static String getBeforeDayString(int days) { Date date = new Date(System.currentTimeMillis() - (ONE_DAY_MILL_SECONDS * days)); DateFormat dateFormat = getNewDateFormat(shortFormat); return getDateString(date, dateFormat); } /** * ȡ���������ڼ����������1-����2�� * * @param one ����1 * @param two ����2 * * @return ������� */ public static long getDiffSeconds(Date one, Date two) { Calendar sysDate = new GregorianCalendar(); sysDate.setTime(one); Calendar failDate = new GregorianCalendar(); failDate.setTime(two); return (sysDate.getTimeInMillis() - failDate.getTimeInMillis()) / 1000; } public static long getDiffMinutes(Date one, Date two) { Calendar sysDate = new GregorianCalendar(); sysDate.setTime(one); Calendar failDate = new GregorianCalendar(); failDate.setTime(two); return (sysDate.getTimeInMillis() - failDate.getTimeInMillis()) / (60 * 1000); } /** * ȡ���������ڵļ������ * * @param one * @param two * * @return ������� */ public static long getDiffDays(Date one, Date two) { Calendar sysDate = new GregorianCalendar(); sysDate.setTime(one); Calendar failDate = new GregorianCalendar(); failDate.setTime(two); return (sysDate.getTimeInMillis() - failDate.getTimeInMillis()) / (24 * 60 * 60 * 1000); } public static String getBeforeDayString(String dateString, int days) { Date date; DateFormat df = getNewDateFormat(shortFormat); try { date = df.parse(dateString); } catch (ParseException e) { date = new Date(); } date = new Date(date.getTime() - (ONE_DAY_MILL_SECONDS * days)); return df.format(date); } public static boolean isValidShortDateFormat(String strDate) { if (strDate.length() != shortFormat.length()) { return false; } try { Integer.parseInt(strDate); //---- ������������������� ---- } catch (Exception NumberFormatException) { return false; } DateFormat df = getNewDateFormat(shortFormat); try { df.parse(strDate); } catch (ParseException e) { return false; } return true; } public static boolean isValidShortDateFormat(String strDate, String delimiter) { String temp = strDate.replaceAll(delimiter, ""); return isValidShortDateFormat(temp); } /** * �жϱ�ʾʱ����ַ��Ƿ�Ϊ���yyyyMMddHHmmss��ʽ * * @param strDate * @return */ public static boolean isValidLongDateFormat(String strDate) { if (strDate.length() != longFormat.length()) { return false; } try { Long.parseLong(strDate); //---- ������������������� ---- } catch (Exception NumberFormatException) { return false; } DateFormat df = getNewDateFormat(longFormat); try { df.parse(strDate); } catch (ParseException e) { return false; } return true; } /** * �жϱ�ʾʱ����ַ��Ƿ�Ϊ���yyyyMMddHHmmss��ʽ * * @param strDate * @param delimiter * @return */ public static boolean isValidLongDateFormat(String strDate, String delimiter) { String temp = strDate.replaceAll(delimiter, ""); return isValidLongDateFormat(temp); } public static String getShortDateString(String strDate) { return getShortDateString(strDate, "-|/"); } public static String getShortDateString(String strDate, String delimiter) { if (StringUtil.isBlank(strDate)) { return null; } String temp = strDate.replaceAll(delimiter, ""); if (isValidShortDateFormat(temp)) { return temp; } return null; } public static String getShortFirstDayOfMonth() { Calendar cal = Calendar.getInstance(); Date dt = new Date(); cal.setTime(dt); cal.set(Calendar.DAY_OF_MONTH, 1); DateFormat df = getNewDateFormat(shortFormat); return df.format(cal.getTime()); } public static String getWebTodayString() { DateFormat df = getNewDateFormat(webFormat); return df.format(new Date()); } public static String getWebFirstDayOfMonth() { Calendar cal = Calendar.getInstance(); Date dt = new Date(); cal.setTime(dt); cal.set(Calendar.DAY_OF_MONTH, 1); DateFormat df = getNewDateFormat(webFormat); return df.format(cal.getTime()); } public static String convert(String dateString, DateFormat formatIn, DateFormat formatOut) { try { Date date = formatIn.parse(dateString); return formatOut.format(date); } catch (ParseException e) { log.warn("convert() --- orign date error: " + dateString); return ""; } } public static String convert2WebFormat(String dateString) { DateFormat df1 = getNewDateFormat(shortFormat); DateFormat df2 = getNewDateFormat(webFormat); return convert(dateString, df1, df2); } public static String convert2ChineseDtFormat(String dateString) { DateFormat df1 = getNewDateFormat(shortFormat); DateFormat df2 = getNewDateFormat(chineseDtFormat); return convert(dateString, df1, df2); } public static String convertFromWebFormat(String dateString) { DateFormat df1 = getNewDateFormat(shortFormat); DateFormat df2 = getNewDateFormat(webFormat); return convert(dateString, df2, df1); } public static boolean webDateNotLessThan(String date1, String date2) { DateFormat df = getNewDateFormat(webFormat); return dateNotLessThan(date1, date2, df); } /** * @param date1 * @param date2 * @param dateWebFormat2 * * @return */ public static boolean dateNotLessThan(String date1, String date2, DateFormat format) { try { Date d1 = format.parse(date1); Date d2 = format.parse(date2); if (d1.before(d2)) { return false; } else { return true; } } catch (ParseException e) { log.debug("dateNotLessThan() --- ParseException(" + date1 + ", " + date2 + ")"); return false; } } public static String getEmailDate(Date today) { String todayStr; SimpleDateFormat sdf = new SimpleDateFormat("yyyy��MM��dd��HH:mm:ss"); todayStr = sdf.format(today); return todayStr; } public static String getSmsDate(Date today) { String todayStr; SimpleDateFormat sdf = new SimpleDateFormat("MM��dd��HH:mm"); todayStr = sdf.format(today); return todayStr; } public static String formatTimeRange(Date startDate, Date endDate, String format) { if ((endDate == null) || (startDate == null)) { return null; } String rt = null; long range = endDate.getTime() - startDate.getTime(); long day = range / DateUtils.MILLIS_PER_DAY; long hour = (range % DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_HOUR; long minute = (range % DateUtils.MILLIS_PER_HOUR) / DateUtils.MILLIS_PER_MINUTE; if (range < 0) { day = 0; hour = 0; minute = 0; } rt = format.replaceAll("dd", String.valueOf(day)); rt = rt.replaceAll("hh", String.valueOf(hour)); rt = rt.replaceAll("mm", String.valueOf(minute)); return rt; } public static String formatMonth(Date date) { if (date == null) { return null; } return new SimpleDateFormat(monthFormat).format(date); } /** * ��ȡϵͳ���ڵ�ǰһ�����ڣ�����Date * * @return */ public static Date getBeforeDate() { Date date = new Date(); return new Date(date.getTime() - (ONE_DAY_MILL_SECONDS)); } /** * ���ָ��ʱ�䵱�����ʱ�� * * @param date * @return */ public static Date getDayBegin(Date date) { DateFormat df = new SimpleDateFormat("yyyyMMdd"); df.setLenient(false); String dateString = df.format(date); try { return df.parse(dateString); } catch (ParseException e) { return date; } } /** * �жϲ�date��min���Ӻ��Ƿ�С�ڵ�ǰʱ�� * @param date * @param min * @return */ public static boolean dateLessThanNowAddMin(Date date, long min) { return addMinutes(date, min).before(new Date()); } public static boolean isBeforeNow(Date date) { if (date == null) return false; return date.compareTo(new Date()) < 0; } public static void main(String[] args) { System.out.println(isBeforeNow(new Date())); } public static Date parseNoSecondFormat(String sDate) throws ParseException { DateFormat dateFormat = new SimpleDateFormat(noSecondFormat); if ((sDate == null) || (sDate.length() < noSecondFormat.length())) { throw new ParseException("length too little", 0); } if (!StringUtils.isNumeric(sDate)) { throw new ParseException("not all digit", 0); } return dateFormat.parse(sDate); } } |
|||
google guava包筛选List对象迭代器的使用 | guava | ||
import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; List<ArrangementQuerySelector> selectors = new ArrayList<ArrangementQuerySelector>(); ArrangementAccountSelector selector = new ArrangementAccountSelector(); selectors.add(selector); List<ArrangementInfo> arrs = arrangementQueryAdapter.queryArrInfoByRoleIdAndProdCode(cmpid, SysDict.PRODCODE_COMPANYACCNO, ArrangementStatusEnum.VALID.getCode(), selectors); if (CollectionUtils.isEmpty(arrs)) { throw new EBankException(EBankErrorEnum.REQUEST_PARAM_ILLEGAL, "dddd"); } // 根据外部标识进行过滤(平台PartnerId和MemberId) Iterable<ArrangementInfo> ArrIterable = Iterables.filter(arrs, new Predicate<ArrangementInfo>() { @Override public boolean apply(final ArrangementInfo input) { List<ArrangementAccountInfo> accountInfoList = input .getArrangementAccountInfo(); if (CollectionUtils.isEmpty(accountInfoList)) { return false; } return StringUtils.equals(memberInfo.getPartnerId(), accountInfoList.get(0) .getFinancialInvovledPartyCode()) && StringUtils.equals(memberInfo.getMemberId(), accountInfoList.get(0) .getAccountNo()); } }); arrs = Lists.newArrayList(ArrIterable); |
|||
LogUtils | java, java 字符串\消息工具类 | ||
public class LogUtils { /** * 参数数组转换成脱敏后的字符串数组 * * @param params 日志入参 * @return */ private static Object[] shieldParams(final Object... params) { if (params == null || params.length == 0) { return params; } String[] shieldParams = new String[params.length]; for (int i = 0; i < params.length; i++) { shieldParams[i] = LogFormatUtil.getLogStringWithoutBracket(params[i]); } return shieldParams; } /** * <p> Log a message with debug log level. </p> * @param logger 日志类对象 * @param message 日志内容 * @param params 日志入参 * */ public static void debug(final Logger logger, final String message, final Object... params) { if ((logger != null)) { if (logger.isDebugEnabled()) { logger.debug(format(message, shieldParams(params))); } } } /** * <p> Log a message with info log level. </p> * @param logger 日志类对象 * @param message 日志内容 * @param params 日志入参 * */ public static void info(final Logger logger, final String message, final Object... params) { if ((logger != null)) { if (logger.isInfoEnabled()) { logger.info(format(message, shieldParams(params))); } } } /** * <p> Log a message with warn log level. </p> * @param logger 日志类对象 * @param message 日志内容 * @param param 日志入参 * */ public static void warn(final Logger logger, final String message, final Object... params) { if ((logger != null)) { if (logger.isWarnEnabled()) { logger.warn(format(message, shieldParams(params))); } } } /** * <p> Log a message with warn log level. </p> * @param logger 日志类对象 * @param message 日志内容 * @param throwable 异常对象 * @param params 日志入参 * */ public static void warn(final Logger logger, final String message, final Throwable throwable, final Object... params) { if ((logger != null)) { if (logger.isWarnEnabled()) { logger.warn(format(message, shieldParams(params)), throwable); } } } /** * <p> Log a message with error log level. </p> * @param logger 日志类对象 * @param message 日志内容 * @param params 日志入参 * */ public static void error(final Logger logger, final String message, final Object... params) { if ((logger != null)) { if (logger.isErrorEnabled()) { logger.error(format(message, shieldParams(params))); } } } /** * <p> Log a message and throwable with error log level. </p> * @param logger 日志类对象 * @param message 日志内容 * @param throwable 异常对象 * @param params 日志入参 * */ public static void error(final Logger logger, final String message, final Throwable throwable, final Object... params) { if ((logger != null)) { if (logger.isErrorEnabled()) { logger.error(format(message, shieldParams(params)), throwable); } } } } |
|||
和ResourceBundle及消息字符串有关的工具类 | java 字符串\消息工具类 | ||
import java.text.MessageFormat; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * 和<code>ResourceBundle</code>及消息字符串有关的工具类。 * */ public class MessageUtil { /* ============================================================================ */ /* 以下是有关resource bundle的方法 */ /* ============================================================================ */ /** * 从<code>ResourceBundle</code>中取得字符串,并使用<code>MessageFormat</code>格式化字符串. * * @param bundle resource bundle * @param key 要查找的键 * @param params 参数表 * * @return key对应的字符串,如果key为<code>null</code>或resource * bundle为<code>null</code>,或resource key未找到,则返回<code>key</code> */ public static String getMessage(ResourceBundle bundle, String key, Object[] params) { if ((bundle == null) || (key == null)) { return key; } try { String message = bundle.getString(key); return formatMessage(message, params); } catch (MissingResourceException e) { return key; } } /** * 从<code>ResourceBundle</code>中取得字符串,并使用<code>MessageFormat</code>格式化字符串. * * @param bundle resource bundle * @param key 要查找的键 * @param param1 参数1 * * @return key对应的字符串,如果key为<code>null</code>或resource * bundle为<code>null</code>,则返回<code>null</code>。如果resource key未找到,则返回<code>key</code> */ public static String getMessage(ResourceBundle bundle, String key, Object param1) { return getMessage(bundle, key, new Object[] { param1 }); } /** * 从<code>ResourceBundle</code>中取得字符串,并使用<code>MessageFormat</code>格式化字符串. * * @param bundle resource bundle * @param key 要查找的键 * @param param1 参数1 * @param param2 参数2 * * @return key对应的字符串,如果key为<code>null</code>或resource * bundle为<code>null</code>,则返回<code>null</code>。如果resource key未找到,则返回<code>key</code> */ public static String getMessage(ResourceBundle bundle, String key, Object param1, Object param2) { return getMessage(bundle, key, new Object[] { param1, param2 }); } /** * 从<code>ResourceBundle</code>中取得字符串,并使用<code>MessageFormat</code>格式化字符串. * * @param bundle resource bundle * @param key 要查找的键 * @param param1 参数1 * @param param2 参数2 * @param param3 参数3 * * @return key对应的字符串,如果key为<code>null</code>或resource * bundle为<code>null</code>,则返回<code>null</code>。如果resource key未找到,则返回<code>key</code> */ public static String getMessage(ResourceBundle bundle, String key, Object param1, Object param2, Object param3) { return getMessage(bundle, key, new Object[] { param1, param2, param3 }); } /** * 从<code>ResourceBundle</code>中取得字符串,并使用<code>MessageFormat</code>格式化字符串. * * @param bundle resource bundle * @param key 要查找的键 * @param param1 参数1 * @param param2 参数2 * @param param3 参数3 * @param param4 参数4 * * @return key对应的字符串,如果key为<code>null</code>或resource * bundle为<code>null</code>,则返回<code>null</code>。如果resource key未找到,则返回<code>key</code> */ public static String getMessage(ResourceBundle bundle, String key, Object param1, Object param2, Object param3, Object param4) { return getMessage(bundle, key, new Object[] { param1, param2, param3, param4 }); } /** * 从<code>ResourceBundle</code>中取得字符串,并使用<code>MessageFormat</code>格式化字符串. * * @param bundle resource bundle * @param key 要查找的键 * @param param1 参数1 * @param param2 参数2 * @param param3 参数3 * @param param4 参数4 * @param param5 参数5 * * @return key对应的字符串,如果key为<code>null</code>或resource * bundle为<code>null</code>,则返回<code>null</code>。如果resource key未找到,则返回<code>key</code> */ public static String getMessage(ResourceBundle bundle, String key, Object param1, Object param2, Object param3, Object param4, Object param5) { return getMessage(bundle, key, new Object[] { param1, param2, param3, param4, param5 }); } /* ============================================================================ */ /* 以下是用MessageFormat格式化字符串的方法 */ /* ============================================================================ */ /** * 使用<code>MessageFormat</code>格式化字符串. * * @param message 要格式化的字符串 * @param params 参数表 * * @return 格式化的字符串,如果message为<code>null</code>,则返回<code>null</code> */ public static String formatMessage(String message, Object[] params) { if ((message == null) || (params == null) || (params.length == 0)) { return message; } return MessageFormat.format(message, params); } /** * 使用<code>MessageFormat</code>格式化字符串. * * @param message 要格式化的字符串 * @param param1 参数1 * * @return 格式化的字符串,如果message为<code>null</code>,则返回<code>null</code> */ public static String formatMessage(String message, Object param1) { return formatMessage(message, new Object[] { param1 }); } /** * 使用<code>MessageFormat</code>格式化字符串. * * @param message 要格式化的字符串 * @param param1 参数1 * @param param2 参数2 * * @return 格式化的字符串,如果message为<code>null</code>,则返回<code>null</code> */ public static String formatMessage(String message, Object param1, Object param2) { return formatMessage(message, new Object[] { param1, param2 }); } /** * 使用<code>MessageFormat</code>格式化字符串. * * @param message 要格式化的字符串 * @param param1 参数1 * @param param2 参数2 * @param param3 参数3 * * @return 格式化的字符串,如果message为<code>null</code>,则返回<code>null</code> */ public static String formatMessage(String message, Object param1, Object param2, Object param3) { return formatMessage(message, new Object[] { param1, param2, param3 }); } /** * 使用<code>MessageFormat</code>格式化字符串. * * @param message 要格式化的字符串 * @param param1 参数1 * @param param2 参数2 * @param param3 参数3 * @param param4 参数4 * * @return 格式化的字符串,如果message为<code>null</code>,则返回<code>null</code> */ public static String formatMessage(String message, Object param1, Object param2, Object param3, Object param4) { return formatMessage(message, new Object[] { param1, param2, param3, param4 }); } /** * 使用<code>MessageFormat</code>格式化字符串. * * @param message 要格式化的字符串 * @param param1 参数1 * @param param2 参数2 * @param param3 参数3 * @param param4 参数4 * @param param5 参数5 * * @return 格式化的字符串,如果message为<code>null</code>,则返回<code>null</code> */ public static String formatMessage(String message, Object param1, Object param2, Object param3, Object param4, Object param5) { return formatMessage(message, new Object[] { param1, param2, param3, param4, param5 }); } } |
|||
ubuntu hadoop环境搭建资料集合 | ubuntu, hadoop | ||
Hadoop 官方资料:http://hadoop.apache.org/docs/r1.0.4/cn/quickstart.html Ubuntu jdk安装:http://freewxy.iteye.com/blog/882784 win7+eclipse+hadoop配置:http://www.cnblogs.com/huligong1234/p/4137133.html Ubuntu14.04下安装Hadoop2.4.0 (单机模式) http://www.cnblogs.com/kinglau/p/3794433.html Ubuntu14.04下安装Hadoop2.4.0 (伪分布模式) http://www.cnblogs.com/kinglau/p/3796164.html 伪分布模式下执行wordcount实例时报错解决办法 http://www.cnblogs.com/kinglau/p/3364928.html Eclipse下搭建Hadoop2.4.0开发环境 http://www.cnblogs.com/kinglau/p/3802705.html Hadoop学习三十:Win7 Eclipse调试Centos Hadoop2.2-Mapreduce http://zy19982004.iteye.com/blog/2024467 hadoop2.5.0 centOS系列 分布式的安装 部署 http://my.oschina.net/yilian/blog/310189 Centos6.5源码编译安装Hadoop2.5.1 http://www.myhack58.com/Article/sort099/sort0102/2014/54025.htm Hadoop MapReduce两种常见的容错场景分析 http://www.chinacloud.cn/show.aspx?id=15793&cid=17 hadoop 2.2.0集群安装 http://blog.csdn.net/bluishglc/article/details/24591185 Apache Hadoop 2.2.0 HDFS HA + YARN多机部署 http://blog.csdn.net/u010967382/article/details/20380387 Hadoop集群配置(最全面总结) http://blog.csdn.net/hguisu/article/details/7237395 Hadoop hdfs-site.xml 配置项清单 http://he.iori.blog.163.com/blog/static/6955953520138107638208/ http://slaytanic.blog.51cto.com/2057708/1101111 Hadoop三种安装模式 http://blog.csdn.net/liumm0000/article/details/13408855 |
|||
Dom4j解析带namespace的XML | java xml | ||
StringBuilder sourceSB = new StringBuilder("<root>").append(htmlText).append("</root>"); StringBuilder resultSB = new StringBuilder(""); try { Document doc = DocumentHelper.parseText(sourceSB.toString()); Element root = doc.getRootElement(); @SuppressWarnings("unchecked") List<Element> imgs = root.selectNodes("//img"); String src; for(Element img : imgs){ src = img.attribute("src").getText(); img.addAttribute("width", "" + getImageWidth(src)); img.attribute("src").setText(new StringBuilder(ContextUtils.getServerHost()).append(src).toString()); } resultSB.append(root.asXML()); resultSB.replace(0, "<root>".length(), ""); resultSB.replace(resultSB.lastIndexOf("</root>"), resultSB.length(), ""); |
|||
Java生成xml时设置编码 | java xml | ||
File xmlOutputFile = new File(xmlOutputPath); File parentDir = xmlOutputFile.getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); } //set xml encoding here. OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(xmlOutputFile),"utf-8"); StreamResult result = new StreamResult(osw); transformer.transform(source, result); |
|||
Java用AST解析java源码各种结构注解等 | java ast | ||
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.Javadoc; import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.NormalAnnotation; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.TypeDeclaration; public class JavaClassInfoPicker { private static final ASTParser PARSER = ASTParser.newParser(AST.JLS3); public static final String FILE_EXTENTION = ".java"; public static final String TEST_ANNOTATION_FULL_NAME = "org.junit.Test"; public static final String TEST_CASE_NAME_KEY = "getId"; public static final String TEST_CASE_DESC = "Desc"; public static final String TEST_CASE_DESC_NAME = "name"; public static final String TEST_CASE_DESC_FULL = "description"; public static final String TEST_CASE_DESC_PROJECT = "project"; public static final String TEST_CASE_DESC_MODULE = "module"; public static final String TEST_CASE_DESC_PRIORITY = "priority"; public static final String TEST_CASE_DESC_GROUPS = "groups"; public static final String TEST_ANNOTATION_NAME = "Test"; public static final String TEST_METHOD_MATCHES = "^test.*"; public static final String TEST_CASEID_MATCHES = "caseid"; public static List<TestClass> getClasses(String path) { List<File> files = getAllJavaFiles(new File(path)); List<TestClass> classes = new ArrayList<TestClass>(); try { for (File file : files) { classes.addAll(assambleClassInfo(file)); } } catch (IOException e) { throw new RuntimeException(e); } return classes; } public static List<TestClass> getMethods(String path) { List<File> files = getAllJavaFiles(new File(path)); List<TestClass> Methods = new ArrayList<TestClass>(); try { for (File file : files) { Methods.addAll(assambleMethodInfo(file)); } } catch (IOException e) { throw new RuntimeException(e); } return Methods; } private static List<TestClass> assambleMethodInfo(File javaFile) throws IOException { List<TestClass> testClasses = new ArrayList<TestClass>(); PARSER.setSource(FileUtils.readFileToString(javaFile, CharsetUtils.guessCharset(javaFile)) .toCharArray()); CompilationUnit result = (CompilationUnit) PARSER.createAST(null);// (org.eclipse.jdt.internal.core.CompilationUnit) if (result.types() == null || result.types().size() == 0) { return testClasses; } for (int i = 0; i < result.types().size(); i++) { Object clazz = result.types().get(i); if (!(clazz instanceof TypeDeclaration)) { continue; } TypeDeclaration typeDec = (TypeDeclaration) clazz; String packageName = result.getPackage() == null ? null : result.getPackage().getName() .getFullyQualifiedName(); String className = typeDec.getName().getFullyQualifiedName(); MethodDeclaration methods[] = typeDec.getMethods(); if (methods == null || methods.length == 0) { continue; } for (MethodDeclaration method : methods) { String name = method.getName().toString(); String javadoc = method.getJavadoc() == null ? "" : method.getJavadoc().toString(); List<?> methodModifiers = method.modifiers(); if (null == methodModifiers || methodModifiers.size() < 1) { continue; } TestClass testClass = new TestClass(packageName, className + "." + name, javadoc); appendTestClass(methodModifiers, testClass); if (StringUtils.isNotEmpty(testClass.getNickName())) { testClasses.add(testClass); } } } return testClasses; } @SuppressWarnings("unchecked") private static TestClass appendTestClass(List<?> methodModifiers, TestClass testClass) { for (int j = 0; j < methodModifiers.size(); j++) { Object object = methodModifiers.get(j); if (object instanceof NormalAnnotation && TEST_CASE_DESC.equals(getSimpleName(((NormalAnnotation) object).getTypeName() .getFullyQualifiedName()))) { NormalAnnotation caseNameAnotation = (NormalAnnotation) object; List<MemberValuePair> values = caseNameAnotation.values(); for (MemberValuePair value : values) { if (TEST_CASE_DESC_NAME.equals(value.getName().toString())) { testClass.setNickName(value.getValue().toString().replace("\"", "")); } else if (TEST_CASE_DESC_PROJECT.equals(value.getName().toString())) { testClass.setPrj(value.getValue().toString().replace("\"", "")); } } } } return testClass; } private static List<File> getAllJavaFiles(File file) { List<File> files = new ArrayList<File>(); if (file != null) { if (file.isDirectory()) { File[] listFiles = file.listFiles(); if (listFiles != null) { for (int i = 0; i < listFiles.length; i++) { files.addAll(getAllJavaFiles(listFiles[i])); } } } else { if (file.getName().toLowerCase().endsWith(FILE_EXTENTION)) { files.add(file); } } } return files; } @SuppressWarnings("unchecked") private static List<TestClass> assambleClassInfo(File javaFile) throws IOException { List<TestClass> testClasses = new ArrayList<TestClass>(); // PARSER.setSource(JavaCore.createCompilationUnitFrom(file.getFile())); PARSER.setSource(FileUtils.readFileToString(javaFile, CharsetUtils.guessCharset(javaFile)) .toCharArray()); // long currentTimeMillis = System.currentTimeMillis(); CompilationUnit result = (CompilationUnit) PARSER.createAST(null);// (org.eclipse.jdt.internal.core.CompilationUnit) // JavaCore.createCompilationUnitFrom(file.getFile());// // time += (System.currentTimeMillis() - currentTimeMillis); if (result.types() == null || result.types().size() == 0) { return testClasses; } for (int i = 0; i < result.types().size(); i++) { Object clazz = result.types().get(i); if (!(clazz instanceof TypeDeclaration)) { continue; } TypeDeclaration typeDec = (TypeDeclaration) clazz; Javadoc javadoc = typeDec.getJavadoc(); String packageName = result.getPackage() == null ? null : result.getPackage().getName() .getFullyQualifiedName(); TestClass testClass = new TestClass(packageName, typeDec.getName() .getFullyQualifiedName(), javadoc == null ? "" : javadoc.toString()); testClasses.add(testClass); List<?> typeModifiers = typeDec.modifiers(); appendTestClass(typeModifiers, testClass); if (StringUtils.isNotEmpty(testClass.getNickName())) {//已经取得用例名了,不用再检查getId方法了 continue; } // 从getId获取用例名称 MethodDeclaration methods[] = typeDec.getMethods(); if (methods == null || methods.length == 0) { continue; } // boolean hasModified = false; for (MethodDeclaration method : methods) { String name = method.getName().toString(); //从这里获取本测试类的用例名称 if (TEST_CASE_NAME_KEY.equals(name)) { List<Object> statements = method.getBody().statements(); for (int j = 0; j < statements.size(); j++) { Object obj = method.getBody().statements().get(j); if (obj instanceof ReturnStatement) { ReturnStatement object = (ReturnStatement) obj; testClass.setNickName(object.getExpression().toString() .replace("\"", "")); } } } } } return testClasses; } public static List<TestMethod> getWebUITestMethods(List<String> classContents) { List<TestMethod> methods = new ArrayList<TestMethod>(); for (String classContent : classContents) { methods.addAll(assambleWebUITestMethodInfo(classContent)); } return methods; } public static List<TestMethod> getApiTestMethods(List<String> classContents){ List<TestMethod> methods = new ArrayList<TestMethod>(); for (String classContent : classContents) { methods.addAll(assambleApiTestMethodInfo(classContent)); } return methods; } @SuppressWarnings("unchecked") private static List<TestMethod> assambleWebUITestMethodInfo(String classContent){ List<TestMethod> testMethods = new ArrayList<TestMethod>(); if(org.apache.commons.lang.StringUtils.isNotBlank(classContent)){ PARSER.setSource(classContent.toCharArray()); CompilationUnit result = (CompilationUnit) PARSER.createAST(null); if(CollectionUtils.isEmpty(result.types())) { return testMethods; } for (int i = 0; i < result.types().size(); i++) { Object clazz = result.types().get(i); if (!(clazz instanceof TypeDeclaration)) { continue; } TypeDeclaration typeDec = (TypeDeclaration) clazz; String packageName = result.getPackage() == null ? null : result.getPackage().getName() .getFullyQualifiedName(); String className = typeDec.getName().getFullyQualifiedName(); MethodDeclaration methods[] = typeDec.getMethods(); if (methods == null || methods.length == 0) { continue; } for (MethodDeclaration method : methods) { String name = method.getName().toString(); String javadoc = method.getJavadoc() == null ? "" : method.getJavadoc().toString(); String caseId = getModifiersCaseId(method.modifiers()); if(isTestMethod(method)){ List<?> methodModifiers = method.modifiers(); TestMethod testMethod = new TestMethod(packageName, name, javadoc,TestMethod.JAVA_SCRIPT); testMethod.setClassName(className); testMethod.setCaseId(caseId); appendTestMethod(methodModifiers, testMethod); if(StringUtils.isBlank(testMethod.getNickName())){ testMethod.setNickName(testMethod.getName()); } testMethods.add(testMethod); } } } } return testMethods; } @SuppressWarnings("unchecked") public static List<TestMethod> assambleApiTestMethodInfo(String classContent){ List<TestMethod> testMethods = new ArrayList<TestMethod>(); if(org.apache.commons.lang.StringUtils.isNotBlank(classContent)){ PARSER.setSource(classContent.toCharArray()); CompilationUnit result = (CompilationUnit) PARSER.createAST(null); if (CollectionUtils.isEmpty(result.types())) { return testMethods; } for (int i = 0; i < result.types().size(); i++) { Object clazz = result.types().get(i); if (!(clazz instanceof TypeDeclaration)) { continue; } TypeDeclaration typeDec = (TypeDeclaration) clazz; String packageName = result.getPackage() == null ? null : result.getPackage().getName() .getFullyQualifiedName(); String className = typeDec.getName().getFullyQualifiedName(); MethodDeclaration methods[] = typeDec.getMethods(); if (methods == null || methods.length == 0) { continue; } for (MethodDeclaration method : methods) { boolean isTestMethod=false; isTestMethod=isTestMethod(method); String name = method.getName().toString(); if(!isTestMethod){ isTestMethod=name.matches(TEST_METHOD_MATCHES); } if(isTestMethod){ String javadoc = method.getJavadoc() == null ? "" : method.getJavadoc().toString(); String caseId = getModifiersCaseId(method.modifiers()); String groups = getAnnotationGroups(TEST_CASE_DESC, method.modifiers()); TestMethod testMethod = new TestMethod(packageName, name, name,javadoc,TestMethod.JAVA_SCRIPT); testMethod.setClassName(className); testMethod.setCaseId(caseId); testMethod.setGroups(groups); testMethods.add(testMethod); } } } } return testMethods; } private static String getModifiersCaseId(List<Object> modifiers){ String caseId = ""; if(org.apache.commons.collections.CollectionUtils.isNotEmpty(modifiers)){ for (Object object : modifiers) { if(object instanceof NormalAnnotation){ NormalAnnotation caseNameAnotation = (NormalAnnotation) object; String annotationName = getSimpleName(caseNameAnotation.getTypeName().getFullyQualifiedName()); if(TEST_ANNOTATION_NAME.equals(annotationName)){ @SuppressWarnings("unchecked") List<MemberValuePair> values = caseNameAnotation.values(); for(MemberValuePair v : values){ if(TEST_CASEID_MATCHES.equals(v.getName().toString())){ caseId = v.getValue().toString().replace("{", "").replace("}", "").replaceAll("\"", ""); } } } } } } return caseId; } private static String getAnnotationGroups(String annotationName, List<Object> modifiers) { return getAnnotationValueByKey(annotationName, TEST_CASE_DESC_GROUPS, modifiers); } private static String getAnnotationValueByKey(String annotationName, String key, List<Object> modifiers) { if (CollectionUtils.isNotEmpty(modifiers) && StringUtils.isNotEmpty(annotationName) && StringUtils.isNotEmpty(key)) { for (Object object : modifiers) { if(object instanceof NormalAnnotation){ NormalAnnotation normalAnnotation = (NormalAnnotation) object; String annotationSimpleName = getSimpleName(normalAnnotation.getTypeName().getFullyQualifiedName()); if(annotationName.equals(annotationSimpleName)){ @SuppressWarnings("unchecked") List<MemberValuePair> memberValuePairs = normalAnnotation.values(); for(MemberValuePair memberValuePair : memberValuePairs){ if(key.equals(memberValuePair.getName().toString())){ return memberValuePair.getValue().toString().replace("{", "").replace("}", "").replaceAll("\"", ""); } } } } } } return ""; } private static boolean isTestMethod(MethodDeclaration method){ List<?> methodModifiers = method.modifiers(); if(org.apache.commons.collections.CollectionUtils.isNotEmpty(methodModifiers)){ for (Object object : methodModifiers) { if(object instanceof Annotation){ Annotation annotation = (Annotation)object; String annotationName = getSimpleName(annotation.getTypeName().getFullyQualifiedName()); if(TEST_ANNOTATION_NAME.equals(annotationName)){ return true; } } } } return false; } @SuppressWarnings("unchecked") private static TestMethod appendTestMethod(List<?> methodModifiers, TestMethod testMethod) { NormalAnnotation caseNameAnotation=null; NormalAnnotation testAnotation=null; for (int j = 0; j < methodModifiers.size(); j++) { Object object = methodModifiers.get(j); if (object instanceof NormalAnnotation) { NormalAnnotation annotation = (NormalAnnotation)object; String annotationName = getSimpleName(annotation.getTypeName().getFullyQualifiedName()); if(TEST_CASE_DESC.equals(annotationName)){ caseNameAnotation=annotation; }else if(TEST_ANNOTATION_NAME.equals(annotationName)){ testAnotation=annotation; } } } if(caseNameAnotation!=null){ List<MemberValuePair> values = caseNameAnotation.values(); for (MemberValuePair value : values) { String name = value.getName().toString().trim(); String val = value.getValue().toString().trim().replace("\"", "").replace("{", "").replace("}", ""); if (TEST_CASE_DESC_NAME.equals(name)) { testMethod.setNickName(val); } else if (TEST_CASE_DESC_MODULE.equals(name)) { testMethod.setModule(val); } else if (TEST_CASE_DESC_PRIORITY.equals(name)) { testMethod.setPriority(val); } else if (TEST_CASE_DESC_GROUPS.equals(name)) { testMethod.setGroups(val); } } }else if(testAnotation!=null){ List<MemberValuePair> values = testAnotation.values(); for (MemberValuePair value : values) { String name = value.getName().toString().trim(); String val = value.getValue().toString().trim().replace("\"", ""); if (TEST_CASE_DESC_FULL.equals(name)) { testMethod.setNickName(val); break; } } } return testMethod; } private static String getSimpleName(String name) { if (name == null || !name.contains(".")) return name; return name.substring(name.lastIndexOf(".") + 1); } } |
|||
Java解析Groovy测试类(输入文本解析标签) | java | ||
import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class GroovyClassInfoPicker { private static final String PACKAGE_KEY="package"; private static final String CLASS_KEY="class"; private static final String PUBLIC_KEY="public"; private static final String PRIVATE_KEY="private"; private static final String PROTECTED_KEY="protected"; private static final String DEF_KEY="def"; private static final String EXTENDS_KEY="extends"; private static final String TEST_ANNOTATION="@Test"; private static final String DESC_KEY="description"; private static final String GROUP_KEY = "groups"; private static final String VOID_KEY="void"; public static List<TestMethod> getWebUITestMethods(Collection<ByteArrayOutputStream> byteArrayOutputStreams){ List<TestMethod> testMethods = new ArrayList<TestMethod>(); for (ByteArrayOutputStream byteArrayOutputStream : byteArrayOutputStreams) { testMethods.addAll(getWebUITestMethods(byteArrayOutputStream)); } return testMethods; } public static List<TestMethod> getWebUITestMethods(ByteArrayOutputStream byteArrayOutputStream){ byte bytes[]=byteArrayOutputStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes); return getWebUITestMethods(inputStream); } public static List<TestMethod> getWebUITestMethods(InputStream inputStream){ List<TestMethod> testMethods = new ArrayList<TestMethod>(); String charsetName = CharsetUtils.guessCharset(inputStream,false); BufferedReader bufferedReader=null; String packageName=null; String className=null; TestMethod testMethod = null; try { inputStream.reset(); bufferedReader= new BufferedReader(new InputStreamReader(inputStream,charsetName)); String line=bufferedReader.readLine(); while (line!=null) { if(StringUtils.isBlank(className)){ if(StringUtils.isBlank(packageName)){ packageName=getPackageName(line); } className=getClassName(line); }else{ if(isTestAnnotation(line)){ testMethod = new TestMethod(packageName,className,TestMethod.GROOVY_SCRIPT); setNickname(line, testMethod); String[] groupAttribute = getTestAnnotationGroups(line); testMethod.setGroups(null == groupAttribute ? "" : groupAttribute[1]); } else if(testMethod!=null) { setName(line, testMethod); } } if(testMethod!=null&&StringUtils.isNotBlank(testMethod.getName())){ if(StringUtils.isBlank(testMethod.getNickName())){ testMethod.setNickName(testMethod.getName()); } testMethods.add(testMethod); testMethod=null; } line=bufferedReader.readLine(); } } catch (Exception e) { e.printStackTrace(); }finally{ if(bufferedReader!=null){ try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } return testMethods; } private static String getPackageName(String line){ String packageName = ""; line=line.trim(); if(StringUtils.startsWith(line, PACKAGE_KEY)){ packageName=StringUtils.substring(line, PACKAGE_KEY.length()); packageName=StringUtils.remove(packageName, ";"); packageName=StringUtils.trim(packageName); } return packageName; } private static String getClassName(String line){ String className = ""; line=StringUtils.trim(line); if(StringUtils.startsWith(line, PRIVATE_KEY)){ line=StringUtils.substring(line, PRIVATE_KEY.length()); line=StringUtils.trim(line); } if(StringUtils.startsWith(line, PUBLIC_KEY)){ line=StringUtils.substring(line, PUBLIC_KEY.length()); line=StringUtils.trim(line); } if(StringUtils.startsWith(line, PROTECTED_KEY)){ line=StringUtils.substring(line, PROTECTED_KEY.length()); line=StringUtils.trim(line); } if(StringUtils.startsWith(line, CLASS_KEY)){ className=StringUtils.substring(line, CLASS_KEY.length()); className=className.split(EXTENDS_KEY)[0]; className=StringUtils.remove(className, "{"); className=StringUtils.trim(className); } return className; } private static boolean isTestAnnotation(String line){ boolean isTestAnnotation= false; line=StringUtils.trim(line); isTestAnnotation=StringUtils.startsWith(line, TEST_ANNOTATION); return isTestAnnotation; } private static void setNickname(String line,TestMethod method){ line = StringUtils.trim(line); line = StringUtils.substring(line, TEST_ANNOTATION.length()); line = StringUtils.trim(line); if (StringUtils.isNotBlank(line)) { line = StringUtils.substring(line, 1, line.length() - 1); String attributes[] = StringUtils.split(line, ","); for (String attribut : attributes) { String str[] = StringUtils.split(attribut, "="); if (str.length == 2) { String key = str[0].trim(); if (DESC_KEY.equals(key)) { String value = str[1]; value = StringUtils.remove(value, "\""); method.setNickName(value); break; } } } } } private static String[] getTestAnnotationGroups(String line) { if (StringUtils.isNotBlank(line)) { int keyIndex = line.indexOf(GROUP_KEY); if(keyIndex != -1){ int left = line.indexOf("[", keyIndex); int right = line.indexOf("]", keyIndex); if((left != -1) && (right != -1)){ try{ String value = line.substring(left+1, right); value = StringUtils.remove(value, "\""); return new String[]{GROUP_KEY, value}; }catch(Exception e){ } } return getTestAnnotationAttribute(line, GROUP_KEY); } } return null; } private static String[] getTestAnnotationAttribute(String line, String key) { line = StringUtils.trim(line); line = StringUtils.substring(line, TEST_ANNOTATION.length()); line = StringUtils.trim(line); if (StringUtils.isNotBlank(line)) { line = StringUtils.substring(line, 1, line.length() - 1); String attributes[] = StringUtils.split(line, ","); for (String attribute : attributes) { String str[] = StringUtils.split(attribute, "="); if (str.length == 2) { String currentKey = str[0].trim(); if (key.equals(currentKey)) { str[1] = StringUtils.remove(str[1], "\""); return str; } } } } return null; } private static void setName(String line,TestMethod method){ String name = ""; line=StringUtils.trim(line); if(StringUtils.startsWith(line, PRIVATE_KEY)){ line=StringUtils.substring(line, PRIVATE_KEY.length()); line=StringUtils.trim(line); } if(StringUtils.startsWith(line, PUBLIC_KEY)){ line=StringUtils.substring(line, PUBLIC_KEY.length()); line=StringUtils.trim(line); } if(StringUtils.startsWith(line, PROTECTED_KEY)){ line=StringUtils.substring(line, PROTECTED_KEY.length()); line=StringUtils.trim(line); } if(StringUtils.startsWith(line, DEF_KEY)){ line=StringUtils.substring(line, DEF_KEY.length()); line=StringUtils.trim(line); } if(StringUtils.startsWith(line, VOID_KEY)){ line=StringUtils.substring(line, VOID_KEY.length()); name=StringUtils.trim(line); } if(StringUtils.isNotBlank(name)){ name = StringUtils.split(name, "(")[0].trim(); method.setName(name); } } } |
|||
java发送邮件(不带图片的) | java email | ||
import java.io.UnsupportedEncodingException; import java.security.Security; import java.text.MessageFormat; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; /** * 发送邮件的工具类 * 发送邮件失败,是否抛出异常,一般来说,不要阻断主流程 * */ @SuppressWarnings("restriction") public class EmailUtils { private static final Log logger = LogFactory .getLog(EmailUtils.class); private final static JavaMailSenderImpl sender = new JavaMailSenderImpl(); private final static String DEFAULT_FROM = "aqc@alipay.com"; private static final String SEPRETOR = "<br />"; private static final String CLIENT_ABORT_EXCEPTION = "clientabortexception"; /** * 调用阿里云smtp邮箱发送邮件 */ private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; private final static Session session; static { // 邮件配置项 Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = System.getProperties(); props.setProperty("mail.smtp.host", "smtp.alibaba-inc.com"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); final String username = "aqc@alipay.com"; final String password = PropertyUtils.getProperty("email.password","auto_pwd*123"); session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } private EmailUtils() { //单例模式 } /** * 只能用来发送text格式的html邮件 * @param to * @param subject * @param content * @throws MessagingException */ public static void sendSimpleMailMessage(String subject, String content, boolean isHtml) throws MessagingException { String receivers = PropertyUtils.getProperty("error.email.receivers", defaultCc); sendSimpleMailMessage(receivers.split(","), null, subject, content, isHtml); } public static void sendSimpleMailMessage(String[] to, String[] cc, String subject, String content, boolean isHtml) throws MessagingException { sendSimpleMailMessage(to, cc, DEFAULT_FROM, subject, content, isHtml); } /** * * 发送邮件 * @param to 发送者列表 * @param cc 抄送者列表 * @param from 发送者 * @param subject 主题 * @param content 内容(支持Text/HTML) * @param isHtml 该属性废弃 * @throws MessagingException * @throws UnsupportedEncodingException */ public static void sendSimpleMailMessage(String[] to, String[] cc, String from, String subject, String content, boolean isHtml) throws MessagingException { Message message = new MimeMessage(session); message.setSubject(transferChinese(subject)); logger.info(MessageFormat.format("发送邮件主题{0}", subject)); //设置源地址 InternetAddress addressFrom = new InternetAddress(from); message.setFrom(addressFrom); //设置目的地址 InternetAddress[] addressesTo = null; if (to != null && to.length > 0) { addressesTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { InternetAddress addressTo = new InternetAddress(to[i]); addressesTo[i] = addressTo; } message.addRecipients(Message.RecipientType.TO, addressesTo); } // 设置抄送的地址 InternetAddress[] addressesCC = null; if (cc != null && cc.length > 0) { addressesCC = new InternetAddress[cc.length]; for (int i = 0; i < cc.length; i++) { InternetAddress addressCc = new InternetAddress(cc[i]); addressesCC[i] = addressCc; } message.addRecipients(Message.RecipientType.CC, addressesCC); } // 邮件内容 Multipart mp = new MimeMultipart(); MimeBodyPart mbpContent = new MimeBodyPart(); // 邮件格式 mbpContent.setContent(content, "text/html; charset=UTF-8"); mp.addBodyPart(mbpContent); message.setContent(mp); message.setSentDate(new Date()); // 发送邮件 Transport.send(message); } /** * 发邮件 * 2009-10-15 * @param throwable */ public static void sendMessage(Throwable throwable, boolean isHtml) { if (throwable == null) { return; } String title = throwable.toString(); sendMessage(title, throwable, isHtml); } public static final String defaultCc = "fuqu.lgd@alibaba-inc.com,guoqing.ji@alipay.com"; /** * 发邮件 * @author fuqu * 2009-10-15 * @param throwable */ public static void sendMessage(String title, Throwable throwable, boolean isHtml) { if(!ContextUtils.isDevEnv()){ String receivers = PropertyUtils.getProperty("error.email.receivers", defaultCc); sendMessage(title, throwable, isHtml, receivers.split(","), defaultCc.split(",")); } } /** * 发邮件 * 2009-10-15 * @param throwable */ public static void sendMessage(String title, Throwable throwable, boolean isHtml, String[] to, String[] cc) { if (title != null && title.toLowerCase().contains(CLIENT_ABORT_EXCEPTION)) { return; } try { HttpServletRequest request = ContextUtils.getRequest(); StringBuilder content = new StringBuilder(10000); content.append(getUserInfo(request)); content.append(getRequestInfo(request)); ExceptionUtils.appendStackTrace(content, throwable); sendSimpleMailMessage(to, cc, DEFAULT_FROM, title, content.toString(), false); } catch (Exception e) {//这里不能再抛异常 logger.error(e); } } private static String getRequestInfo(HttpServletRequest request) { if(request!=null){ StringBuilder requestInfo = new StringBuilder("server: ").append(request.getServerName()).append(":").append(request.getServerPort()).append(SEPRETOR) .append("url: ").append(request.getContextPath()).append(request.getServletPath()).append(SEPRETOR) .append("parameters: ").append(ParameterParser.getParametersMapExcept(null, request)).append(SEPRETOR); return requestInfo.toString(); }else{ return ""; } } /** * 获得登录人Id * Apr 27, 2009 */ private static String getUserInfo(HttpServletRequest request) { if(request!=null){ StringBuilder userInfo = new StringBuilder("当前操作者信息:"); userInfo.append(SEPRETOR); String ip = request.getHeader("X-Real-IP"); if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("x-forwarded-for") ; } if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } userInfo.append("用户IP:").append(ip).append(SEPRETOR); HttpSession session = request.getSession(false); if (session != null) { User user = (User) session.getAttribute("currentUser"); if (user != null) { userInfo.append("用户旺旺:").append(user.getWangWang()).append(SEPRETOR); } } return userInfo.toString(); }else{ return ""; } } /** * 除了from属性之外,所有属性自己设置 * @param helper */ public static boolean sendMimeMessage(MimeMessageHelper helper) { if (null != helper) { try { String from = DEFAULT_FROM; helper.setFrom(from);//发送者别名 sender.send(helper.getMimeMessage()); } catch (Exception e) { throw new BusinessException(e); } } return true; } public static void main(String[] args) throws MessagingException { String[] to = { "aa@163.com" }; String[] cc = null; sendSimpleMailMessage(to, cc, "系统通知", "系统通知", false); } private static String transferChinese(String strText) { String ret = ""; try { ret = MimeUtility.encodeText(new String(strText.getBytes("GBK"), "GBK"), "GBK", "B"); } catch (Exception e) { } return ret; } } |
|||
Java判断文件的编码 | java charset | ||
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class CharsetUtils { //f用于猜编码 public static String guessCharset(File file) { String charset = "GBK"; try { charset=guessCharset(new FileInputStream(file)); } catch (FileNotFoundException e) { } return charset; } public static String guessCharset(InputStream inputStream){ return guessCharset(inputStream, true); } public static String guessCharset(InputStream inputStream,boolean isAutoClose) { String charset = "GBK"; byte[] first3Bytes = new byte[3]; BufferedInputStream bis = null; try { boolean checked = false; bis = new BufferedInputStream(inputStream); bis.mark(0); int read = bis.read(first3Bytes, 0, 3); if (read == -1) return charset; if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) { charset = "UTF-16LE"; checked = true; } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) { charset = "UTF-16BE"; checked = true; } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF) { charset = "UTF-8"; checked = true; } bis.reset(); if (!checked) { // int len = 0; //int loc = 0; while ((read = bis.read()) != -1) { //loc++; if (read >= 0xF0) break; if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK break; if (0xC0 <= read && read <= 0xDF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF) // (0x80 // - 0xBF),也可能在GB编码内 continue; else break; } else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小 read = bis.read(); if (0x80 <= read && read <= 0xBF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) { charset = "UTF-8"; break; } else break; } else break; } } // System.out.println( loc + " " + Integer.toHexString( read ) // ); } } catch (Exception e) { return "UTF-8"; }finally{ if(isAutoClose){ try { bis.close(); } catch (Exception e) { } } } return charset; } public static InputStreamReader getInputStreamReader(InputStream inputIntream) throws IOException { String charset = "GBK"; byte[] first3Bytes = new byte[3]; BufferedInputStream bis = null; boolean checked = false; bis = new BufferedInputStream(inputIntream); bis.mark(0); int read = bis.read(first3Bytes, 0, 3); if (read == -1){ bis.reset(); return new InputStreamReader(bis,charset); } if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) { charset = "UTF-16LE"; checked = true; } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) { charset = "UTF-16BE"; checked = true; } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF) { charset = "UTF-8"; checked = true; } bis.reset(); if (!checked) { // int len = 0; //int loc = 0; while ((read = bis.read()) != -1) { //loc++; if (read >= 0xF0) break; if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK break; if (0xC0 <= read && read <= 0xDF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF) // (0x80 // - 0xBF),也可能在GB编码内 continue; else break; } else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小 read = bis.read(); if (0x80 <= read && read <= 0xBF) { read = bis.read(); if (0x80 <= read && read <= 0xBF) { charset = "UTF-8"; break; } else break; } else break; } } } bis.reset(); return new InputStreamReader(bis,charset); } } |
|||
Java给图片加水印 | java image | ||
import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; /** * 图片处理工具类,用于处理图片添加水印等功能 */ public class ImageUtils { /** * 在图片指定位置画一个矩形框,并填写文字 * * @param srcImagePath 原图地址 * @param toPath 输出图片地址 * @param inputText 需要填写的文字 * @param x 位置坐标X * @param y 位置坐标Y * @throws IOException */ public static void drawPolygon(String srcImagePath,String toPath,String inputText,int x,int y) throws IOException { int[] xPoints = {x-20,x+20,x+20,x-20,x-20}; int[] yPoints = {y-20,y-20,y+20,y+20,y-20}; int nPoints = 5; FileOutputStream fos = null; try { //获取图片 BufferedImage image = ImageIO.read(new File(srcImagePath)); //根据xy点坐标绘制闭合多边形 Graphics2D g2d = image.createGraphics(); g2d.setColor(Color.RED); g2d.drawPolygon(xPoints, yPoints, nPoints); g2d.drawString(inputText,x-10,y); //输入水印文字及其起始x、y坐标 fos = new FileOutputStream(toPath); ImageIO.write(image, "jpg", fos); g2d.dispose(); } catch (Exception e) { }finally{ if(fos!=null){ fos.close(); } } } } |
|||
Java zip压缩解压缩 | java zip | ||
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.apache.tools.zip.ZipOutputStream; public class ZipFileUtils { /** * 能支持中文的压缩 * 参数base 开始为"" * first 开始为true */ private static void doZip(ZipOutputStream out, File f, String base, boolean first) throws Exception { if (first) { if (f.isDirectory()) { base = base + f.getName(); } else { base = f.getName(); } } if (f.isDirectory()) { File[] fl = f.listFiles(); base = base + "/"; for (int i = 0; i < fl.length; i++) { doZip(out, fl[i], base + fl[i].getName(), false); } } else { out.putNextEntry(new ZipEntry(base)); FileInputStream in = new FileInputStream(f); int b; //System.out.println(base); while ((b = in.read()) != -1) { out.write(b); } in.close(); } } /** * 解压文件 * unZip为解压路径 */ private static void doUnZip(ZipFile zipFile, String unZipRoot) throws Exception, IOException { java.util.Enumeration<?> e = zipFile.getEntries(); ZipEntry zipEntry; while (e.hasMoreElements()) { zipEntry = (ZipEntry) e.nextElement(); InputStream fis = zipFile.getInputStream(zipEntry); if (zipEntry.isDirectory()) { // TODO } else { File file = new File(unZipRoot + File.separator + zipEntry.getName()); File parentFile = file.getParentFile(); parentFile.mkdirs(); FileOutputStream fos = new FileOutputStream(file); byte[] b = new byte[1024]; int len; while ((len = fis.read(b, 0, b.length)) != -1) { fos.write(b, 0, len); } fos.close(); fis.close(); } } } public static void zipFile(String zipToFile, String toBeZip) throws Exception { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipToFile)); out.setEncoding("gbk");//TODO 只能写死GBK? File inputFile = new File(toBeZip); doZip(out, inputFile, "", true); //System.out.println("zip done"); out.close(); } public static void unZipFile(String zipFilePath, String unZipToDir) throws Exception { ZipFile zipFile = new ZipFile(zipFilePath); doUnZip(zipFile, unZipToDir); //System.out.println("unZip Ok"); } public static void unZipFileFlat(String zipFilePath, String unZipToDir) throws Exception { ZipFile zipFile = new ZipFile(zipFilePath); java.util.Enumeration<?> e = zipFile.getEntries(); ZipEntry zipEntry; while (e.hasMoreElements()) { zipEntry = (ZipEntry) e.nextElement(); InputStream fis = zipFile.getInputStream(zipEntry); if (zipEntry.isDirectory()) { // TODO } else { String name = zipEntry.getName(); int index = zipEntry.getName().lastIndexOf(File.separator); if (index != -1) { name = zipEntry.getName().substring(index); } File file = new File(unZipToDir + name); File parentFile = file.getParentFile(); parentFile.mkdirs(); FileOutputStream fos = new FileOutputStream(file); byte[] b = new byte[1024]; int len; while ((len = fis.read(b, 0, b.length)) != -1) { fos.write(b, 0, len); } fos.close(); fis.close(); } } } public static void main(String[] args) throws Exception { zipFile("d:/工作常用.zip", "D:\\temp"); // unZipFile("d:/javaFile.zip","e:/"); } |
|||
Java操作svn下载更新代码等 | java svn | ||
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.tmatesoft.svn.core.SVNAuthenticationException; import org.tmatesoft.svn.core.SVNDepth; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.wc.ISVNOptions; import org.tmatesoft.svn.core.wc.SVNClientManager; import org.tmatesoft.svn.core.wc.SVNDiffClient; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNStatus; import org.tmatesoft.svn.core.wc.SVNStatusClient; import org.tmatesoft.svn.core.wc.SVNStatusType; import org.tmatesoft.svn.core.wc.SVNUpdateClient; import org.tmatesoft.svn.core.wc.SVNWCUtil; public class SvnUtils { private static final ISVNOptions options = SVNWCUtil.createDefaultOptions(true); private static String TEMP_DIR_NAME = "/tmp"; static { // 初始化支持http://协议的库。 必须先执行此操作。 DAVRepositoryFactory.setup(); } public static List<String> getChangeFiles(String url1,long revision1,String url2,long revision2,String userName,String password) { try{ SVNURL newUrl = SVNURL.parseURIEncoded(url1); SVNURL oldUrl = SVNURL.parseURIEncoded(url2); SVNRevision newRevision = SVNRevision.create(revision1); SVNRevision oldRevision = SVNRevision.create(revision2); // 实例化客户端管理类 SVNClientManager clientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, userName, password); // 获得SVNDiffClient类的实例。 SVNDiffClient diffClient = clientManager.getDiffClient(); File parentDir = new File(TEMP_DIR_NAME); if(!parentDir.exists()){ parentDir.mkdirs(); } //revision1-revision2_diff.txt String fileName = TEMP_DIR_NAME + File.separator + revision1+"-"+revision2+"_diff.txt"; File resultFile = new File(fileName); if (resultFile.exists()){ FileUtils.deleteFile(resultFile); } // 保存比较结果的输出流 BufferedOutputStream result = null; try{ result = new BufferedOutputStream(new FileOutputStream(resultFile)); // 比较compFile文件的SVNRevision.WORKING版本和 // SVNRevision.HEAD版本的差异,结果保存在E:/result.txt文件中。 diffClient.doDiff(oldUrl, oldRevision, newUrl, newRevision, SVNDepth.INFINITY, true, result); }finally{ if(result!=null) result.close(); } List<String> readChangeFileNames = readChangeFileNames(resultFile); FileUtils.deleteFile(resultFile); return readChangeFileNames; }catch (SVNAuthenticationException e) { throw new BusinessException("用户"+userName+"无权访问您请求的SVN地址,请确认用户名密码是否正确"); } catch (Exception e) { throw new UnknownException(e); } } private static final String PRE_FIX = "Index:"; //private static final String SUF_FIX = ".java"; private static List<String> readChangeFileNames(File diffFile) { BufferedReader br = null; try { List<String> changeFiles = new ArrayList<String>(); br = new BufferedReader(new InputStreamReader(new FileInputStream( diffFile))); String line = br.readLine(); while (line != null) { //后缀先不判断,因为不知道调用者要关注的是什么 if (line.startsWith(PRE_FIX) /*&& line.endsWith(SUF_FIX)*/) { changeFiles.add(getFileName(line)); } line = br.readLine(); } return changeFiles; } catch (Exception e) { // ignore return null; } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } } private static String getFileName(String fileName) { if (fileName.contains("/")) { return fileName.substring(fileName.lastIndexOf("/") + 1); } else { return fileName.replace(PRE_FIX, "").trim(); } } /** * 返回当前工作目录的版本号 * @author fuqu * @param rootDir 应用的工作目录 * @return */ public static long getWorkingVersion(File rootDir,String userName, String password) { // 实例化客户端管理类 SVNClientManager clientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, userName, password); SVNStatus doStatus; try { doStatus = clientManager.getStatusClient().doStatus(rootDir, false); } catch (SVNException e) { throw new UnknownException("目录中不包含.svn文件夹,无法解析出版本号与URL"); } return doStatus.getRevision().getNumber(); } /** * 返回当前工作目录的SVN url * @author fuqu * @param rootDir 应用的工作目录 * @param decoded 是否需要对路径进行解码 * @return */ public static String getWorkingSvnUrl(File rootDir,boolean decoded ,String userName, String password) { SVNClientManager clientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, userName, password); SVNStatus doStatus; try { doStatus = clientManager.getStatusClient().doStatus(rootDir, false); } catch (SVNException e) { throw new UnknownException("目录中不包含.svn文件夹,无法解析出版本号与URL"); } SVNURL url = doStatus.getURL(); if(decoded){ return url.toDecodedString(); }else{ return url.toString(); } } public static long checkout(String svnUrl, String svnVersion, String distPath, String userName, String password){ try{ SVNClientManager clientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, userName, password); SVNURL repositoryURL = SVNURL.parseURIEncoded(svnUrl); // 通过客户端管理类获得updateClient类的实例。 SVNUpdateClient updateClient = clientManager.getUpdateClient(); //sets externals not to be ignored during the checkout updateClient.setIgnoreExternals(true); File distDir = new File(distPath); if(!distDir.exists()){ distDir.mkdirs(); } SVNRevision version ; if (StringUtils.isEmpty(svnVersion) ){ version = SVNRevision.HEAD; } else { version = SVNRevision.parse(svnVersion); } // 执行check out 操作,返回工作副本的版本号。 return updateClient.doCheckout(repositoryURL, distDir,SVNRevision.HEAD, version, SVNDepth.INFINITY,false); }catch (SVNAuthenticationException e) { throw new BusinessException(String.format("用户:%s/%s无权访问您请求的SVN地址:%s,请确认用户名密码是否正确", userName==null?"":userName, password==null?"":password, svnUrl),e); } catch (Exception e) { throw new UnknownException(e); } } public static long checkout(String svnUrl, String distPath, String userName, String password){ return checkout( svnUrl, "", distPath, userName, password); } /** * add by zhj * * @param svnFilePath * @param commitMessage * @param userName * @param password * @return */ public static boolean commit(String svnFilePath, String commitMessage, String userName, String password){ try{ SVNClientManager clientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, userName, password); // 通过客户端管理类获得statusClient类的实例。 SVNStatusClient statusClient = clientManager.getStatusClient(); File commitFile = new File(svnFilePath); SVNStatus svnStatus = statusClient.doStatus(commitFile, false); if (svnStatus.getContentsStatus() == SVNStatusType.STATUS_UNVERSIONED||svnStatus.getContentsStatus() == SVNStatusType.STATUS_NONE) { clientManager.getWCClient().doAdd(commitFile, false, false, false, SVNDepth.INFINITY, false, false);; } clientManager.getCommitClient().doCommit(new File[] { commitFile }, true, commitMessage, null, null, false, false, SVNDepth.INFINITY); return true; }catch (SVNAuthenticationException e) { throw new BusinessException(String.format("用户:%s/%s无权访问您请求的SVN地址,请确认用户名密码是否正确", userName==null?"":userName, password==null?"":password),e); } catch (Exception e) { throw new UnknownException(e); } } /** * add by zhj * * @param svnFilePath * @param commitMessage * @param userName * @param password * @return */ public static boolean delete(String svnFilePath, String commitMessage, String userName, String password) { try{ SVNClientManager clientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, userName, password); File commitFile = new File(svnFilePath); clientManager.getWCClient().doDelete(commitFile, false, false); clientManager.getCommitClient().doCommit(new File[] { commitFile }, true, commitMessage, null, null, false, false, SVNDepth.INFINITY); return true; }catch (SVNAuthenticationException e) { throw new BusinessException(String.format("用户:%s/%s无权访问您请求的SVN地址,请确认用户名密码是否正确", userName==null?"":userName, password==null?"":password),e); } catch (Exception e) { throw new UnknownException(e); } } /** * add by zhj * * @param svnFilePath * @param userName * @param password * @return */ public static long update(String svnFilePath, String userName, String password) { try{ SVNClientManager clientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, userName, password); File commitFile = new File(svnFilePath); SVNUpdateClient updateClient = clientManager.getUpdateClient(); updateClient.setIgnoreExternals(false); long versionNum = updateClient.doUpdate(commitFile, SVNRevision.HEAD, SVNDepth.INFINITY, false, false); return versionNum; }catch (SVNAuthenticationException e) { throw new BusinessException(String.format("用户:%s/%s无权访问您请求的SVN地址,请确认用户名密码是否正确", userName==null?"":userName, password==null?"":password),e); } catch (Exception e) { throw new UnknownException(e); } } public static void main(String[] args) throws Exception { String url = "http://www.baidu.com/svn/repo/myproject"; // long ll = checkout(url,"d:\\abc","", "" ); long ll = checkout(url,"74200","d:\\ab11c","", "" ); System.out.println(ll); // String url = "http://sources.alipay.net/svn/lab/lab/script/Script/1111/"; // long ll = checkout(url,"","d:\\1111","techtestteam", "techtest@team" ); // System.out.println(ll); // if(commit("d:\\1111","test","techtestteam","techtest@team")) // System.out.println("commit success"); // System.out.println(update("d:\\1111\\zhj.txt","techtestteam","techtest@team")); } |
|||
远程执行windows cmd命令(使用socket和telnet) | java windows, java telnet | ||
//TelnetClient是Apache common包中的:org.apache.commons.net.telnet.TelnetClient public static void restartWebUIRunnerOS(String remoteIp, String user, String password) throws Exception { boolean executeCommand = executeCommand(remoteIp, "shutdown -r -t 3"); if(executeCommand){//通过客户机tomcat重启 logger.info("通过客户机tomcat重启命令"); return ; } logger.info("通过telnet执行的重启命令"); TelnetClient telnetClient = new TelnetClient(); try{ telnetClient.setConnectTimeout(500); telnetClient.setDefaultTimeout(500); telnetClient.connect(remoteIp, 23); OutputStream outstr = telnetClient.getOutputStream(); final InputStream instr = telnetClient.getInputStream(); Thread.sleep(8000); outstr.write((user+"\r\n").getBytes()); outstr.flush(); Thread.sleep(2000); outstr.write((password+"\r\n").getBytes()); outstr.flush(); Thread.sleep(2000); outstr.write("shutdown -r -t 5\r\n".getBytes()); outstr.flush(); Thread.sleep(2000); outstr.write("exit\r\n".getBytes()); outstr.flush(); Thread.sleep(200); outstr.close(); instr.close(); }finally{ telnetClient.disconnect(); } } public static boolean executeCommand(String ip, String command){ try { Socket socket = new Socket(); socket.setSoTimeout(3000); SocketAddress socketAddress = new InetSocketAddress(ip, 8384); socket.connect(socketAddress, 1000); OutputStream outputStream = socket.getOutputStream(); outputStream.write(command.getBytes("UTF-8")); outputStream.write("\n".getBytes("UTF-8")); outputStream.flush(); InputStream inputStream = socket.getInputStream(); byte[] content = new byte[1024]; List<Byte> bytes = new ArrayList<Byte>(100); int read = 0; while((read = inputStream.read(content))!=-1){ for (int i = 0; i < read; i++) { bytes.add(content[i]); } } content = new byte[bytes.size()]; for (int i = 0; i < content.length; i++) { content[i] = bytes.get(i); } String result = new String(content, "UTF-8"); inputStream.close(); outputStream.close(); socket.close(); return "OK".equals(result); } catch (Throwable e) { logger.error("runner:"+ip+"执行命令:"+command+" 失败",e); return false; } } |
|||
根据Date,技术时间差,如1.4小时 | java date | ||
public static String getDuration(Date startedAt, Date endedAt){ if(null == startedAt || null == endedAt){ return new StringBuilder().append("--").toString(); } else{ //in milliseconds float diff = endedAt.getTime() - startedAt.getTime(); BigDecimal big = new BigDecimal(diff/(60 * 60 * 1000)); float diffHours = big.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue(); return new StringBuilder().append(diffHours).append("h").toString(); } } |
|||
Spring中PropertyPlaceholderConfigurer实现属性与变量替换的具体代码 | spring | ||
//这个类是在spring-core中org.springframework.util包下的PropertyPlaceholderHelper具体实现的,代码如下 /* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.util; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Utility class for working with Strings that have placeholder values in them. A placeholder takes the form * {@code ${name}}. Using {@code PropertyPlaceholderHelper} these placeholders can be substituted for * user-supplied values. <p> Values for substitution can be supplied using a {@link Properties} instance or * using a {@link PlaceholderResolver}. * * @author Juergen Hoeller * @author Rob Harrop * @since 3.0 */ public class PropertyPlaceholderHelper { private static final Log logger = LogFactory.getLog(PropertyPlaceholderHelper.class); private static final Map<String, String> wellKnownSimplePrefixes = new HashMap<String, String>(4); static { wellKnownSimplePrefixes.put("}", "{"); wellKnownSimplePrefixes.put("]", "["); wellKnownSimplePrefixes.put(")", "("); } private final String placeholderPrefix; private final String placeholderSuffix; private final String simplePrefix; private final String valueSeparator; private final boolean ignoreUnresolvablePlaceholders; /** * Creates a new {@code PropertyPlaceholderHelper} that uses the supplied prefix and suffix. * Unresolvable placeholders are ignored. * @param placeholderPrefix the prefix that denotes the start of a placeholder. * @param placeholderSuffix the suffix that denotes the end of a placeholder. */ public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix) { this(placeholderPrefix, placeholderSuffix, null, true); } /** * Creates a new {@code PropertyPlaceholderHelper} that uses the supplied prefix and suffix. * @param placeholderPrefix the prefix that denotes the start of a placeholder * @param placeholderSuffix the suffix that denotes the end of a placeholder * @param valueSeparator the separating character between the placeholder variable * and the associated default value, if any * @param ignoreUnresolvablePlaceholders indicates whether unresolvable placeholders should be ignored * ({@code true}) or cause an exception ({@code false}). */ public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix, String valueSeparator, boolean ignoreUnresolvablePlaceholders) { Assert.notNull(placeholderPrefix, "placeholderPrefix must not be null"); Assert.notNull(placeholderSuffix, "placeholderSuffix must not be null"); this.placeholderPrefix = placeholderPrefix; this.placeholderSuffix = placeholderSuffix; String simplePrefixForSuffix = wellKnownSimplePrefixes.get(this.placeholderSuffix); if (simplePrefixForSuffix != null && this.placeholderPrefix.endsWith(simplePrefixForSuffix)) { this.simplePrefix = simplePrefixForSuffix; } else { this.simplePrefix = this.placeholderPrefix; } this.valueSeparator = valueSeparator; this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders; } /** * Replaces all placeholders of format {@code ${name}} with the corresponding * property from the supplied {@link Properties}. * @param value the value containing the placeholders to be replaced. * @param properties the {@code Properties} to use for replacement. * @return the supplied value with placeholders replaced inline. */ public String replacePlaceholders(String value, final Properties properties) { Assert.notNull(properties, "Argument 'properties' must not be null."); return replacePlaceholders(value, new PlaceholderResolver() { @Override public String resolvePlaceholder(String placeholderName) { return properties.getProperty(placeholderName); } }); } /** * Replaces all placeholders of format {@code ${name}} with the value returned * from the supplied {@link PlaceholderResolver}. * @param value the value containing the placeholders to be replaced. * @param placeholderResolver the {@code PlaceholderResolver} to use for replacement. * @return the supplied value with placeholders replaced inline. */ public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver) { Assert.notNull(value, "Argument 'value' must not be null."); return parseStringValue(value, placeholderResolver, new HashSet<String>()); } protected String parseStringValue( String strVal, PlaceholderResolver placeholderResolver, Set<String> visitedPlaceholders) { StringBuilder buf = new StringBuilder(strVal); int startIndex = strVal.indexOf(this.placeholderPrefix); while (startIndex != -1) { int endIndex = findPlaceholderEndIndex(buf, startIndex); if (endIndex != -1) { String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex); String originalPlaceholder = placeholder; if (!visitedPlaceholders.add(originalPlaceholder)) { throw new IllegalArgumentException( "Circular placeholder reference '" + originalPlaceholder + "' in property definitions"); } // Recursive invocation, parsing placeholders contained in the placeholder key. placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders); // Now obtain the value for the fully resolved key... String propVal = placeholderResolver.resolvePlaceholder(placeholder); if (propVal == null && this.valueSeparator != null) { int separatorIndex = placeholder.indexOf(this.valueSeparator); if (separatorIndex != -1) { String actualPlaceholder = placeholder.substring(0, separatorIndex); String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length()); propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder); if (propVal == null) { propVal = defaultValue; } } } if (propVal != null) { // Recursive invocation, parsing placeholders contained in the // previously resolved placeholder value. propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders); buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal); if (logger.isTraceEnabled()) { logger.trace("Resolved placeholder '" + placeholder + "'"); } startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length()); } else if (this.ignoreUnresolvablePlaceholders) { // Proceed with unprocessed value. startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length()); } else { throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "'" + " in string value \"" + strVal + "\""); } visitedPlaceholders.remove(originalPlaceholder); } else { startIndex = -1; } } return buf.toString(); } private int findPlaceholderEndIndex(CharSequence buf, int startIndex) { int index = startIndex + this.placeholderPrefix.length(); int withinNestedPlaceholder = 0; while (index < buf.length()) { if (StringUtils.substringMatch(buf, index, this.placeholderSuffix)) { if (withinNestedPlaceholder > 0) { withinNestedPlaceholder--; index = index + this.placeholderSuffix.length(); } else { return index; } } else if (StringUtils.substringMatch(buf, index, this.simplePrefix)) { withinNestedPlaceholder++; index = index + this.simplePrefix.length(); } else { index++; } } return -1; } /** * Strategy interface used to resolve replacement values for placeholders contained in Strings. * @see PropertyPlaceholderHelper */ public static interface PlaceholderResolver { /** * Resolves the supplied placeholder name into the replacement value. * @param placeholderName the name of the placeholder to resolve * @return the replacement value or {@code null} if no replacement is to be made */ String resolvePlaceholder(String placeholderName); } } |
|||
Java读写XML | java xml | http://www.cnblogs.com/wangchenyang/archive/2011/08/23/2150530.html | |
Java读取、创建xml(通过dom方式) 创建一个接口 XmlInterface.java public interface XmlInterface { /** * 建立XML文档 * @param fileName 文件全路径名称 */ public void createXml(String fileName); /** * 解析XML文档 * @param fileName 文件全路径名称 */ public void parserXml(String fileName); } 接口实现 XmlImpl.java package com.test.xml; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XmlImpl implements XmlInterface{ private Document document; public void init() { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); this.document = builder.newDocument(); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } } public void createXml(String fileName) { Element root = this.document.createElement("scores"); this.document.appendChild(root); Element employee = this.document.createElement("employee"); Element name = this.document.createElement("name"); name.appendChild(this.document.createTextNode("wangchenyang")); employee.appendChild(name); Element sex = this.document.createElement("sex"); sex.appendChild(this.document.createTextNode("m")); employee.appendChild(sex); Element age = this.document.createElement("age"); age.appendChild(this.document.createTextNode("26")); employee.appendChild(age); root.appendChild(employee); TransformerFactory tf = TransformerFactory.newInstance(); try { Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); PrintWriter pw = new PrintWriter(new FileOutputStream(fileName)); StreamResult result = new StreamResult(pw); transformer.transform(source, result); System.out.println("生成XML文件成功!"); } catch (TransformerConfigurationException e) { System.out.println(e.getMessage()); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (TransformerException e) { System.out.println(e.getMessage()); } } public void parserXml(String fileName) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(fileName); NodeList employees = document.getChildNodes(); for (int i = 0; i < employees.getLength(); i++) { Node employee = employees.item(i); NodeList employeeInfo = employee.getChildNodes(); for (int j = 0; j < employeeInfo.getLength(); j++) { Node node = employeeInfo.item(j); NodeList employeeMeta = node.getChildNodes(); for (int k = 0; k < employeeMeta.getLength(); k++) { System.out.println(employeeMeta.item(k).getNodeName() + ":" + employeeMeta.item(k).getTextContent()); } } } System.out.println("解析完毕"); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } } } 测试 public class Main { public static void main(String args[]){ XmlImpl dd=new XmlImpl(); String str="D:/grade.xml"; dd.init(); dd.createXml(str); //创建xml dd.parserXml(str); //读取xml } } 结果 生成xml 复制代码 <?xml version="1.0" encoding="GB2312"?> <scores> <employee> <name>wangchenyang</name> <sex>m</sex> <age>26</age> </employee> </scores> 复制代码 读取xml 生成XML文件成功! #text: name:wangchenyang #text: sex:m #text: age:26 #text: 解析完毕 |
|||
java读写Properties文件 | java properties | ||
package apistudy; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Properties; public class PropertiesTest { public static void main(String[] args) { String readfile = "d:" + File.separator + "readfile.properties"; String writefile = "d:" + File.separator + "writefile.properties"; String readxmlfile = "d:" + File.separator + "readxmlfile.xml"; String writexmlfile = "d:" + File.separator + "writexmlfile.xml"; String readtxtfile = "d:" + File.separator + "readtxtfile.txt"; String writetxtfile = "d:" + File.separator + "writetxtfile.txt"; readPropertiesFile(readfile); //读取properties文件 writePropertiesFile(writefile); //写properties文件 readPropertiesFileFromXML(readxmlfile); //读取XML文件 writePropertiesFileToXML(writexmlfile); //写XML文件 readPropertiesFile(readtxtfile); //读取txt文件 writePropertiesFile(writetxtfile); //写txt文件 } //读取资源文件,并处理中文乱码 public static void readPropertiesFile(String filename) { Properties properties = new Properties(); try { InputStream inputStream = new FileInputStream(filename); properties.load(inputStream); inputStream.close(); //关闭流 } catch (IOException e) { e.printStackTrace(); } String username = properties.getProperty("username"); String passsword = properties.getProperty("password"); String chinese = properties.getProperty("chinese"); try { chinese = new String(chinese.getBytes("ISO-8859-1"), "GBK"); // 处理中文乱码 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(username); System.out.println(passsword); System.out.println(chinese); } //读取XML文件,并处理中文乱码 public static void readPropertiesFileFromXML(String filename) { Properties properties = new Properties(); try { InputStream inputStream = new FileInputStream(filename); properties.loadFromXML(inputStream); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } String username = properties.getProperty("username"); String passsword = properties.getProperty("password"); String chinese = properties.getProperty("chinese"); //XML中的中文不用处理乱码,正常显示 System.out.println(username); System.out.println(passsword); System.out.println(chinese); } //写资源文件,含中文 public static void writePropertiesFile(String filename) { Properties properties = new Properties(); try { OutputStream outputStream = new FileOutputStream(filename); properties.setProperty("username", "myname"); properties.setProperty("password", "mypassword"); properties.setProperty("chinese", "中文"); properties.store(outputStream, "author: shixing_11@sina.com"); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } //写资源文件到XML文件,含中文 public static void writePropertiesFileToXML(String filename) { Properties properties = new Properties(); try { OutputStream outputStream = new FileOutputStream(filename); properties.setProperty("username", "myname"); properties.setProperty("password", "mypassword"); properties.setProperty("chinese", "中文"); properties.storeToXML(outputStream, "author: shixing_11@sina.com"); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } |
|||
java 动态编辑xml | java xml | ||
package imix.codegen; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XMLDocumentHelper { private static final String HEADER_TRAILER_XML_NAME = "IMIXT 1.0"; private static final String DEFAULT_HEADER_TRAILER_XML_NAME = "Default Header And Trailer"; /** Tag whether header and tailer document is IMIXT or default one. **/ private boolean isIMIXTDocument = true; /** Document that used to load header and trailer information. **/ private Document headerTrailerDocument = null; private MessageCodeGenerator messageCodeGenerator = null; public XMLDocumentHelper(MessageCodeGenerator messageCodeGenerator){ this.messageCodeGenerator = messageCodeGenerator; } /** * Append header, trailer and related fields and components. Should only be done for app message document. * @param task * @param document */ void appendHeaderTrailerAndRelated(Task task, Document document){ HTNodeList headerNodeList = new HTNodeList(); HTNodeList trailerNodeList = new HTNodeList(); extractHeaderAndTrailerNode(headerNodeList, trailerNodeList); HTNodeList headerTrailerFields = new HTNodeList(); HTNodeList headerTrailerCompoments = new HTNodeList(); findHTFieldsAndComponents(headerTrailerDocument, isIMIXTDocument, headerTrailerFields, headerTrailerCompoments); Element documentElement = document.getDocumentElement(); Document ownerDoc = documentElement.getOwnerDocument(); Node headerNode = documentElement.getElementsByTagName("header").item(0); for(int i=0;i<headerNodeList.getLength();i++){ if(headerNodeList.item(i).getNodeName().equals("field")||headerNodeList.item(i).getNodeName().equals("component")){ Node clonedNode = headerNodeList.item(i).cloneNode(true);// deep clone headerNode.appendChild(ownerDoc.adoptNode(clonedNode)); // append cloned node to header } } Node trailerNode = documentElement.getElementsByTagName("trailer").item(0); for(int j=0;j<trailerNodeList.getLength();j++){ if(trailerNodeList.item(j).getNodeName().equals("field")||trailerNodeList.item(j).getNodeName().equals("component")){ Node clonedNode = trailerNodeList.item(j).cloneNode(true); trailerNode.appendChild(ownerDoc.adoptNode(clonedNode));//append cloned node to trailer } } appendNecessaryHTFieldNode(document, headerTrailerFields, isIMIXTDocument); appendNecessaryHTComponentNode(document, headerTrailerCompoments, isIMIXTDocument); } /** * Extract header and trailer nodes from Admin message xml * for App message xml.<br/>. * @author Keliang Xin * @return */ private void extractHeaderAndTrailerNode(HTNodeList headerNodeList, HTNodeList trailerNodeList){ Task t = new Task(); t.setName(HEADER_TRAILER_XML_NAME); t.setSpecification(MessageCodeGenerator.specificationDirectory+MessageCodeGenerator.stripSpaces(HEADER_TRAILER_XML_NAME)+".xml"); try { headerTrailerDocument = messageCodeGenerator.getSpecification(t); } catch (Exception e) { System.out.println("No imixt xml was found, load the default header and trailer xml"); headerTrailerDocument = loadAndParseDefaultHeaderTrailerXml(); if(headerTrailerDocument == null) throw new RuntimeException("Try to load default header and trailer xml, but not found."); isIMIXTDocument = false; } NodeList hNodeList = headerTrailerDocument.getDocumentElement().getElementsByTagName("header"); if(hNodeList == null || hNodeList.getLength()<1){ String errorMsg = "No 'header' node was found when extracting 'header' from " + (isIMIXTDocument?"imixt":"default header and trailer")+" xml."; System.out.println(errorMsg); throw new RuntimeException(errorMsg); } NodeList tNodeList = headerTrailerDocument.getDocumentElement().getElementsByTagName("trailer"); if(tNodeList == null || tNodeList.getLength()<1){ String errorMsg = "No 'trailer' node was found when extracting 'trailer' from " + (isIMIXTDocument?"imixt":"default header and trailer")+" xml."; System.out.println(errorMsg); throw new RuntimeException(errorMsg); } Node headerNode = hNodeList.item(0); NodeList hChildNodes = headerNode.getChildNodes(); for(int i=0;i<hChildNodes.getLength();i++){ headerNodeList.addNode(hChildNodes.item(i)); } Node trailerNode = tNodeList.item(0); NodeList tChildNodes = trailerNode.getChildNodes(); for(int j=0;j<tChildNodes.getLength();j++){ trailerNodeList.addNode(tChildNodes.item(j)); } } /** * Append not existing field node referred in header and trailer * to 'fields' section of target doc. * @param targetDoc * @param headerTrailerFields * @param isIMIXTDocument */ private void appendNecessaryHTFieldNode(Document targetDoc, HTNodeList headerTrailerFields, boolean isIMIXTDocument){ Element documentElement = targetDoc.getDocumentElement(); Node fieldsNode = documentElement.getElementsByTagName("fields").item(0); Node htFNode = null; for(int i = 0; i < headerTrailerFields.getLength(); i++){ htFNode = headerTrailerFields.item(i); String nodeName = getAttribute(htFNode, "name"); if(lookupFieldNodeByName(documentElement, nodeName, isIMIXTDocument)==null){ Document ownerDoc = fieldsNode.getOwnerDocument(); Node clonedNode = htFNode.cloneNode(true); fieldsNode.appendChild(ownerDoc.adoptNode(clonedNode)); } } } /** *Append not existing component node referred in header and trailer * to 'components' section of target doc. * @param targetDoc * @param headerTrailerCompoments * @param isIMIXTDocument */ private void appendNecessaryHTComponentNode(Document targetDoc, HTNodeList headerTrailerCompoments, boolean isIMIXTDocument){ Element documentElement = targetDoc.getDocumentElement(); Node componentsNode = documentElement.getElementsByTagName("components").item(0); Node htCNode = null; for(int i = 0; i < headerTrailerCompoments.getLength(); i++){ htCNode = headerTrailerCompoments.item(i); String nodeName = getAttribute(htCNode, "name"); if(lookupComponentNodeByName(documentElement, nodeName, isIMIXTDocument)==null){ Document ownerDoc = componentsNode.getOwnerDocument(); Node clonedNode = htCNode.cloneNode(true); componentsNode.appendChild(ownerDoc.adoptNode(clonedNode)); } } } /** * If no imixt xml found, load default one. * @return */ private Document loadAndParseDefaultHeaderTrailerXml(){ Task t = new Task(); t.setName(DEFAULT_HEADER_TRAILER_XML_NAME); t.setSpecification(MessageCodeGenerator.specificationDirectory+MessageCodeGenerator.stripSpaces(DEFAULT_HEADER_TRAILER_XML_NAME)+".xml"); Document document = null; try { document = messageCodeGenerator.getSpecification(t); } catch (Exception e) { System.out.println("Exception occured when loading or parsing 'default header and trailer' " + "xml for App message xml."); throw new RuntimeException(e); } return document; } /** * Use as a special node collection that can add node flexibly. * @author Keliang Xin * */ class HTNodeList implements NodeList { private List<Node> nodeList = null; public HTNodeList(){ nodeList = new ArrayList<Node>(); } public void addNode(Node node){ nodeList.add(node); } public Node item(int i) { return nodeList.get(i); } public int getLength() { return nodeList.size(); } }; /** * Find fields and components in header and tailer node of certain document. * @param headerTrailerDocument * @param isIMIXTDocument * @param headerTrailerFields * @param headerTrailerCompoments * @throws RuntimeException */ private void findHTFieldsAndComponents(Document headerTrailerDocument, boolean isIMIXTDocument, HTNodeList headerTrailerFields, HTNodeList headerTrailerCompoments) throws RuntimeException{ Element headerTrailerDocumentElement = headerTrailerDocument.getDocumentElement(); // HEADER final NodeList headerNodes = headerTrailerDocumentElement.getElementsByTagName("header"); if (headerNodes.getLength() == 0) { throw new RuntimeException("<header> section not found in " + (isIMIXTDocument?"imixt":"default header and trailer") +" data dictionary"); } putNodeInCertainContainer(headerNodes.item(0).getChildNodes(), headerTrailerFields, headerTrailerCompoments , headerTrailerDocumentElement, isIMIXTDocument); // TRAILER final NodeList trailerNode = headerTrailerDocumentElement.getElementsByTagName("trailer"); if (trailerNode.getLength() == 0) { throw new RuntimeException("<trailer> section not found in " + (isIMIXTDocument?"imixt":"default header and trailer") +" data dictionary"); } putNodeInCertainContainer(trailerNode.item(0).getChildNodes(), headerTrailerFields, headerTrailerCompoments , headerTrailerDocumentElement, isIMIXTDocument); } /** * Put fields in field node list and do the same for component. * @param nodeList * @param headerTrailerFields * @param headerTrailerCompoments * @throws RuntimeException */ private void putNodeInCertainContainer(NodeList nodeList, HTNodeList headerTrailerFields, HTNodeList headerTrailerCompoments , Element headerTrailerDocumentElement, boolean isIMIXTDocument) throws RuntimeException{ int nodeCount = nodeList.getLength(); for(int i=0;i<nodeCount;i++){ Node childNode = nodeList.item(i); String nodeName = childNode.getNodeName(); if("field".equals(nodeName) || "group".equals(nodeName)){ String nameAttrValue = getAttribute(childNode, "name"); Node node = lookupFieldNodeByName(headerTrailerDocumentElement, nameAttrValue, isIMIXTDocument); if(node == null) throw new RuntimeException("header or trailer node '"+nameAttrValue+"' not found in " + (isIMIXTDocument?"imixt":"default header and trailer")+" data dictionary"); headerTrailerFields.addNode(node); // handle group child node if("group".equals(nodeName)){ putNodeInCertainContainer(childNode.getChildNodes(), headerTrailerFields, headerTrailerCompoments , headerTrailerDocumentElement, isIMIXTDocument); } }else if("component".equals(nodeName)){ String nameAttrValue = getAttribute(childNode, "name"); Node node = lookupComponentNodeByName(headerTrailerDocumentElement, nameAttrValue, isIMIXTDocument); if(node == null) throw new RuntimeException("header or trailer node '"+nameAttrValue+"' not found in " + (isIMIXTDocument?"imixt":"default header and trailer")+" data dictionary"); headerTrailerCompoments.addNode(node); //handle component child node putNodeInCertainContainer(node.getChildNodes(), headerTrailerFields, headerTrailerCompoments , headerTrailerDocumentElement, isIMIXTDocument); } } } /** * Find field node with certain name in 'fields' section.(mainly used for imixt or default header and trailer document) * @param documentElement * @param name * @param isIMIXTDocument * @return Node or null * @throws RuntimeException */ private Node lookupFieldNodeByName(Element documentElement, String name, boolean isIMIXTDocument) throws RuntimeException{ // fields final NodeList fieldsNode = documentElement.getElementsByTagName("fields"); if (fieldsNode.getLength() == 0) { throw new RuntimeException("<fields> section not found in " + (isIMIXTDocument?"imixt":"default header and trailer") +"data dictionary"); } Node node = null; NodeList fieldsChildrenNode = fieldsNode.item(0).getChildNodes(); for(int i=0;i<fieldsChildrenNode.getLength();i++){ node = fieldsChildrenNode.item(i); if(name.equals(getAttribute(node, "name"))) return node; } return null; } /** * Find component node with certain name in 'components' section.(mainly used for imixt or default header and trailer document) * @param documentElement * @param name * @param isIMIXTDocument * @return Node or null * @throws RuntimeException */ private Node lookupComponentNodeByName(Element documentElement, String name, boolean isIMIXTDocument) throws RuntimeException{ // components final NodeList componentsNode = documentElement.getElementsByTagName("components"); if (componentsNode.getLength() == 0) { throw new RuntimeException("<components> section not found in " + (isIMIXTDocument?"imixt":"default header and trailer") +"data dictionary"); } Node node = null; NodeList componentsChildrenNode = componentsNode.item(0).getChildNodes(); for(int i=0;i<componentsChildrenNode.getLength();i++){ node = componentsChildrenNode.item(i); if(name.equals(getAttribute(node, "name"))) return node; } return null; } private String getAttribute(Node node, String name) { return getAttribute(node, name, null); } private String getAttribute(Node node, String name, String defaultValue) { final NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { final Node namedItem = attributes.getNamedItem(name); return namedItem != null ? namedItem.getNodeValue() : null; } return defaultValue; } } |
|||
Java使用JSONObject和JSONArray对象操作json数据 | java json | ||
/** *之前查询CQ数据,传入的参数和获得的数据都是json格式的,当时不知道使用JSONObject和JSONArray,自己构件了相关对*象,然后再用ObjectToJson转换了一下。后来看到别人的代码,发现这样使用JSONObject和JSONArray也很方便,弄了两个*方法 */ /** * * 根据项目ID从CQ获取 * 1.项目名称 * 2.项目类型 * 3.项目状态 * 4.开发负责人 * 5.测试负责人 * 6.项目预计发布时间 * 7.项目ID * 8.svn 地址 * @param projectId 项目ID * @return JSONObject */ public static JSONObject getProjectInfoByProjectIdForCq(String projectId) { JSONObject resultObject = new JSONObject(); try { if (StringUtils.isNotEmpty(projectId)) { if (loginCP()) { JSONObject params = new JSONObject(); params.put("entityName", "项目"); List<String> colomnList = new ArrayList<String>(); colomnList.add("id"); colomnList.add("Headline"); colomnList.add("State"); colomnList.add("项目类型"); colomnList.add("计划迭代发布时间"); colomnList.add("SVN分支"); colomnList.add("开发负责人名称"); colomnList.add("测试负责人名称"); params.put("colomnList", colomnList); JSONArray conditionList = new JSONArray(); JSONObject jsonObject = new JSONObject(); jsonObject.put("conditionTypeEnum", "STRING"); jsonObject.put("operatorEnum", "EQUAL"); jsonObject.put("colomnName", "id"); List<String> colomnValues = new ArrayList<String>(); colomnValues.add(projectId); jsonObject.put("colomnValues", colomnValues); conditionList.add(jsonObject); params.put("conditionList", conditionList); String data = JsonXmlUtils.toJSONString(params); ResultObject rs = HttpClientUtils.sendPost(searchCqUrl, "data", data); if (rs.isOk()) { String content = rs.getContent(); JSONArray recordFieldCollection = JSONObject.parseObject(content) .getJSONObject("tcResultRecordList").getJSONArray("result"); for (Iterator<Object> iterator = recordFieldCollection.iterator(); iterator .hasNext();) { JSONObject object = (JSONObject) iterator.next(); JSONObject resultDbMap = object.getJSONObject("resultDbMap"); String title = resultDbMap.getString("FLDCOLUMN_15"); String proType = resultDbMap.getString("FLDCOLUMN_37"); String releaseDate = resultDbMap.getString("FLDCOLUMN_5"); String id = resultDbMap.getString("ID"); String state = resultDbMap.getString("STATE"); String devOwner = resultDbMap.getString("TEST_HEAD_NAME"); String testOwner = resultDbMap.getString("DEV_HEADER_NAME"); String svnUrl = resultDbMap.getString("FLDCOLUMN_65"); resultObject.put("cqId", id); resultObject.put("projectName", title); resultObject.put("proType", proType); resultObject.put("releaseDate", releaseDate); resultObject.put("state", state); if (StringUtils.isNotEmpty(devOwner)) { devOwner = StringUtils.substring(devOwner, devOwner.indexOf("[") + 1, devOwner.indexOf("]")); } if (StringUtils.isNotEmpty(testOwner)) { testOwner = StringUtils.substring(devOwner, devOwner.indexOf("[") + 1, devOwner.indexOf("]")); } resultObject.put("devOwner", devOwner); resultObject.put("testOwner", testOwner); resultObject.put("svnUrl", svnUrl); } } } } } catch (Exception e) { logger.error(e.getMessage(), e); } return resultObject; } /** * * 根据项目ID从CP获取 * 1.项目名称 * 2.项目类型 * 3.项目状态 * 4.开发负责人 * 5.测试负责人 * 6.项目预计发布时间 * 7.项目ID * 8.svn 地址 * @param projectId 项目ID * @return JSONObject */ public static JSONObject getProjectInfoByProjectIdForCp(String projectId) { JSONObject resultObject = new JSONObject(); try { if (StringUtils.isNotEmpty(projectId)) { if (loginCP()) { String releaseType = "cp_record_service_release"; if (StringUtils.containsIgnoreCase(projectId, "cp_record_client")) { releaseType = "cp_record_client_release"; } JSONObject releaseJsonObject = getReleaseByProjectId(projectId, releaseType); String releaseId = releaseJsonObject.getString(releaseType); if (StringUtils.isNotEmpty(releaseId)) { resultObject.put("releaseDate", getReleaseTimeByReleaseId(releaseId)); } JSONObject jsonObject = getReleaseByProjectId(projectId, releaseType); String iterationId = jsonObject.getString("cp_record_iteration"); if (StringUtils.isNotEmpty(iterationId)) { JSONObject params = new JSONObject(); params.put("recordUniqueId", iterationId); String data = JsonXmlUtils.toJSONString(params); ResultObject rs = HttpClientUtils.sendPost(simpleSearchCpUrl, "data", data); if (rs.isOk()) { String content = rs.getContent(); JSONObject rolePersonMap = JSONObject.parseObject(content) .getJSONObject("resultMes").getJSONObject("result").getJSONObject( "rolePersonMap"); JSONArray testOwnerArray = rolePersonMap.getJSONArray("DEVELOP_LEADER"); for (Iterator<Object> iterator1 = testOwnerArray.iterator(); iterator1 .hasNext();) { JSONObject object = (JSONObject) iterator1.next(); String value = object.getString("value"); if (StringUtils.isNotEmpty(value)) { resultObject.put("testOwner", value); } } JSONArray devOwnerArray = rolePersonMap.getJSONArray("TEST_LEADER"); for (Iterator<Object> iterator1 = devOwnerArray.iterator(); iterator1 .hasNext();) { JSONObject object = (JSONObject) iterator1.next(); String value = object.getString("value"); if (StringUtils.isNotEmpty(value)) { resultObject.put("devOwner", value); } } } } JSONObject params1 = new JSONObject(); String recordUniqueType = "cp_record_client_change"; for (String str : recordUniqueTypeList) { if (StringUtils.containsIgnoreCase(projectId, str)) { recordUniqueType = str; } } params1.put("recordUniqueType", recordUniqueType); String[] fieldList = { "unique_id", "summary", "unique_type", "svn_branches" }; params1.put("fieldList", fieldList); params1.put("loadStatusFlag", "true"); Map<String, Object> conditionConnector = new HashMap<String, Object>(); conditionConnector.put("connectorEnum", "AND"); Map<String, Object> conditionParams1 = new HashMap<String, Object>(); conditionParams1.put("operatorEnum", "EQUAL"); String[] colomnValues1 = { projectId }; conditionParams1.put("colomnValues", colomnValues1); conditionParams1.put("colomnName", "unique_id"); conditionParams1.put("conditionTypeEnum", "STRING"); Object[] conditionList = new Object[] { conditionParams1 }; conditionConnector.put("conditionList", conditionList); params1.put("conditionConnector", conditionConnector); String data1 = JsonXmlUtils.toJSONString(params1); ResultObject rs1 = HttpClientUtils.sendPost(searchCpUrl, "data", data1); if (rs1.isOk()) { String content1 = rs1.getContent(); JSONArray resultArray = JSONObject.parseObject(content1).getJSONObject( "resultMes").getJSONArray("result"); Iterator<Object> iterator = resultArray.iterator(); while (iterator.hasNext()) { JSONObject jsonObject1 = (JSONObject) iterator.next(); JSONArray jsonArray = jsonObject1.getJSONArray("recordFieldCollection"); for (Iterator<Object> iterator1 = jsonArray.iterator(); iterator1 .hasNext();) { JSONObject object = (JSONObject) iterator1.next(); String name = object.getString("name"); String value = object.getString("value"); if (StringUtils.equals("summary", name)) { resultObject.put("projectName", value); } if (StringUtils.equals("unique_id", name)) { resultObject.put("cqId", value); } if (StringUtils.equals("unique_type", name)) { resultObject.put("proType", value); } if (StringUtils.equals("svn_branches", name)) { JSONArray jSONArrayValue = object.getJSONArray("value"); StringBuffer stringBuffer = new StringBuffer(); for (Iterator<Object> iterator2 = jSONArrayValue.iterator(); iterator2 .hasNext();) { JSONObject object3 = (JSONObject) iterator2.next(); String branch = object3.getString("branch"); stringBuffer.append(branch).append("\n"); } resultObject.put("svnUrl", stringBuffer); } } JSONObject jsonObject2 = jsonObject1.getJSONObject("wfEntity"); String wfStatus = jsonObject2.getJSONObject("wfStatus").getString( "name"); resultObject.put("state", wfStatus); } } } } } catch (Exception e) { logger.error(e.getMessage(), e); } return resultObject; } /** * * 根据项目ID从CQ获取 * 1.发布ID * 2.发布名称 * 3.发布状态 * 4.发布类型 * 5.发布时间 * @param startTime 开始时间 * @param endTime 结束时间 * @param state 状态 * @param releaseTimeType 1: 实际发布上线时间;0:计划发布时间 * @return JSONArray */ public static JSONArray getReleaseInfoByTimeForCq(String startTime, String endTime, String[] states, int releaseTimeType) { JSONArray jsonArray = new JSONArray(); try { if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime) && states != null) { if (loginCP()) { Map<String, Object> params = new HashMap<String, Object>(); params.put("entityName", "发布"); String[] colomnList = { "id", "Headline", "State", "发布类型", "发布时间", "实际发布上线时间" }; params.put("colomnList", colomnList); String colomnName = "实际发布上线时间"; if (releaseTimeType == 0) { colomnName = "发布时间"; } Map<String, Object> conditionParams1 = new HashMap<String, Object>(); conditionParams1.put("operatorEnum", "GE"); conditionParams1.put("colomnName", colomnName); String[] colomnValues1 = { startTime }; conditionParams1.put("colomnValues", colomnValues1); conditionParams1.put("conditionTypeEnum", "CQDATE"); conditionParams1.put("colomnValuePattern", "yyyy-mm-dd"); Map<String, Object> conditionParams2 = new HashMap<String, Object>(); conditionParams2.put("operatorEnum", "LT"); conditionParams2.put("colomnName", colomnName); String[] colomnValues2 = { endTime }; conditionParams2.put("colomnValues", colomnValues2); conditionParams2.put("conditionTypeEnum", "CQDATE"); conditionParams2.put("colomnValuePattern", "yyyy-mm-dd"); Map<String, Object> conditionParams3 = new HashMap<String, Object>(); conditionParams3.put("operatorEnum", "IN"); conditionParams3.put("colomnName", "State"); String[] colomnValues3 = states; conditionParams3.put("colomnValues", colomnValues3); conditionParams3.put("conditionTypeEnum", "CQSTATETYPE"); Object[] conditionParamsList = new Object[] { conditionParams1, conditionParams2, conditionParams3 }; params.put("conditionList", conditionParamsList); String data = JsonXmlUtils.toJSONString(params); ResultObject rs = HttpClientUtils.sendPost(searchCqUrl, "data", data); if (rs.isOk()) { String content = rs.getContent(); boolean handerResult = JSONObject.parseObject(content).getJSONObject( "tcResultRecordList").getBooleanValue("success"); if (handerResult) { JSONArray resultArray = JSONObject.parseObject(content).getJSONObject( "tcResultRecordList").getJSONArray("result"); Iterator<Object> iterator = resultArray.iterator(); while (iterator.hasNext()) { JSONObject jsonObject = (JSONObject) iterator.next(); JSONObject resultDbMap = jsonObject.getJSONObject("resultDbMap"); JSONObject releaseCqJsonObject = new JSONObject(); releaseCqJsonObject.put("cqId", resultDbMap.get("ID")); releaseCqJsonObject.put("headLine", resultDbMap.get("FLDCOLUMN_5")); releaseCqJsonObject.put("state", resultDbMap.get("STATE")); releaseCqJsonObject.put("type", resultDbMap.get("FLDCOLUMN_10")); releaseCqJsonObject.put("releaseTime", resultDbMap .get("FLDCOLUMN_48")); releaseCqJsonObject.put("releasePlanTime", resultDbMap .get("FLDCOLUMN_2")); jsonArray.add(releaseCqJsonObject); } } } } } } catch (Exception e) { logger.error(e.getMessage(), e); } return jsonArray; } |
|||
java jar包中文件读写(不能使用new File的形式) | java io | ||
package com.alipay.ats.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import org.apache.commons.io.CopyUtils; public class FileUtil { private final static String ATS3_FILE_DIR = "\\ats\\tmpFile3\\"; /** * 将工程中resource下面的文件复制到本地磁盘,并返回此文件在本地磁盘的绝对路径。 * 如入参为“config/ats-config.properties”, * 出参为“C:\Users\keliang.xkl\ats\tmpFile3\sit-Core\ats-config.properties” * @param resourcePath * @return */ public static String resourceToPath(String resourcePath) { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); URL resourceUrl = currentClassLoader.getResource(resourcePath); File resource = new File(resourceUrl.getFile()); String resourceName = resource.getName(); String projectDir = System.getProperty("user.dir"); String projectName = null; if (projectDir.indexOf("\\") != -1) { projectName = projectDir.substring(projectDir.lastIndexOf('\\') + 1, projectDir.length()); } String userHomeDir = System.getProperty("user.home"); File destDir = new File(userHomeDir + ATS3_FILE_DIR + projectName); destDir.mkdirs(); File destFile = new File(destDir, resourceName); try { InputStream resourceInputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(resourcePath); OutputStream destFileOutputStream = new FileOutputStream(destFile); CopyUtils.copy(resourceInputStream, destFileOutputStream); } catch (IOException e) { throw new RuntimeException(e); } return destFile.getAbsolutePath(); } /** * 将工程中resource下面的文件复制到本地磁盘,并返回以此文件在本地磁盘的绝对路径创建的File对象。 * * @param resourcePath * @return */ public static File resourceToFile(String resourcePath) { return new File(resourceToPath(resourcePath)); } public static void main(String[] args) { System.out.println(resourceToPath("config/ats-config.properties")); File file = resourceToFile("config/ats-config.properties"); System.out.println(file.getAbsolutePath()); } } |
|||
Jquery confirm | jquery | ||
var deleteComment = function(commentId){ jQuery.confirmBox(function () { jQuery.ajax({ type: 'post', url :"deleteFaultComment.htm", data:{ id: commentId }, success:function(data){ if(data.success == true){ $("#comment" + commentId).remove(); } if ($("#faultCommentListItems li").length == 0) { $("#faultCommentList").addClass("hide"); } }, error: function () { } }); }, "确定删除吗?"); } |
|||
KindEditor配置,以及字数限制提示 | kindeditor | ||
var editor = KindEditor.create('.editor', { resizeType : 1, allowImageUpload : true, filterMode : false, uploadJson:"uploadImage.htm", height : "200px", #if(!$!fault.canEdit) readonlyMode : true, #end afterChange: function () { this.sync(); //限制字数 var limitNum = 2000; //设定限制字数 var pattern = '还可以输入 ' + limitNum + ' 个字'; $('#wordLimitTipContainer').html(pattern); //输入显示 if(this.count('text') > limitNum) { var textCount = limitNum - this.count('text'); pattern = ('还可以输入 <span class="ft-red">' + textCount + '</span> 个字'); // 表单不可提交 buttonDisabled(); } else { //计算剩余字数 var result = limitNum - this.count('text'); pattern = '还可以输入 ' + result + ' 个字'; // 表单可提交 buttonEnabled(); } $('#wordLimitTipContainer').html(pattern); //输入显示 }, items : [ 'fullscreen','|','fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat','table', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', '|', 'image', 'link'] }); |
|||
LinuxUtils类 | java linux | ||
//LinuxUtils import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.SCPClient; import com.alipay.aqc.common.exception.BusinessException; import com.alipay.aqc.common.exception.UnknownException; import com.alipay.aqc.common.util.LinuxUtils.ITransferFileListener; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; /** * 此类相比LinuxUtils类更新,主要是因为LinuxUtils类中读取命令执行结果的方法失效,所以新写一个类 * 如果有需要用到原来类的方法,但是读取不到结果,请在此类中使用新的api实现,把原来的方法标记为过时 * */ public class LinuxUtils2 { private static Log logger = LogFactory.getLog(LinuxUtils2.class); public static void main(String[] args) throws Exception { String hostname = "tradecore-1-64.test.alipay.net";// 要登陆目标主机 String username = "admin";// 登陆用的用户名 String password = "jiaoyi123"; // 登陆用到的密码 /* Create a connection instance */ LinuxSession conn = getSession(hostname, username, password); // // //取远程文件 // File file = getRemoteFile(conn, "/home/admin/deploy.sh", // "C:/一般文件/",null); // if(file.exists()){ // System.out.println(CharsetUtils.guessCharset(file)); // } List<String> findByFileNames = findByFileNames(conn, "/home/admin/tradecore/target/tradecore.ace/core", new String[] { "*.jar" }); System.out.println(findByFileNames); getRemoteDir(hostname, username, password, "/home/admin/tradecore/target/tradecore.ace/core", "*.jar", "/Users/xinkeliang/Downloads/jars"); close(conn); } public static interface CommandCallBack<T> { void handle(T br) throws Exception; } static public class ResultToListCommandCallBack implements CommandCallBack<LinuxSession> { private final List<String> resultLines; public ResultToListCommandCallBack(List<String> resultLines) { this.resultLines = resultLines; } @Override public void handle(LinuxSession sess) { ExecuteShellResult result = sess.result; if (result.isHasException) { resultLines.add(result.errorResult); } else { String resultString = result.result; if (resultString != null) { String[] lines = resultString.split("\\n"); resultLines.addAll(Arrays.asList(lines)); } } } } // private static List<String> findByFileNames(String host, String userName, // String password, String remoteDir, String[] fileNames) { // LinuxSession session = getConnection(host, userName, password); // List<String> files = findByFileNames(session, remoteDir, fileNames); // close(session); // return files; // } private static List<String> findByFileNames(LinuxSession session, String remoteDir, String[] fileNames) { if (fileNames == null) { return null; } final List<String> files = new ArrayList<String>(); for (int i = 0; i < fileNames.length; i++) { String command = "find " + remoteDir + " -name " + getValidFileNamePattern(fileNames[i]); execCommand(session, command, new ResultToListCommandCallBack(files)); } return files; } /** * 如果没有用引号括起来的,加上 * @param fileNamePattern * @return */ static String getValidFileNamePattern(String fileNamePattern) { if (fileNamePattern == null) { return null; } StringBuilder sb = new StringBuilder(fileNamePattern); if (!fileNamePattern.startsWith("\"") && !fileNamePattern.startsWith("'")) { sb.insert(0, "\""); } if (!fileNamePattern.endsWith("\"") && !fileNamePattern.endsWith("'")) { sb.append("\""); } return sb.toString(); } /** * 执行远程命令 * @param host * @param userName * @param password * @param command * @param commandEncoding 发送命令时使用的编码:utf-8 , gbk ....,结果读取时默认用gbk */ public static List<String> executeCommand(String host, String userName, String password, String command, String commandEncoding, String resultEncoding) { LinuxSession session = getSession(host, userName, password); List<String> output = new ArrayList<String>(); execCommand(session, command, commandEncoding, resultEncoding, new LinuxUtils2.ResultToListCommandCallBack(output)); close(session); return output; } /** * 执行远程命令 * @param host * @param userName * @param password * @param command * @param callBack 可以为null */ public static void execCommand(String host, String userName, String password, String command, CommandCallBack<LinuxSession> callBack) { LinuxSession session = getSession(host, userName, password); execCommand(session, command, "UTF-8", "GBK", callBack); close(session); } public static void execCommand(String host, String userName, String password, String command, String commandEncoding, CommandCallBack<LinuxSession> callBack) { LinuxSession session = getSession(host, userName, password); execCommand(session, command, commandEncoding, "GBK", callBack); close(session); } static byte[] str2byte(String str, String encoding){ if(str==null) return null; try{ return str.getBytes(encoding); } catch(java.io.UnsupportedEncodingException e){ return str.getBytes(); } } private static void execCommand(LinuxSession session, String command, CommandCallBack<LinuxSession> callBack) { // execCommand(session, command, "UTF-8", "GBK", callBack); } private static void execCommand(LinuxSession session, String command, String commandEncoding, String resultEncoding, CommandCallBack<LinuxSession> callBack) { ExceptionUtils.throwIfEmpty(command, "错误:命令为空"); ChannelExec channelExec = null; try { ExecuteShellResult result = new ExecuteShellResult(); session.setResult(result); channelExec = session.openChannel(); //channelExec.setCommand(command); channelExec.setCommand(str2byte(command, commandEncoding)); ByteArrayOutputStream os = new ByteArrayOutputStream(); channelExec.setOutputStream(os); ByteArrayOutputStream eos = new ByteArrayOutputStream(); channelExec.setErrStream(eos); channelExec.connect(); if (logger.isDebugEnabled()) { logger.debug("远程调用Shell 脚本:" + command); } // 等 0.1 秒. TimeUnit.MILLISECONDS.sleep(100); while (!channelExec.isClosed()) { TimeUnit.SECONDS.sleep(5); } result.exitValue = channelExec.getExitStatus(); if (os != null && os.size() > 0) { result.result = os.toString(resultEncoding); } if (eos != null && eos.size() > 0) { result.errorResult = eos.toString(); } if (callBack != null) { callBack.handle(session); } os.close(); eos.close(); } catch (Exception e) { if (isNoPermissionError(e)) { throw new BusinessException("用户权限不够,请更换用户"); } throw new UnknownException(e); } finally { if (channelExec != null) channelExec.disconnect(); } } /** * 取得链接 * * @param host * @param userName * @param password * @return */ private static LinuxSession getSession(String host, String userName, String password) { ExceptionUtils.throwIfEmpty(host, "建立远程连接出错,远程地址不能为空"); return new LinuxSession(host, userName, password); } /** * @author only openSession(),close can be used */ static public class LinuxSession { com.jcraft.jsch.Session sshSession; String host; String userName; String password; int port = 22; ExecuteShellResult result; public LinuxSession(String host, String userName, String password) { this.host = host; this.userName = userName; this.password = password; createConnection(); } public void setResult(ExecuteShellResult result) { this.result = result; } public ChannelExec openChannel() { return openChannel("exec"); } public ChannelExec openChannel(String type) { try { return (ChannelExec) sshSession.openChannel(type); } catch (JSchException e) { throw new UnknownException("打开通道出错", e); } } private void createConnection() { try { JSch jsch = new JSch(); sshSession = jsch.getSession(userName, host, port); if (password != null) { sshSession.setPassword(password); } else { String privateKey = "/home/" + userName + "/.ssh/id_rsa"; jsch.addIdentity(privateKey); } Properties sshConfig = new Properties(); // "StrictHostKeyChecking"如果设为"yes", // ssh将不会自动把计算机的密匙加入"$HOME/.ssh/known_hosts"文件, // 且一旦计算机的密匙发生了变化,就拒绝连接。 sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); synchronized (sessions) { sessions.put(this, System.currentTimeMillis()); } } catch (Exception e) { throw new BusinessException("建立远程连接出错:" + e.getMessage(), e); } } public synchronized void close() { sshSession.disconnect(); } } private static Map<LinuxSession, Long> sessions = new HashMap<LinuxSession, Long>(); private static class ConnectionMoniter implements Runnable { private static final long MAX_ALIVE_TIME = 90 * 1000; // 最大存活时间90秒种 private static final List<LinuxSession> deadConnections = new ArrayList<LinuxSession>(); public void run() { while (true) { try { synchronized (sessions) { if (!sessions.isEmpty()) { for (Iterator<LinuxSession> iterator = sessions.keySet().iterator(); iterator .hasNext();) { LinuxSession conn = iterator.next(); if ((System.currentTimeMillis() - sessions.get(conn)) >= MAX_ALIVE_TIME) { deadConnections.add(conn); } } } } if (deadConnections.size() > 0) { for (Iterator<LinuxSession> iterator = deadConnections.iterator(); iterator .hasNext();) { LinuxUtils2.close(iterator.next()); iterator.remove(); } } } catch (Throwable e) { // StringBuilder content = new StringBuilder(); // MailUtils.appendStackTrace(content, e); // MailUtils.sendMessage("异常信息邮件:远程连接监视器发生错误",content.toString()); } try { Thread.sleep(5000); } catch (Throwable e) { } } } } static {// 全程监视联接情况 new Thread(new ConnectionMoniter()).start(); } private static void close(Object connectionOrSession) { if (connectionOrSession == null) { return; } synchronized (sessions) { sessions.remove(connectionOrSession); if (connectionOrSession instanceof LinuxSession) { ((LinuxSession) connectionOrSession).close(); } else { throw new UnknownException("未知的对象类型,无法关闭"); } } } /** * Shell 脚本执行结果.<br> * 可以获取: <li>进程出口值. {@link ExecuteShellResult#getExitValue()} <br> <li> * 进程输出流输出的结果. {@link ExecuteShellResult#getResult()} <br> <li>进程错误输出流输出的结果. * {@link ExecuteShellResult#getErrorResult()} <br> */ public static class ExecuteShellResult { /** * 执行过程中没有异常. */ boolean isHasException; /** * 如果发生异常, cause 不能为空. */ // private Exception cause; // /** // * 进程的出口值。根据惯例,0 表示正常终止。 // */ int exitValue; /** * 进程输出流输出的结果. */ String result = ""; /** * 进程错误输出流输出的结果. */ String errorResult = ""; } public static void getRemoteDir(String host, String userName, String password, String remoteDir, String fileName, String localDir) { LinuxSession session = getSession(host, userName, password); List<String> files = findByFileNames(session, remoteDir, new String[] { fileName }); close(session); Connection connection = LinuxUtils.getConnection(host, userName, password); if (!files.get(0).isEmpty()) { getRemoteDir(connection, remoteDir, files, localDir, null); } LinuxUtils.close(connection); } private static File getRemoteDir(Connection connection, String remoteDir, final List<String> files, String localDir, ITransferFileListener listener) { ExceptionUtils.throwIfEmpty(localDir, "错误:本地目录文件名为空"); File dir = new File(localDir); if (files.size() == 0) { return dir;//没有下载到有文件 } //同名类,要先放起来,逐个取,因为取回来是放在同一目录的,所以不能一起取 List<String> tongMingLeis = new ArrayList<String>(5); //装所有类名,用来判断是否重复 List<String> tempList = new ArrayList<String>(files.size()); //如果有内部类,把类名加入“\\”,否则取时会出错 for (int i = 0; i < files.size(); i++) { String clazz = files.get(i); if (clazz.contains("$")) { files.set(i, clazz.replace("$", "\\$")); } String clazzName = clazz.replace('\\', '/'); //文件名 if (clazzName.contains("/")) { clazzName = clazzName.substring(clazzName.lastIndexOf('/')); } if (tempList.contains(clazzName)) { //加入同名类中 tongMingLeis.add(clazz); //从批量取的集合中去除,后面另外单独取 files.remove(i); i--; } //装到集合中 tempList.add(clazzName); } //用完了,释放集合 tempList = null; //装到数组中 String[] array = files.toArray(new String[files.size()]); //创建本地文件夹 if (!dir.exists()) { dir.mkdirs(); } //创建客户端 SCPClient client = new SCPClient(connection); try { //分批取文件,每批100个 int maxCount = 100; String[] dest = new String[100]; for (int i = 0; (i * maxCount) < array.length; i++) { if (array.length < ((i + 1) * maxCount)) {//改成分批进行,太多了SCP时会出错 dest = new String[array.length - i * maxCount]; } System.arraycopy(array, i * maxCount, dest, 0, dest.length); if (listener != null) { listener.transferFileMsg("正在获取文件:" + dest[0]); } //取文件 client.get(dest, localDir); } //把文件从“dir”这个目录放回到原来的目录结构中 moveToOrigalPath(files, remoteDir, localDir); //取同名类回来,同名类中不论是否多次同名,每次取一个,主要是为了编程简单, for (String file : tongMingLeis) { try { //取回单个文件,放在当前目录中 getRemoteFile(connection, file, localDir, listener); } catch (Exception e) { if (isNoPermissionError(e)) { throw new BusinessException("用户权限不够,请更换用户"); } else if (isNotARegularFile(e)) {//可能是一个文件夹,取不回来,那么直接在本址建文件夹好了 String filePath = file.replace(remoteDir, ""); filePath = filePath.replace("\\$", "$"); //以localDir为基准,恢复原来的层次结构 File toFile = new File(localDir + filePath); toFile.mkdirs(); continue; } else { throw new UnknownException(e); } } //把文件从“dir”这个目录放回到原来的目录结构中 moveToOrigalPath(Arrays.asList(new String[] { file }), remoteDir, localDir); } return dir; } catch (IOException e) { if (isNoPermissionError(e)) { throw new BusinessException("用户权限不够,请更换用户"); } throw new UnknownException(e); } } /** * 提示不规则文件错 * @param e * @return */ static boolean isNotARegularFile(Throwable e) { while (e != null) { if (e.getMessage() != null && e.getMessage().contains("not a regular file")) { return true; } e = e.getCause(); } return false; } /** * 把文件搬回到原来的位置 * 1、文件已全都放在localDir中,没有层次 * 2、把remoteFiles中的字符串删除掉remoteDir字符串,即得到文件本来的目录层次 * 3、将这个层次前面加上localDir中,即保留了原来的目录层次 * @param remoteFiles * @param remoteDir * @param localDir */ static void moveToOrigalPath(List<String> remoteFiles, String remoteDir, String localDir) { if (remoteFiles.size() == 0) { return; } for (String filePath : remoteFiles) { //把remoteFiles中的字符串删除掉remoteDir字符串,即得到文件本来的目录层次 filePath = filePath.replace(remoteDir, ""); filePath = filePath.replace("\\$", "$"); filePath = filePath.replace('\\', '/'); //文件名 String fileName = filePath.substring(filePath.lastIndexOf('/')); //文件已全都放在localDir中,没有层次,所以下面的代码可以得到当前文件绝对路径 File fromFile = new File(localDir + fileName); //以localDir为基准,恢复原来的层次结构 File toFile = new File(localDir + filePath); //建父文件夹 File parentFile = toFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } try { //移动文件 FileUtils.copyFile(fromFile, toFile); com.alipay.aqc.common.util.FileUtils.deleteFile(fromFile); } catch (IOException e) { } } } static boolean isNoPermissionError(Exception e) { if (e == null) { return false; } if (e.getMessage() == null) { return false; } if (e.getMessage().contains("Permission denied")) { return true; } if (e.getCause() != null && e.getCause().getMessage() != null && e.getCause().getMessage().contains("Permission denied")) { return true; } return false; } public static boolean isEndWithPathSeperator(String dirName) { if (dirName.endsWith("/")) { return true; } if (dirName.endsWith("\\")) { return true; } return false; } /** * 取回单个文件 * @param connection * @param fullFileName 不能是目录 * @param localDir * @return */ private static File getRemoteFile(Connection connection, String fullFileName, String localDir, ITransferFileListener listener) { ExceptionUtils.throwIfEmpty(fullFileName, "错误:远程文件名为空"); ExceptionUtils.throwIfEmpty(localDir, "错误:本地目录文件名为空"); File dir = new File(localDir); if (!dir.exists()) { dir.mkdirs(); } SCPClient client = new SCPClient(connection); try { if (listener != null) { listener.transferFileMsg("正在获取文件:" + fullFileName); } client.get(fullFileName, localDir); fullFileName = fullFileName.replace('\\', '/'); fullFileName = fullFileName.substring(fullFileName.lastIndexOf('/') + 1); return new File(isEndWithPathSeperator(localDir) ? localDir + fullFileName : localDir + File.separator + fullFileName); } catch (IOException e) { if (isNoPermissionError(e)) { throw new BusinessException("用户权限不够,请更换用户"); } throw new UnknownException(e); } } } |
|||
读取并操作Excel的实例 | java excel | ||
//引用了ExcelUtils的create方法,处理不同版本excel的兼容 import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.POIXMLDocument; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.alipay.aqc.common.exception.BusinessException; import com.alipay.aqc.common.util.ExcelUtils; import com.alipay.aqc.common.util.FileUtils; import com.alipay.aqc.defect.DefectConstants; import com.alipay.aqc.defect.biz.FaultManager; import com.alipay.aqc.defect.biz.FaultMemberManager; import com.alipay.aqc.defect.dal.model.Fault; import com.alipay.aqc.defect.wf.biz.WorkFlowManager; @Service public class WorkFlowManagerImpl implements WorkFlowManager{ private static final Log logger = LogFactory.getLog(WorkFlowManagerImpl.class); private static final String FAULT_CODE = "故障编号"; private static final String FAULT_TITLE = "故障标题"; private static final String FAULT_SEVERITY = "故障级别"; private static final String FAULT_GROUP = "主要责任部门"; private static final String[] EXTENSIONS = { ".xls", ".xlsx" }; @Autowired private FaultManager faultManager; @Autowired private FaultMemberManager faultMemberManager; private int locateColumnByTitle(Row headerRow, String columnName){ Cell cell = null; for(int i = 0; i<= headerRow.getLastCellNum(); i++){ cell = headerRow.getCell(i); if(cell != null && cell.getStringCellValue() != null){ if(columnName.equals(cell.getStringCellValue())){ return i; } } } logger.warn("未能在WFExcel中找到列名【" + columnName + "】,系统将会忽略此列!"); return -1; } @Override public List<String> importData(String filePath, String fileName) { List<String> resultMsg = new ArrayList<String>(); File file = new File(FileUtils.getUploadFilePath(filePath)); if(!isValidedFileExtension(fileName)){ resultMsg.add("文件格式不正确, 上传文件必须为.xls或.xlsx!"); return resultMsg; } String formatFileName = new StringBuffer("【文件名: ").append(fileName).append("】").toString(); String msg = null; InputStream is = null; Workbook wb = null; try { is = new FileInputStream(file); wb = ExcelUtils.create(is); } catch (Throwable t) { msg = new StringBuffer(formatFileName).append("读取失败: ").append(t.getMessage()).toString(); logger.error(msg, t); resultMsg.add(msg); return resultMsg; } Sheet sheet = wb.getSheetAt(0); //定位Header中的字段 Row headerRow = sheet.getRow(0); if(headerRow == null){ resultMsg.add("【文件名: " + fileName + "】第一行未发现标题头,您的Excel也许为空或者不符合规范格式!"); return resultMsg; } //若无标题列则返回 int faultTitleIndex = locateColumnByTitle(headerRow, FAULT_TITLE); if(faultTitleIndex == -1){ msg = new StringBuffer(formatFileName).append(",未发现\"").append(FAULT_TITLE) .append("\",系统视此文件为无效数据文件!").toString(); logger.info(msg); resultMsg.add(msg.toString()); return resultMsg; } int faultCodeIndex = locateColumnByTitle(headerRow, FAULT_CODE); int faultSeverityIndex = locateColumnByTitle(headerRow, FAULT_SEVERITY); int faultGroupIndex = locateColumnByTitle(headerRow, FAULT_GROUP); Fault fault = null; logger.info("========================= 【文件名:"+fileName+"】开始导入Excel数据 ======================"); int counter = 1; //逐行处理数据 for(int j = 1; j<= sheet.getLastRowNum(); j++){ logger.info("-------------导入第" + counter +"条数据---------------------------------------"); fault = new Fault(); Row row = sheet.getRow(j); if(faultTitleIndex != -1){ Cell faultTitleCell = row.getCell(faultTitleIndex); if(faultTitleCell != null && StringUtils.isNotBlank(faultTitleCell.getStringCellValue())){ fault.setTitle(faultTitleCell.getStringCellValue()); }else{ msg = new StringBuffer(formatFileName).append("第").append(j+1).append("行\"") .append(FAULT_TITLE).append("\"列为空,系统忽略此行!").toString(); resultMsg.add(msg); continue; } logger.info("第"+(j +1) + "行【" + FAULT_TITLE +"】列: " + faultTitleCell.getStringCellValue()); } if(faultCodeIndex != -1){ Cell faultCodeCell = row.getCell(faultCodeIndex); if(faultCodeCell != null){ fault.setCode(faultCodeCell.getStringCellValue()); logger.info("第"+(j +1) + "行【" + FAULT_CODE +"】列: " + faultCodeCell.getStringCellValue()); } } if(faultSeverityIndex != -1){ Cell faultSeverityCell = row.getCell(faultSeverityIndex); if(faultSeverityCell != null){ fault.setSeverity(faultSeverityCell.getStringCellValue().trim()); logger.info("第"+(j +1) + "行【" + FAULT_SEVERITY +"】列: " + faultSeverityCell.getStringCellValue()); } } if(faultGroupIndex != -1){ Cell faultGroupCell = row.getCell(faultGroupIndex); if(faultGroupCell != null){ fault.setGroup(faultGroupCell.getStringCellValue()); logger.info("第"+(j +1) + "行【" + FAULT_GROUP +"】列: " + faultGroupCell.getStringCellValue()); } } fault.setStatus(DefectConstants.DEFAULT_FAULT_STATUS_KEY);//open fault.setOwnerId(DefectConstants.USER_ID_TANGYUE);//塘月 fault.setCreatedBy(DefectConstants.USER_ID_AQC); try{ faultManager.save(fault, DefectConstants.DEFAULT_FAULT_MEMBER_IDS); }catch(BusinessException be){ //缺陷已存在 if(StringUtils.isNotBlank(be.getMessage()) && be.getMessage().contains(DefectConstants.FAULT_EXISTED_MESSAGE)){ msg = new StringBuffer("缺陷【").append(fault.getCode()).append("】已存在!").toString(); resultMsg.add(msg); logger.info(msg); continue; }else{ throw be; } } counter++; logger.info("------------------------------------------------------------------------------"); } msg = new StringBuffer(formatFileName).append(", 共导入").append(counter-1).append("条缺陷").toString(); String result = "====================" + msg + "======================"; logger.info(result); resultMsg.add(msg); return resultMsg; } private static boolean isValidedFileExtension(String filePath) { for (int i = 0, length = EXTENSIONS.length; i < length; i++) { if (filePath.endsWith(EXTENSIONS[i])) { return true; } } return false; } } |
|||
ExcelUtils类 | java excel | ||
//ExcelUtils类 import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.POIXMLDocument; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelUtils { /** 简单中文格式 yyyy年MM月dd日*/ public final static String chineseDtFormat = "yyyy年MM月dd日"; private static final Log logger = LogFactory.getLog(ExcelUtils.class); private static final String STATUS_KEY = "error"; private static final String STATUS_CODE_SUCCESS = "0"; private static final String STATUS_CODE_FAIL = "1"; private static final String RESULT_KEY = "message"; private static final String[] EXTENSIONS = { ".xls", ".xlsx" }; /** * @param dataList 输出数据列表 ,数据对象要有public的get方法 * @param defineMapping 数据定义 {{"XX商家名","supplierName","100"},{"XX商家ID","supplierID" ,"100"},{"表头名称","对象属性","列宽"}...} * @param headRowNumStart 开始写入表头的行索引 * @param dataRowNumStart 开始写入数据的行索引 * @param sheetName 生成sheet页的名字 * @return Map 包括当前workbook和sheet及下次写入数据的开始行数 */ public static Map<String, Object> defaultExport(List<?> dataList, String[][] defineMapping, int headRowNumStart, int dataRowNumStart, String sheetName) throws Exception { // 创建book Workbook wb = new XSSFWorkbook(); // 表头单元格边STYLE CellStyle headStyle = getDefautHeaderStyle(wb); // 数据 单元格STYLE CellStyle dataStyle = getDefautDataStyle(wb); // 创建 包裹信息sheet Sheet sheet = wb.createSheet(sheetName); String[] titles = new String[defineMapping.length]; String[] properties = new String[defineMapping.length]; String[] widths = new String[defineMapping.length]; for (int i = 0; i < defineMapping.length; i++) { // 表头 titles[i] = defineMapping[i][0]; // 数据映射对象属性 properties[i] = defineMapping[i][1]; if (defineMapping[i].length > 2) { // 列宽 widths[i] = defineMapping[i][2]; } } // 判断是否设置了列宽 if (defineMapping[0].length > 2) { for (int j = 0; j < widths.length; j++) { sheet.setColumnWidth(j, Integer.valueOf(widths[j]) * 38); } } // writeHeader writeRow(sheet, titles, headStyle, headRowNumStart); // writeData int dataRowNumNext = writeNewRow(sheet, dataList, properties, dataStyle, dataRowNumStart); Map<String, Object> map = new HashMap<String, Object>(); map.put("workbook", wb); map.put("sheet", sheet); map.put("dataRowNumNext", dataRowNumNext); return map; } /** * 创建头部的默认样式 * * @param wb * @return */ public static CellStyle getDefautHeaderStyle(Workbook wb) { CellStyle style = wb.createCellStyle(); Font font = wb.createFont(); font.setBoldweight((short) 900); font.setColor(IndexedColors.GREEN.getIndex()); font.setFontName("宋体"); // 线条 style.setBorderBottom(CellStyle.BORDER_THIN); style.setBorderLeft(CellStyle.BORDER_THIN); style.setBorderRight(CellStyle.BORDER_THIN); style.setBorderTop(CellStyle.BORDER_THIN); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFont(font); style.setAlignment(CellStyle.ALIGN_LEFT); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setWrapText(true); return style; } /** * 写数组数据到一个excel行 * * @param sheet * @param values * @param style * @param rowNum */ public static void writeRow(Sheet sheet, String[] values, CellStyle style, int rowNum) { Row row = sheet.createRow(rowNum); for (int i = 0; i < values.length; i++) { Cell cell = row.createCell(i, Cell.CELL_TYPE_STRING); cell.setCellValue(values[i]); if (style != null) { cell.setCellStyle(style); } } } public static int writeNewRow(Sheet sheet, List<?> dataList, String[] properties, CellStyle style, int rowNumStart) throws Exception { if (dataList != null && dataList.size() > 0) { Class<?> cls = dataList.get(0).getClass(); Method[] objMds = new Method[properties.length]; int i = 0; for (String prop : properties) { objMds[i] = cls.getDeclaredMethod("get" + prop.substring(0, 1).toUpperCase() + prop.substring(1)); i++; } for (Object dataObj : dataList) { Row row = sheet.createRow(rowNumStart); rowNumStart++; for (i = 0; i < objMds.length; i++) { Cell cell = row.createCell(i, Cell.CELL_TYPE_STRING); Object value = objMds[i].invoke(dataObj); setCellValue(cell, value); if (style != null) { cell.setCellStyle(style); } } } } return rowNumStart; } /** * 给格子设置值 * * @param cell * @param value */ public static void setCellValue(Cell cell, Object value) { if (value == null) { cell.setCellValue(""); } else if (value instanceof Float) { // 转成string,不然Excle显示的不一样 cell.setCellValue(value.toString()); } else if (value instanceof Double) { // 转成string,不然Excle显示的会不一样 cell.setCellValue(value.toString()); } else if (value instanceof Boolean) { cell.setCellValue((Boolean) value); } else if (value instanceof Date) { cell.setCellValue(new SimpleDateFormat(chineseDtFormat).format(value)); } else { String content = value.toString(); if (StringUtils.isNotEmpty(content)) { cell.setCellValue(content); } } } /** * 设置默认数据部分格式 * * @param wb * @return */ public static CellStyle getDefautDataStyle(Workbook wb) { CellStyle style = wb.createCellStyle(); // style.setWrapText(true); style.setAlignment(CellStyle.ALIGN_LEFT); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBorderLeft(CellStyle.BORDER_THIN); style.setBorderRight(CellStyle.BORDER_THIN); style.setBorderTop(CellStyle.BORDER_THIN); // 默认不设置 return style; } /** * @param dataList 输出数据列表 ,数据对象要有public的get方法 * @param defineMapping 数据定义 {{"XX商家名","supplierName","100"},{"XX商家ID","supplierID" ,"100"},{"表头名称","对象属性","列宽"}...} * @param headRowNumStart 开始写入表头的行索引 * @param dataRowNumStart 开始写入数据的行索引 * @param mapInfo 包括当前workbook和新sheet页的名字 * @return Map 包括当前workbook */ public static Map<String, Object> exportNewSheet(List<?> dataList, String[][] defineMapping, int headRowNumStart, int dataRowNumStart, Map<String, Object> mapInfo) throws Exception { Workbook wb = (Workbook) mapInfo.get("workbook"); // 表头单元格边STYLE CellStyle headStyle = getDefautHeaderStyle(wb); // 数据 单元格STYLE CellStyle dataStyle = getDefautDataStyle(wb); // 创建 包裹信息sheet Sheet sheet = wb.createSheet((String) mapInfo.get("newSheetName")); String[] titles = new String[defineMapping.length]; String[] properties = new String[defineMapping.length]; String[] widths = new String[defineMapping.length]; for (int i = 0; i < defineMapping.length; i++) { // 表头 titles[i] = defineMapping[i][0]; // 数据映射对象属性 properties[i] = defineMapping[i][1]; if (defineMapping[i].length > 2) { // 列宽 widths[i] = defineMapping[i][2]; } } // 判断是否设置了列宽 if (defineMapping[0].length > 2) { for (int j = 0; j < widths.length; j++) { sheet.setColumnWidth(j, Integer.valueOf(widths[j]) * 38); } } // writeHeader writeRow(sheet, titles, headStyle, headRowNumStart); // writeData writeNewRow(sheet, dataList, properties, dataStyle, dataRowNumStart); Map<String, Object> map = new HashMap<String, Object>(); map.put("workbook", wb); return map; } /*** * 描述:解析已经上传的文件 返回List * 1、查询数据库中所有的属性名称 2、加载已经上传的文件 3、对上传的文件进行是否重名判断、已经存在的则不做写入操作,但把未处理的结果记录并返回 * 4、处理完已上传的文件 5、删除当前的文件 * * @param fileUrl * @param status * @author wen.yuanw * @return 返回处理结果 如果都写入成功,则返回处理成功;如果是部分成功,则把处理失败的结果展示出来 */ public static List<List<String>> convertFromFile(String filePath,Map<String,String> status,List<String> title){ // 已上传文件输入流, 该文件位于上传目录web_upload_files当中 InputStream inputStream = null; // 解析成功的数据行数 int successCount = 0; int errorCount = 0; List<List<String>> excelList = new ArrayList<List<String>>(); if (StringUtils.isBlank(filePath)) { status.put(STATUS_KEY, STATUS_CODE_FAIL); status.put(RESULT_KEY, "解析文件名不能为空!"); return null; }else if (!isValidedFileExtension(filePath)) { status.put(STATUS_KEY, STATUS_CODE_FAIL); status.put(RESULT_KEY, "文件格式不正确, 上传文件必须为.xls或.xlsx"); deleteUploadedFile(filePath); return null; } try { File file = new File(FileUtils.getUploadFilePath(filePath)); if (!file.exists()) { status.put(STATUS_KEY, STATUS_CODE_FAIL); status.put(RESULT_KEY, "当前解析文件不存在!"); return null; } // 获得文件输出流 inputStream = new FileInputStream(file); // 创建工作薄 Workbook workbook = create(inputStream); // 获取第一张excel表格 Sheet sheet = workbook.getSheetAt(0); // 获取excel总行数 int totalRow = sheet.getPhysicalNumberOfRows(); Row row = null; // excel总列数 int lineCount = 0; if(CollectionUtils.isNotEmpty(title)){ // 获取Excel第0行 row = sheet.getRow(0); if (null == row) { status.put(STATUS_KEY, STATUS_CODE_FAIL); status.put(RESULT_KEY, "文件无内容!"); return null; } for (int j = 0; j < title.size(); j++) { if(!title.get(j).equals(row.getCell(j))){ status.put(STATUS_KEY, STATUS_CODE_FAIL); status.put(RESULT_KEY, "文件标题格式错误,请根据模版填写!"); return null; } } } // 起始行为第1行,忽略表头 for (int i = 1; i < totalRow; i++) { try { // excel当前行数据集 List<String> visitValueList = new ArrayList<String>(); // 获取Excel第i行 row = sheet.getRow(i); // 空行则继续下一行 if (null == row) { logger.info("VisitManagerImpl-->importExcel()解析的文件存在空行"); continue; } // 获取当前行列数 lineCount = row.getLastCellNum(); Cell currentCell = null; for (int j = 0; j < lineCount; j++) { // 获取当第i行第j列单元格 currentCell = row.getCell(j); if (null != currentCell) { // 获取当前单元格数据 visitValueList.add(getValue(currentCell)); } } if (CollectionUtils.hasNotEmptyElement(visitValueList)) { excelList.add(visitValueList); successCount++; } }catch (Exception ex) { errorCount++; logger.error("VisitManagerImpl-->importExcel() 单行出现异常:", ex); } } status.put(STATUS_KEY, STATUS_CODE_SUCCESS); status.put("successCount",Integer.toString(successCount)); status.put("errorCount", Integer.toString(errorCount)); } catch (Exception ex) { logger.error("VisitManagerImpl-->importExcel() 出现异常:", ex); status.put(STATUS_KEY, STATUS_CODE_FAIL); status.put(RESULT_KEY, "文件解析异常!"); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } /** 清理掉上传的临时文件 **/ FileUtils.deleteQuietly(new File(FileUtils .getUploadFilePath(filePath))); } return excelList; } /** * 是否有有效的上传文件扩展名 * * @param filePath * @return */ private static boolean isValidedFileExtension(String filePath) { for (int i = 0, length = EXTENSIONS.length; i < length; i++) { if (filePath.endsWith(EXTENSIONS[i])) { return true; } } return false; } /** * 删除已上传的临时文件 * * @param filePath */ private static void deleteUploadedFile(String filePath) { /** 清理掉上传的临时文件 **/ FileUtils.deleteQuietly(new File(FileUtils.getUploadFilePath(filePath))); } /** * 描述:对excel表中的数据进行转换 * * @param hssfCell * @return 以字符串的格式输出 */ @SuppressWarnings("static-access") private static String getValue(Cell hssfCell) { if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) { // 返回布尔类型的值 return String.valueOf(hssfCell.getBooleanCellValue()).trim(); } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) { // 返回数值类型的值 return String.valueOf(hssfCell.getNumericCellValue()).trim(); } else { // 返回字符串类型的值 return String.valueOf(hssfCell.getStringCellValue()).trim(); } } /** * 读写xls和xlsx格式时,HSSFWorkbook针对xls,XSSFWorkbook针对xlsx * @param in * @return * @throws IOException * @throws InvalidFormatException */ public static Workbook create(InputStream in) throws IOException,InvalidFormatException { if (!in.markSupported()) { in = new PushbackInputStream(in, 8); } if (POIFSFileSystem.hasPOIFSHeader(in)) { return new HSSFWorkbook(in); } if (POIXMLDocument.hasOOXMLHeader(in)) { return new XSSFWorkbook(OPCPackage.open(in)); } throw new IllegalArgumentException("你的excel版本目前poi解析不了"); } } |