Java tutorial
/** The MIT License (MIT) * Copyright (c) 2016 (mingsoft.net) * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mingsoft.weixin.util; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import com.alibaba.fastjson.JSONArray; import com.mingsoft.basic.entity.AppEntity; import com.mingsoft.cms.entity.ArticleEntity; import com.mingsoft.parser.IParserRegexConstant; import com.mingsoft.util.MD5Util; import com.mingsoft.util.StringUtil; import com.mingsoft.weixin.bean.NewsBean; import com.mingsoft.weixin.bean.UploadNewsBean; import com.mingsoft.weixin.entity.NewsEntity; /** * mswx-? * Copyright: Copyright (c) 2014 - 2015 * Company:?? * @author wangtp * @version 300-001-001 * ? * Comments: ??(XML)???str2xml,xml2str * Create Date:2013-12-23 * Modification history: */ public class XmlUtils { /** * list? */ private static String NEWS_ERR = "items size err"; /** * ? */ public static final String DUO_KE_FU = "transfer_customer_service"; /** * log4j */ protected final static Logger LOG = Logger.getLogger(XmlUtils.class); /** * ??? * * @param toUser * ??OpenID * @param fromUser * ?? * @param items * ???item,?10? * @return String -????(?)? * @see ?? * :http://mp.weixin.qq.com/wiki/index.php?title=%E5%8F%91%E9%80%81% * E8%A2%AB%E5%8A%A8%E5%93%8D%E5%BA%94%E6%B6%88%E6%81%AF#.E5.9B * .9E.E5.A4.8D.E5.9B.BE.E6.96.87.E6.B6.88.E6.81.AF ? * XmlUtils.buildText(XmlUtils.getString(postStr, "FromUserName"), * XmlUtils.getString(postStr, "ToUserName"),list); */ public static String buildXmlNews(String toUser, String fromUser, NewsEntity news) { //? AppEntity app = news.getApp(); //??host String host = app.getAppHostUrl(); //??hostUrl; String hostUrl = ""; LOG.debug("host??=======" + host); if (!StringUtil.isBlank(app.getAppMobileStyle())) { hostUrl = host + File.separator + IParserRegexConstant.HTML_SAVE_PATH + File.separator + app.getAppId() + File.separator + IParserRegexConstant.MOBILE + File.separator; } int size = 1; StringBuffer sb = new StringBuffer(); sb.append("<xml>"); sb.append("<ToUserName><![CDATA[").append(toUser).append("]]></ToUserName>"); sb.append("<FromUserName><![CDATA[").append(fromUser).append("]]></FromUserName>"); sb.append("<CreateTime><![CDATA[").append(new Date().getTime()).append("]]></CreateTime>"); sb.append("<MsgType><![CDATA[").append("news").append("]]></MsgType>"); if (news != null && news.getNewsMasterArticle() != null) { // ?? if (news.getChilds() != null && news.getChilds().size() > 0) { size += news.getChilds().size(); } sb.append("<ArticleCount>").append(size).append("</ArticleCount>"); sb.append("<Articles>"); // ? sb.append("<item>"); sb.append("<Title><![CDATA[").append(news.getNewsMasterArticle().getBasicTitle()).append("]]></Title>");// ?ISO?? sb.append("<Description><![CDATA[").append(news.getNewsMasterArticle().getBasicDescription()) .append("]]></Description>");// ???ISO?? sb.append("<PicUrl><![CDATA[").append(host + news.getNewsMasterArticle().getBasicThumbnails()) .append("]]></PicUrl>"); if (!StringUtil.isBlank(news.getNewsLink())) { //???? sb.append("<Url><![CDATA[").append(news.getNewsLink()).append("]]></Url>"); } else { sb.append("<Url><![CDATA[").append(hostUrl + news.getNewsMasterArticle().getArticleUrl()) .append("]]></Url>");//?? } sb.append("</item>"); if (size > 1) { for (ArticleEntity article : news.getChilds()) { sb.append("<item>"); sb.append("<Title><![CDATA[").append(article.getBasicTitle()).append("]]></Title>");// ?ISO?? sb.append("<Description><![CDATA[").append(article.getBasicDescription()) .append("]]></Description>");// ???ISO?? sb.append("<PicUrl><![CDATA[").append(host + article.getBasicThumbnails()) .append("]]></PicUrl>"); sb.append("<Url><![CDATA[").append(hostUrl + article.getArticleUrl()).append("]]></Url>"); sb.append("</item>"); } } sb.append("</Articles>"); } else { if (size > 10) { return NEWS_ERR; } } sb.append("</xml>"); return sb.toString(); } /** * ??? * * @param toUser * ??OpenID * @param items * ???item,?10? * @return String -????(?)? * @see ?? * :http://mp.weixin.qq.com/wiki/index.php?title=%E5%8F%91%E9%80%81%E5%AE%A2%E6%9C%8D%E6%B6%88%E6%81%AF#.E5.8F.91.E9.80.81.E5.9B.BE.E6.96 .87.E6.B6.88.E6.81.AF ? * XmlUtils.buildText(XmlUtils.getString(postStr, "FromUserName"), * XmlUtils.getString(postStr, "ToUserName"),list); */ public static String buildJsonNews(String toUser, List<NewsBean> items) { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"touser\":\"").append(toUser).append("\","); sb.append("\"msgtype\":\"news\","); sb.append("\"news\":{"); sb.append("\"articles\":"); if (items != null && !(items.size() > 10)) { sb.append(JSONArray.toJSONString(items)); } else { if (items.size() > 10) { return NEWS_ERR; } else { sb.append("[]"); } } sb.append("}}"); return sb.toString(); } /** * ?? * * @param items * ???item,?10? * @return String -? */ public static String uploadJsonNews(List<UploadNewsBean> items) { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"articles\":"); if (items != null && !(items.size() > 10)) { sb.append(JSONArray.toJSONString(items)); } else { if (items.size() > 10) { return NEWS_ERR; } else { sb.append("[]"); } } sb.append("}}"); return sb.toString(); } /** * ?? * * @param toUser * ??OpenID * @param mediaId * ??media_id * @return String -?? */ public static String PreviewJsonMessageMASS(String openId, String mediaId) { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"touser\":\"").append(openId).append("\","); sb.append("\"msgtype\":\"mpnews\","); sb.append("\"mpnews\":{"); sb.append("\"media_id\":\"").append(mediaId).append("\""); sb.append("}}"); return sb.toString(); } /** * ??? * * @param mediaId * ??media_id * @param bool * ?? * @param gourpId * ID??? * @return String -??? */ public static String SendAllJsonMessageMass(String mediaId, Boolean bool, String gourpId) { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"msgtype\":\"mpnews\","); sb.append("\"mpnews\":{"); sb.append("\"media_id\":\"").append(mediaId).append("\""); sb.append("},"); sb.append("\"filter\":{"); sb.append("\"is_to_all\":").append(bool); sb.append("\"group_id\":\"").append(gourpId).append("\""); sb.append("}}"); return sb.toString(); } /** * ???? * * @param msgId * ??? * @return String -?????? */ public static String getJsonMessageMass(String msgId) { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"msg_id\":\"").append(msgId).append("\""); sb.append("}"); return sb.toString(); } /** * ???ID * * @param templateIdShort * ?? * @return String -??ID? */ public static String getJsonTempleteId(String templateIdShort) { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"template_id_short\":\"").append(templateIdShort).append("\""); sb.append("}"); return sb.toString(); } /** * ?? * * @param toUser * ??OpenID * @param fromUser * ?? (?null) * @param items * ???item,?10? * @return String -????(?)? * @see ?? * :http://mp.weixin.qq.com/wiki/index.php?title=%E5%8F%91%E9%80%81% * E5%AE * %A2%E6%9C%8D%E6%B6%88%E6%81%AF#.E5.8F.91.E9.80.81.E5.9B.BE.E6.96 * .87.E6.B6.88.E6.81.AF ? * XmlUtils.buildText(XmlUtils.getString(postStr, "FromUserName"), * XmlUtils.getString(postStr, "ToUserName"),list); */ public static String buildJsonText(String toUser, String content) { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"touser\":\"").append(toUser).append("\","); sb.append("\"msgtype\":\"text\","); sb.append("\"text\":{"); sb.append("\"content\":\"").append(content).append("\""); sb.append("}}"); return sb.toString(); } /** * ??? * * @param toUser * * @param mediaId * ??id * @return */ public static String buildJsonImage(String toUser, String mediaId) { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"touser\":\"").append(toUser).append("\","); sb.append("\"msgtype\":\"image\","); sb.append("\"image\":{"); sb.append("\"media_id\":\"").append(mediaId).append("\""); sb.append("}}"); return sb.toString(); } /** * * ??? * * @param toUser * * @param mediaId * ??id * @return */ public static String buildJsonVoice(String toUser, String mediaId) { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"touser\":\"").append(toUser).append("\","); sb.append("\"msgtype\":\"voice\","); sb.append("\"voice\":{"); sb.append("\"media_id\":\"").append(mediaId).append("\""); sb.append("}}"); return sb.toString(); } /** * ??? * * @param toUser * ??OpenID,??FromUserName * @param fromUser * ?? ??ToUserName * @param content * ???content??? * @return String -????(?)? * @see ?? * :http://mp.weixin.qq.com/wiki/index.php?title=%E5%8F%91%E9%80%81% * E8%A2%AB%E5%8A%A8%E5%93%8D%E5%BA%94%E6%B6%88%E6%81%AF#.E5.9B * .9E.E5.A4.8D.E6.96.87.E6.9C.AC.E6.B6.88.E6.81.AF ? * XmlUtils.buildText(XmlUtils.getString(postStr, "FromUserName"), * XmlUtils.getString(postStr, "ToUserName"), ""); */ public static String buildXmlText(String toUser, String fromUser, String content) { StringBuffer sb = new StringBuffer(); sb.append("<xml>"); sb.append("<ToUserName><![CDATA[").append(toUser).append("]]></ToUserName>"); sb.append("<FromUserName><![CDATA[").append(fromUser).append("]]></FromUserName>"); sb.append("<CreateTime><![CDATA[").append(new Date().getTime()).append("]]></CreateTime>"); sb.append("<MsgType><![CDATA[").append("text").append("]]></MsgType>"); sb.append("<Content><![CDATA[").append(content).append("]]></Content>");// ?ISO?? sb.append("</xml>"); return sb.toString(); } /** * xml?,map * @param xml ??? * @return map? */ public static Map<String, Object> getXmlPayUnifiedOrder(String xml) { LOG.debug("getXmlPayUnifiedOrder xml" + xml); if (xml == null) { return null; } Map<String, Object> param = new HashMap<String, Object>(); String returnCode = XmlUtils.getString(xml, "return_code"); if (returnCode != null) { if (returnCode.equalsIgnoreCase("FAIL")) { param.put("return_code", returnCode); param.put("return_msg", XmlUtils.getString(xml, "return_msg")); } else if (returnCode.equalsIgnoreCase("SUCCESS")) { String resultCode = XmlUtils.getString(xml, "result_code"); if (resultCode != null && resultCode.equalsIgnoreCase("FAIL")) { param.put("return_code", returnCode); param.put("return_msg", XmlUtils.getString(xml, "return_msg")); param.put("appid", XmlUtils.getString(xml, "appid")); param.put("mch_id", XmlUtils.getString(xml, "mch_id")); param.put("device_info", XmlUtils.getString(xml, "device_info")); param.put("nonce_str", XmlUtils.getString(xml, "nonce_str")); param.put("sign", XmlUtils.getString(xml, "sign")); param.put("err_code", XmlUtils.getString(xml, "err_code")); param.put("err_code_des", XmlUtils.getString(xml, "err_code_des")); } else { param.put("return_code", returnCode); param.put("return_msg", XmlUtils.getString(xml, "return_msg")); param.put("appid", XmlUtils.getString(xml, "appid")); param.put("mch_id", XmlUtils.getString(xml, "mch_id")); param.put("device_info", XmlUtils.getString(xml, "device_info")); param.put("nonce_str", XmlUtils.getString(xml, "nonce_str")); param.put("sign", XmlUtils.getString(xml, "sign")); param.put("result_code", XmlUtils.getString(xml, "result_code")); param.put("openid", XmlUtils.getString(xml, "openid")); param.put("is_subscribe", XmlUtils.getString(xml, "is_subscribe")); param.put("trade_type", XmlUtils.getString(xml, "trade_type")); param.put("bank_type", XmlUtils.getString(xml, "bank_type")); param.put("total_fee", XmlUtils.getString(xml, "total_fee")); param.put("coupon_fee", XmlUtils.getString(xml, "coupon_fee")); param.put("fee_type", XmlUtils.getString(xml, "fee_type")); param.put("transaction_id", XmlUtils.getString(xml, "transaction_id")); param.put("out_trade_no", XmlUtils.getString(xml, "out_trade_no")); param.put("attach", XmlUtils.getString(xml, "attach")); param.put("time_end", XmlUtils.getString(xml, "time_end")); param.put("prepay_id", XmlUtils.getString(xml, "prepay_id")); param.put("code_url", XmlUtils.getString(xml, "code_url")); } } } param.put("err_code", XmlUtils.getString(xml, "err_code")); param.put("err_code_des", XmlUtils.getString(xml, "err_code_des")); return param; } public static Map<String, Object> getXmlPayOrderquery(String xml) { LOG.debug("getXmlPayOrderquery xml" + xml); if (xml == null) { return null; } Map<String, Object> param = new HashMap<String, Object>(); String returnCode = XmlUtils.getString(xml, "return_code"); if (returnCode != null) { if (returnCode.equalsIgnoreCase("FAIL")) { param.put("return_code", returnCode); param.put("return_msg", XmlUtils.getString(xml, "return_msg")); } else if (returnCode.equalsIgnoreCase("SUCCESS")) { String resultCode = XmlUtils.getString(xml, "result_code"); if (resultCode != null && resultCode.equalsIgnoreCase("FAIL")) { param.put("appid", XmlUtils.getString(xml, "appid")); param.put("mch_id", XmlUtils.getString(xml, "mch_id")); param.put("nonce_str", XmlUtils.getString(xml, "nonce_str")); param.put("sign", XmlUtils.getString(xml, "sign")); param.put("return_code", returnCode);// param.put("err_code", XmlUtils.getString(xml, "err_code")); //? param.put("err_code_des", XmlUtils.getString(xml, "err_code_des"));//??? } else { param.put("device_info", XmlUtils.getString(xml, "device_info"));//? param.put("openid", XmlUtils.getString(xml, "openid"));// param.put("is_subscribe", XmlUtils.getString(xml, "is_subscribe"));//?? param.put("trade_type", XmlUtils.getString(xml, "trade_type"));// param.put("trade_state", XmlUtils.getString(xml, "trade_state"));//? param.put("bank_type", XmlUtils.getString(xml, "bank_type"));// param.put("total_fee", XmlUtils.getString(xml, "total_fee"));//? param.put("fee_type", XmlUtils.getString(xml, "fee_type"));//?? param.put("cash_fee", XmlUtils.getString(xml, "cash_fee"));//? param.put("cash_fee_type", XmlUtils.getString(xml, "cash_fee_type"));//? param.put("transaction_id", XmlUtils.getString(xml, "transaction_id"));//?? param.put("out_trade_no", XmlUtils.getString(xml, "out_trade_no"));//?? param.put("attach", XmlUtils.getString(xml, "attach"));//? param.put("time_end", XmlUtils.getString(xml, "time_end"));//? param.put("trade_state_desc", XmlUtils.getString(xml, "trade_state_desc"));//??? } } } param.put("err_code", XmlUtils.getString(xml, "err_code")); param.put("err_code_des", XmlUtils.getString(xml, "err_code_des")); return param; } /** * ??? * @param xml * @return Map */ public static Map<String, Object> buildXmlPayNotify(String xml) { LOG.debug("buildXmlPayNotify xml" + xml); if (xml == null) { return null; } Map<String, Object> param = new HashMap<String, Object>(); String returnCode = XmlUtils.getString(xml, "return_code"); if (returnCode != null) { if (returnCode.equalsIgnoreCase("FAIL")) { param.put("return_code", returnCode); param.put("return_msg", XmlUtils.getString(xml, "return_msg")); } else if (returnCode.equalsIgnoreCase("SUCCESS")) { String resultCode = XmlUtils.getString(xml, "result_code"); if (resultCode != null && resultCode.equalsIgnoreCase("FAIL")) { param.put("result_code", resultCode); param.put("appid", XmlUtils.getString(xml, "appid")); param.put("mch_id", XmlUtils.getString(xml, "mch_id")); param.put("device_info", XmlUtils.getString(xml, "device_info")); param.put("nonce_str", XmlUtils.getString(xml, "nonce_str")); param.put("sign", XmlUtils.getString(xml, "sign")); param.put("result_code", XmlUtils.getString(xml, "result_code")); param.put("err_code", XmlUtils.getString(xml, "err_code")); param.put("err_code_des", XmlUtils.getString(xml, "err_code_des")); } else { param.put("result_code", resultCode); param.put("return_msg", XmlUtils.getString(xml, "return_msg")); param.put("openid", XmlUtils.getString(xml, "openid")); param.put("is_subscribe", XmlUtils.getString(xml, "is_subscribe")); //??Y-N-? param.put("trade_type", XmlUtils.getString(xml, "trade_type"));//JSAPI?NATIVE?MICROPAY? APP param.put("bank_type", XmlUtils.getString(xml, "bank_type")); param.put("total_fee", XmlUtils.getString(xml, "total_fee")); param.put("fee_type", XmlUtils.getString(xml, "fee_type")); param.put("transaction_id", XmlUtils.getString(xml, "transaction_id")); param.put("out_trade_no", XmlUtils.getString(xml, "out_trade_no")); param.put("attach", XmlUtils.getString(xml, "attach")); param.put("time_end", XmlUtils.getString(xml, "time_end")); param.put("return_code", XmlUtils.getString(xml, "return_code")); param.put("return_msg", XmlUtils.getString(xml, "return_msg")); //?? ??\?? } } } return param; } /** * ? * @param toUser ? * @param fromUser ?? * @return */ public static String buildDuoKeFu(String toUser, String fromUser) { StringBuffer sb = new StringBuffer(); sb.append("<xml>"); sb.append("<ToUserName><![CDATA[").append(toUser).append("]]></ToUserName>"); sb.append("<FromUserName><![CDATA[").append(fromUser).append("]]></FromUserName>"); sb.append("<CreateTime><![CDATA[").append(new Date().getTime()).append("]]></CreateTime>"); sb.append("<MsgType><![CDATA[").append(XmlUtils.DUO_KE_FU).append("]]></MsgType>"); sb.append("</xml>"); return sb.toString(); } /** * ?xml??document? * * @param str * * @return ??Documentnull */ public static Document stringToXml(String str) { try { return DocumentHelper.parseText(str); } catch (DocumentException e) { e.printStackTrace(); } return null; } /** * ?xml??document??key? * * @param str * * @param key * ?? * @return ??stringnull */ public static String getString(String str, String key) { try { Document document = DocumentHelper.parseText(str); Element root = document.getRootElement(); return root.elementTextTrim(key); } catch (Exception e) { e.printStackTrace(); LOG.debug("Exception?xml:" + str); LOG.debug("Exception?key:" + key); } return null; } /** * ?xml??document??key?</br> xml?</br> * * @param str * * @param key * ?? * @param sonKey ??? * @return ??stringnull */ public static String getString(String str, String key, String sonKey) { try { Document document = DocumentHelper.parseText(str); Element root = document.getRootElement(); for (Iterator<?> i = root.elementIterator(key); i.hasNext();) { Element foo = (Element) i.next(); return foo.elementText(sonKey); } } catch (Exception e) { e.printStackTrace(); LOG.debug("Exception?xml:" + str); LOG.debug("Exception?key:" + key); } return null; } /** * ???</br> * ?????</br> * ??string?KEY</br> * ??MD5</br> * ??</br> * @param param ????</br> * key:(???)|value:</br> * @param Key Key * @return ??? */ public static String getPaySign(Map<String, String> params, String key) { //????? Map<String, String> temp = StringUtil.sortMapByKey(params); //??string?KEY String sign = StringUtil.buildUrl("", temp).replace("?", "") + "&key=" + key; LOG.debug("=====getPaySign:" + sign); //??MD5 sign = MD5Util.MD5Encode(sign, "utf-8"); //?? sign = sign.toUpperCase(); return sign; } }