Java tutorial
/* * Copyright 2012-2014 sammyun.com.cn. All rights reserved. * Support: http://www.sammyun.com.cn * License: http://www.sammyun.com.cn/license */ package com.sammyun.plugin; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.CompareToBuilder; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import com.sammyun.Setting; import com.sammyun.entity.Payment; import com.sammyun.entity.PluginConfig; import com.sammyun.service.PaymentService; import com.sammyun.service.PluginConfigService; import com.sammyun.util.RSAUtils; import com.sammyun.util.SettingUtils; /** * Plugin - * * @author Sencloud Team * @version 3.0 */ public abstract class PaymentPlugin implements Comparable<PaymentPlugin> { /** ????? */ public static final String PAYMENT_NAME_ATTRIBUTE_NAME = "paymentName"; /** ?? */ public static final String FEE_TYPE_ATTRIBUTE_NAME = "feeType"; /** ?? */ public static final String FEE_ATTRIBUTE_NAME = "fee"; /** LOGO?? */ public static final String LOGO_ATTRIBUTE_NAME = "logo"; /** ???? */ public static final String DESCRIPTION_ATTRIBUTE_NAME = "description"; /** * */ public enum FeeType { /** */ scale, /** */ fixed } /** * */ public enum RequestMethod { /** POST */ post, /** GET */ get } /** * */ public enum NotifyMethod { /** */ general, /** ? */ sync, /** */ async } @Resource(name = "pluginConfigServiceImpl") private PluginConfigService pluginConfigService; @Resource(name = "paymentServiceImpl") private PaymentService paymentService; /** * ?ID * * @return ID */ public final String getId() { return getClass().getAnnotation(Component.class).value(); } /** * ??? * * @return ?? */ public abstract String getName(); /** * ? * * @return */ public abstract String getVersion(); /** * ? * * @return */ public abstract String getAuthor(); /** * ?? * * @return ? */ public abstract String getSiteUrl(); /** * ?URL * * @return URL */ public abstract String getInstallUrl(); /** * ?unURL * * @return unURL */ public abstract String getUninstallUrl(); /** * ?URL * * @return URL */ public abstract String getSettingUrl(); /** * ?? * * @return ? */ public boolean getIsInstalled() { return pluginConfigService.pluginIdExists(getId()); } /** * ??? * * @return ?? */ public PluginConfig getPluginConfig() { return pluginConfigService.findByPluginId(getId()); } /** * ??? * * @return ?? */ public boolean getIsEnabled() { PluginConfig pluginConfig = getPluginConfig(); return pluginConfig != null ? pluginConfig.getIsEnabled() : false; } /** * ? * * @param name ?? * @return */ public String getAttribute(String name) { PluginConfig pluginConfig = getPluginConfig(); return pluginConfig != null ? pluginConfig.getAttribute(name) : null; } /** * ?? * * @return ? */ public Integer getOrder() { PluginConfig pluginConfig = getPluginConfig(); return pluginConfig != null ? pluginConfig.getOrder() : null; } /** * ???? * * @return ??? */ public String getPaymentName() { PluginConfig pluginConfig = getPluginConfig(); return pluginConfig != null ? pluginConfig.getAttribute(PAYMENT_NAME_ATTRIBUTE_NAME) : null; } /** * ? * * @return */ public FeeType getFeeType() { PluginConfig pluginConfig = getPluginConfig(); return pluginConfig != null ? FeeType.valueOf(pluginConfig.getAttribute(FEE_TYPE_ATTRIBUTE_NAME)) : null; } /** * ? * * @return */ public BigDecimal getFee() { PluginConfig pluginConfig = getPluginConfig(); return pluginConfig != null ? new BigDecimal(pluginConfig.getAttribute(FEE_ATTRIBUTE_NAME)) : null; } /** * ?LOGO * * @return LOGO */ public String getLogo() { PluginConfig pluginConfig = getPluginConfig(); return pluginConfig != null ? pluginConfig.getAttribute(LOGO_ATTRIBUTE_NAME) : null; } /** * ??? * * @return ?? */ public String getDescription() { PluginConfig pluginConfig = getPluginConfig(); return pluginConfig != null ? pluginConfig.getAttribute(DESCRIPTION_ATTRIBUTE_NAME) : null; } /** * ?URL * * @return URL */ public abstract String getRequestUrl(); /** * ? * * @return */ public abstract RequestMethod getRequestMethod(); /** * ?? * * @return ? */ public abstract String getRequestCharset(); /** * ?? * * @param sn ? * @param description ?? * @param request httpServletRequest * @return ? * @throws Exception */ public abstract Map<String, Object> getParameterMap(String sn, String description, HttpServletRequest request); /** * ??? * * @param sn ? * @param notifyMethod * @param request httpServletRequest * @return ?? */ public abstract boolean verifyNotify(String sn, NotifyMethod notifyMethod, HttpServletRequest request); /** * ??? * * @param sn ? * @param notifyMethod * @param request httpServletRequest * @return ?? */ public abstract boolean verifyMobileNotify(String sn, NotifyMethod notifyMethod, HttpServletRequest request); /** * ?? * * @param sn ? * @param notifyMethod * @param request httpServletRequest * @return ? */ public abstract String getNotifyMessage(String sn, NotifyMethod notifyMethod, HttpServletRequest request); /** * ? * * @return */ public abstract Integer getTimeout(); /** * * * @param amount ? * @return */ public BigDecimal calculateFee(BigDecimal amount) { Setting setting = SettingUtils.get(); BigDecimal fee; if (getFeeType() == FeeType.scale) { fee = amount.multiply(getFee()); } else { fee = getFee(); } //return setting.setScale(fee); return fee; } /** * ? * * @param amount ? * @return ? */ public BigDecimal calculateAmount(BigDecimal amount) { return amount.add(calculateFee(amount)).setScale(2, RoundingMode.UP); } /** * ??? * * @param sn ?(?) * @return ??null */ protected Payment getPayment(String sn) { return paymentService.findBySn(sn); } /** * ?URL * * @param sn ? * @param notifyMethod * @return URL */ protected String getNotifyUrl(String sn, NotifyMethod notifyMethod) { Setting setting = SettingUtils.get(); if (notifyMethod == null) { return setting.getSiteUrl() + "/payment/notify/" + NotifyMethod.general + "/" + sn + ".ct"; } return setting.getSiteUrl() + "/payment/notify/" + notifyMethod + "/" + sn + ".ct"; } /** * ?URL * * @param sn ? * @param notifyMethod * @return URL */ protected String getMobileNotifyUrl(String sn, NotifyMethod notifyMethod) { Setting setting = SettingUtils.get(); if (notifyMethod == null) { return setting.getSiteUrl() + "/payment/mobileNotify/" + NotifyMethod.general + "/" + sn + ".ct"; } return setting.getSiteUrl() + "/payment/mobileNotify/" + notifyMethod + "/" + sn + ".ct"; } /** * Map * * @param map Map * @param prefix ? * @param suffix ? * @param separator * @param ignoreEmptyValue * @param ignoreKeys Key * @return */ protected String joinKeyValue(Map<String, Object> map, String prefix, String suffix, String separator, boolean ignoreEmptyValue, String... ignoreKeys) { List<String> list = new ArrayList<String>(); if (map != null) { for (Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); String value = ConvertUtils.convert(entry.getValue()); if (StringUtils.isNotEmpty(key) && !ArrayUtils.contains(ignoreKeys, key) && (!ignoreEmptyValue || StringUtils.isNotEmpty(value))) { list.add(key + "=" + (value != null ? value : "")); } } } return (prefix != null ? prefix : "") + StringUtils.join(list, separator) + (suffix != null ? suffix : ""); } /** * Map * * @param map Map * @param prefix ? * @param suffix ? * @param separator * @param ignoreEmptyValue * @param ignoreKeys Key * @return */ protected String joinValue(Map<String, Object> map, String prefix, String suffix, String separator, boolean ignoreEmptyValue, String... ignoreKeys) { List<String> list = new ArrayList<String>(); if (map != null) { for (Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); String value = ConvertUtils.convert(entry.getValue()); if (StringUtils.isNotEmpty(key) && !ArrayUtils.contains(ignoreKeys, key) && (!ignoreEmptyValue || StringUtils.isNotEmpty(value))) { list.add(value != null ? value : ""); } } } return (prefix != null ? prefix : "") + StringUtils.join(list, separator) + (suffix != null ? suffix : ""); } /** * ??? * * @param sArray ??? * @return ??????? */ public static Map<String, Object> paraFilter(Map<String, Object> sArray) { Map<String, Object> result = new HashMap<String, Object>(); if (sArray == null || sArray.size() <= 0) { return result; } for (String key : sArray.keySet()) { Object value = sArray.get(key); if (value == null || value.equals("") || key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("sign_type")) { continue; } result.put(key, value); } return result; } /** * ??=???&?? * * @param params ???? * @return ? */ public static String createLinkString(Map<String, Object> params) { List<String> keys = new ArrayList<String>(params.keySet()); Collections.sort(keys); String prestr = ""; for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); Object value = params.get(key); if (i == keys.size() - 1) {// ??& prestr = prestr + key + "=" + value; } else { prestr = prestr + key + "=" + value.toString() + "&"; } } return prestr; } /** * ???=???&?? * * @param params ??? * @return ? */ public static String createLinkStringNoSort(Map<String, Object> params) { // MD5?????? StringBuilder gotoSign_params = new StringBuilder(); gotoSign_params.append("service=" + params.get("service").toString()); gotoSign_params.append("&v=" + params.get("v").toString()); gotoSign_params.append("&sec_id=" + params.get("sec_id").toString()); gotoSign_params.append("¬ify_data=" + params.get("notify_data").toString()); return gotoSign_params.toString(); } /** * POST * * @param url URL * @param parameterMap ? * @return */ protected String post(String url, Map<String, Object> parameterMap) { Assert.hasText(url); String result = null; HttpClient httpClient = new DefaultHttpClient(); try { HttpPost httpPost = new HttpPost(url); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (parameterMap != null) { for (Entry<String, Object> entry : parameterMap.entrySet()) { String name = entry.getKey(); String value = ConvertUtils.convert(entry.getValue()); if (StringUtils.isNotEmpty(name)) { nameValuePairs.add(new BasicNameValuePair(name, value)); } } } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); EntityUtils.consume(httpEntity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } return result; } /** * GET * * @param url URL * @param parameterMap ? * @return */ protected String get(String url, Map<String, Object> parameterMap) { Assert.hasText(url); String result = null; HttpClient httpClient = new DefaultHttpClient(); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (parameterMap != null) { for (Entry<String, Object> entry : parameterMap.entrySet()) { String name = entry.getKey(); String value = ConvertUtils.convert(entry.getValue()); if (StringUtils.isNotEmpty(name)) { nameValuePairs.add(new BasicNameValuePair(name, value)); } } } HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?") + EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"))); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); EntityUtils.consume(httpEntity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } return result; } /** * ?????token ?RSA * * @param text ?? * @return ? * @throws Exception */ public static String getRequestToken(String text) throws Exception { String request_token = ""; // &? String[] strSplitText = text.split("&"); // ?????? Map<String, String> paraText = new HashMap<String, String>(); for (int i = 0; i < strSplitText.length; i++) { // =? int nPos = strSplitText[i].indexOf("="); // int nLen = strSplitText[i].length(); // ???? String strKey = strSplitText[i].substring(0, nPos); // String strValue = strSplitText[i].substring(nPos + 1, nLen); // MAP paraText.put(strKey, strValue); } if (paraText.get("res_data") != null) { String res_data = paraText.get("res_data"); // ?RSAMD5? if (PluginConfig.SIGN_TYPE.equals("0001")) { res_data = RSAUtils.decrypt(res_data, PluginConfig.ALI_PRIVATE_KEY, PluginConfig.INPUT_CHARSET); } // tokenres_data??res_data??token Document document = DocumentHelper.parseText(res_data); request_token = document.selectSingleNode("//direct_trade_create_res/request_token").getText(); } return request_token; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } if (this == obj) { return true; } PaymentPlugin other = (PaymentPlugin) obj; return new EqualsBuilder().append(getId(), other.getId()).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37).append(getId()).toHashCode(); } public int compareTo(PaymentPlugin paymentPlugin) { return new CompareToBuilder().append(getOrder(), paymentPlugin.getOrder()) .append(getId(), paymentPlugin.getId()).toComparison(); } }