6 changed files with 754 additions and 1 deletions
Binary file not shown.
@ -1,3 +1,6 @@
|
||||
# open-JSD-8153 |
||||
|
||||
JSD-8153开源任务材料 |
||||
JSD-8153开源任务材料\ |
||||
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ |
||||
仅作为开发者学习参考使用!禁止用于任何商业用途!\ |
||||
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系hugh处理。 |
@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?> |
||||
<plugin> |
||||
<id>com.fr.plugin.hx.mail</id> |
||||
<name><![CDATA[邮件发送]]></name> |
||||
<active>yes</active> |
||||
<version>1.32</version> |
||||
<env-version>10.0~</env-version> |
||||
<jartime>2019-01-15</jartime> |
||||
<vendor>fr.open</vendor> |
||||
<description><![CDATA[邮件发送]]></description> |
||||
<change-notes><![CDATA[ |
||||
[2021-07-12]增加批量发送参数。<br/> |
||||
[2021-07-13]增加batchMail为true才能发送,param可以为空。<br/> |
||||
[2021-07-13]输出请求的json。<br/> |
||||
[2021-07-13]修改isBatchEmail序列化问题。<br/> |
||||
[2021-07-13]修改isBatchEmail序列化问题。传输为String<br/> |
||||
[2021-07-13]修改接口调用方式<br/> |
||||
<!--[2018-07-31]初始化插件。<br/>--> |
||||
]]></change-notes> |
||||
<extra-core> |
||||
<EmailServiceProvider class="com.fr.plugin.hx.mail.EmailProvider"/> |
||||
</extra-core> |
||||
<function-recorder class="com.fr.plugin.hx.mail.EmailProvider"/> |
||||
</plugin> |
@ -0,0 +1,371 @@
|
||||
package com.fr.plugin.hx.mail; |
||||
|
||||
import com.fr.general.PropertiesUtils; |
||||
import com.fr.general.http.HttpRequest; |
||||
import com.fr.general.http.HttpToolbox; |
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.plugin.transform.ExecuteFunctionRecord; |
||||
import com.fr.plugin.transform.FunctionRecorder; |
||||
import com.fr.stable.StringUtils; |
||||
import com.fr.stable.bridge.ObjectHolder; |
||||
import com.fr.stable.email.EmailAttachmentProvider; |
||||
import com.fr.stable.fun.assist.Selector; |
||||
import com.fr.stable.fun.impl.AbstractEmailServiceProvider; |
||||
import com.fr.third.org.apache.http.entity.StringEntity; |
||||
import com.fr.third.springframework.core.io.ByteArrayResource; |
||||
import com.fr.third.springframework.http.HttpEntity; |
||||
import com.fr.third.springframework.http.HttpHeaders; |
||||
import com.fr.third.springframework.http.MediaType; |
||||
import com.fr.third.springframework.http.ResponseEntity; |
||||
import com.fr.third.springframework.http.converter.HttpMessageConverter; |
||||
import com.fr.third.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; |
||||
import com.fr.third.springframework.util.LinkedMultiValueMap; |
||||
import com.fr.third.springframework.util.MultiValueMap; |
||||
import com.fr.third.springframework.web.client.RestTemplate; |
||||
import com.hisense.pangea.message.service.dto.SendMessageDTO; |
||||
import com.hisense.pangea.message.service.dto.SendResultDTO; |
||||
|
||||
import javax.mail.MessagingException; |
||||
import java.io.IOException; |
||||
import java.util.*; |
||||
import java.util.stream.Collectors; |
||||
import java.util.stream.Stream; |
||||
|
||||
/** |
||||
* @author fr.open |
||||
* @version 10.0 |
||||
* Created by Cloud.Liu on 2021/7/21 |
||||
*/ |
||||
@FunctionRecorder |
||||
public class EmailProvider extends AbstractEmailServiceProvider { |
||||
|
||||
private static Map<String, String> TYPE_MAP = new HashMap<>(); |
||||
|
||||
/** |
||||
* 发送邮件 |
||||
* |
||||
* @param toAddress 收件人地址 |
||||
* @param ccAddress 抄送地址 |
||||
* @param bccAddress 密送地址 |
||||
* @param fromAddress 发件人地址 |
||||
* @param subject 主题 |
||||
* @param bodyContent 正文 |
||||
* @param attaches 附件 |
||||
* @param format 格式 |
||||
* @param contentAttaches 邮件正文显示的附件 |
||||
* @throws MessagingException 异常 |
||||
*/ |
||||
@ExecuteFunctionRecord |
||||
@Override |
||||
public void send(String toAddress, String ccAddress, String bccAddress, String fromAddress, String subject, String bodyContent, final EmailAttachmentProvider[] attaches, String format, EmailAttachmentProvider[] contentAttaches) throws MessagingException { |
||||
init(); |
||||
FineLoggerFactory.getLogger().info("email content is {}", bodyContent); |
||||
//解析参数
|
||||
String ids,param = null; |
||||
try { |
||||
ids = bodyContent.substring(bodyContent.indexOf("[") + 1, bodyContent.indexOf("]")); |
||||
if(bodyContent.indexOf("{") != -1){ |
||||
param = bodyContent.substring(bodyContent.indexOf("{"), bodyContent.indexOf("}") + 1); |
||||
} |
||||
}catch (Exception e){ |
||||
FineLoggerFactory.getLogger().error("ids and param resolve failed"); |
||||
FineLoggerFactory.getLogger().error(e.getMessage(),e); |
||||
return; |
||||
} |
||||
FineLoggerFactory.getLogger().info("ids is [{}] param is [{}]",ids,param); |
||||
//解析正文
|
||||
Map map = getParamMap(bodyContent); |
||||
SendMessageDTO messageDTO = new SendMessageDTO(); |
||||
String sysCode = PropertiesUtils.getProperties("conf").getProperty("sysCode"); |
||||
FineLoggerFactory.getLogger().info("get sysCode is {}", sysCode); |
||||
messageDTO.setSysCode(sysCode); |
||||
String[] arr = ids.trim().split(";"); |
||||
List<String> types = new ArrayList<>(); |
||||
for (int i = 0; i < arr.length; i++) { |
||||
String[] info = arr[i].split(":"); |
||||
String type = TYPE_MAP.get(info[0]); |
||||
FineLoggerFactory.getLogger().info("resolve id info is {}", Arrays.toString(info)); |
||||
if (info.length > 1 && type != null && StringUtils.isNotBlank(info[1])) { |
||||
switch (type) { |
||||
case "0": |
||||
ArrayList<String> group = new ArrayList<>(); |
||||
group.add(info[1]); |
||||
FineLoggerFactory.getLogger().info("get group {}", info[1]); |
||||
messageDTO.setGroupCode(group); |
||||
break; |
||||
case "1": |
||||
types.add(TYPE_MAP.get(info[0])); |
||||
messageDTO.setTemplateCodeEmail(info[1]); |
||||
FineLoggerFactory.getLogger().info("get email template code {}", info[1]); |
||||
FineLoggerFactory.getLogger().info("subject is {}", subject); |
||||
messageDTO.setSubject(subject); |
||||
//FineLoggerFactory.getLogger().info("bodyContent is {}",bodyContent.replace("["+ids+"]",""));
|
||||
//messageDTO.setContentEmail(bodyContent.replace("["+ids+"]",""));
|
||||
FineLoggerFactory.getLogger().info("toAddress is {}", toAddress); |
||||
messageDTO.setSendTo(Arrays.asList(toAddress.split(","))); |
||||
if (StringUtils.isNotBlank(ccAddress)) { |
||||
FineLoggerFactory.getLogger().info("ccAddress is {}", ccAddress); |
||||
messageDTO.setSendToCopy(Arrays.asList(ccAddress.split(","))); |
||||
} |
||||
if (StringUtils.isNotBlank(bccAddress)) { |
||||
FineLoggerFactory.getLogger().info("bccAddress is {}", bccAddress); |
||||
messageDTO.setSendToDark(Arrays.asList(bccAddress.split(","))); |
||||
} |
||||
List<String> files = new ArrayList<>(); |
||||
if (attaches != null) { |
||||
for (EmailAttachmentProvider p : attaches) { |
||||
files.add(uploadEmailFile(p.getData(), p.getFileName())); |
||||
} |
||||
} |
||||
if (!files.isEmpty()) { |
||||
FineLoggerFactory.getLogger().info("attaches name is {}", files); |
||||
messageDTO.setFiles(files); |
||||
} |
||||
|
||||
if (StringUtils.isNotBlank(param)) { |
||||
FineLoggerFactory.getLogger().info("get mail Params {}", param); |
||||
Map paramMap = new JSONObject(param).toMap(); |
||||
if (map != null) { |
||||
paramMap.putAll(map); |
||||
} |
||||
messageDTO.setTemplateParamsEmail(paramMap); |
||||
} else { |
||||
messageDTO.setTemplateParamsEmail(map); |
||||
} |
||||
break; |
||||
case "2": |
||||
types.add(TYPE_MAP.get(info[0])); |
||||
messageDTO.setTemplateCodeSms(info[1]); |
||||
FineLoggerFactory.getLogger().info("get sms template code {}", info[1]); |
||||
if (StringUtils.isNotBlank(param)) { |
||||
FineLoggerFactory.getLogger().info("get sms Params {}", param); |
||||
Map paramMap = new JSONObject(param).toMap(); |
||||
if (map != null) { |
||||
paramMap.putAll(map); |
||||
} |
||||
messageDTO.setTemplateParamsSms(paramMap); |
||||
} else { |
||||
messageDTO.setTemplateParamsSms(map); |
||||
} |
||||
break; |
||||
case "3": |
||||
types.add(TYPE_MAP.get(info[0])); |
||||
messageDTO.setTemplateCodeHiChat(info[1]); |
||||
FineLoggerFactory.getLogger().info("get HiChat template code {}", info[1]); |
||||
if (StringUtils.isNotBlank(param)) { |
||||
FineLoggerFactory.getLogger().info("get HiChat Params {}", param); |
||||
Map paramMap = new JSONObject(param).toMap(); |
||||
if (map != null) { |
||||
paramMap.putAll(map); |
||||
} |
||||
messageDTO.setTemplateParamsHiChat(paramMap); |
||||
} else { |
||||
messageDTO.setTemplateParamsHiChat(map); |
||||
} |
||||
messageDTO.setType(2L); |
||||
messageDTO.setModel(1L); |
||||
break; |
||||
case "4": |
||||
if("true".equals(info[1])){ |
||||
messageDTO.setBatchEmail(true); |
||||
} |
||||
break; |
||||
case "-1": |
||||
FineLoggerFactory.getLogger().info("get dynamic user list {}", info[1]); |
||||
messageDTO.setUser(Stream.of(info[1].split(",")).collect(Collectors.toList())); |
||||
break; |
||||
default: |
||||
break; |
||||
} |
||||
} |
||||
} |
||||
|
||||
|
||||
FineLoggerFactory.getLogger().info("type info is {}", StringUtils.join(",", types.toArray(new String[types.size()]))); |
||||
messageDTO.setSendType(StringUtils.join(",", types.toArray(new String[types.size()]))); |
||||
sendCommonMessage(messageDTO); |
||||
|
||||
/*Map<String, String> info = new HashMap<>(); |
||||
info.put("toAddress", toAddress); |
||||
info.put("ccAddress", ccAddress); |
||||
info.put("bccAddress", bccAddress); |
||||
info.put("fromAddress", fromAddress); |
||||
info.put("subject", subject); |
||||
info.put("bodyContent", bodyContent); |
||||
info.put("format", format); |
||||
if (ArrayUtils.isNotEmpty(attaches)) { |
||||
info.put("attaches", Arrays.stream(attaches).map(EmailAttachmentProvider::getFileName).collect(Collectors.toList()).toString()); |
||||
} |
||||
if (ArrayUtils.isNotEmpty(contentAttaches)) { |
||||
info.put("contentAttaches", Arrays.stream(contentAttaches).map(EmailAttachmentProvider::getFileName).collect(Collectors.toList()).toString()); |
||||
}*/ |
||||
|
||||
/*try { |
||||
FineLoggerFactory.getLogger().error("使用插件发送邮件:" + new ObjectMapper().writeValueAsString(info)); |
||||
FineLoggerFactory.getLogger().error("堆栈信息", new Exception()); |
||||
} catch (JsonProcessingException e) { |
||||
e.printStackTrace(); |
||||
}*/ |
||||
} |
||||
|
||||
/** |
||||
* 获取内置参数 |
||||
* |
||||
* @param bodyContent |
||||
* @return |
||||
*/ |
||||
private Map getParamMap(String bodyContent) { |
||||
Map map = new HashMap(); |
||||
String firstStr = StringUtils.EMPTY; |
||||
String secondStr = StringUtils.EMPTY; |
||||
map.put("reportUrl", firstStr); |
||||
map.put("body", secondStr); |
||||
if (bodyContent.indexOf("<br />") != -1) { |
||||
//有第一个参数
|
||||
int first = bodyContent.indexOf("<br />"); |
||||
int second = bodyContent.indexOf("<br />", first + 6); |
||||
if (second == -1) { |
||||
firstStr = bodyContent.substring(first + 6).trim(); |
||||
FineLoggerFactory.getLogger().info("first tag is {}", firstStr); |
||||
FineLoggerFactory.getLogger().info("secondStr tag is null"); |
||||
} else { |
||||
firstStr = bodyContent.substring(first + 6, second).trim(); |
||||
FineLoggerFactory.getLogger().info("firstStr tag is {}", firstStr); |
||||
secondStr = bodyContent.substring(second + 6).trim(); |
||||
FineLoggerFactory.getLogger().info("secondStr tag is {}", secondStr); |
||||
} |
||||
} |
||||
if (StringUtils.isNotBlank(firstStr)) { |
||||
if (firstStr.indexOf("定时任务结果链接") != -1) { |
||||
map.put("reportUrl", firstStr); |
||||
FineLoggerFactory.getLogger().info("reportUrl is {}", firstStr); |
||||
} else { |
||||
map.put("body", firstStr); |
||||
FineLoggerFactory.getLogger().info("nody is {}", firstStr); |
||||
} |
||||
} |
||||
if (StringUtils.isNotBlank(secondStr)) { |
||||
map.put("body", secondStr); |
||||
FineLoggerFactory.getLogger().info("nody is {}", firstStr); |
||||
} |
||||
String urlName = PropertiesUtils.getProperties("conf").getProperty("urlName"); |
||||
FineLoggerFactory.getLogger().info("get url name is {}",urlName); |
||||
if(StringUtils.isNotBlank(urlName)){ |
||||
map.put("reportUrl", map.get("reportUrl").toString().replace("定时任务结果链接",urlName)); |
||||
} |
||||
return map; |
||||
} |
||||
|
||||
private void init() { |
||||
if (TYPE_MAP.isEmpty()) { |
||||
TYPE_MAP.put("id1", "1"); |
||||
TYPE_MAP.put("id2", "2"); |
||||
TYPE_MAP.put("id3", "3"); |
||||
TYPE_MAP.put("dynamic", "-1"); |
||||
TYPE_MAP.put("groupCode", "0"); |
||||
TYPE_MAP.put("batchEmail", "4"); |
||||
} |
||||
} |
||||
|
||||
public String uploadEmailFile(byte[] file, String fileName) { |
||||
if (file == null) { |
||||
return null; |
||||
} else { |
||||
String url = PropertiesUtils.getProperties("conf").getProperty("upload"); |
||||
FineLoggerFactory.getLogger().info("upload url is {}", url); |
||||
RestTemplate restTemplate = new RestTemplate(); |
||||
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters(); |
||||
HttpMessageConverter<?> converterTarget = null; |
||||
for (HttpMessageConverter<?> item : converterList) { |
||||
if (AllEncompassingFormHttpMessageConverter.class == item.getClass()) { |
||||
converterTarget = item; |
||||
break; |
||||
} |
||||
} |
||||
if (null != converterTarget) { |
||||
converterList.remove(converterTarget); |
||||
} |
||||
converterList.add(1, new UTF8FormHttpMessageConverter()); |
||||
HttpHeaders headers = new HttpHeaders(); |
||||
//MediaType type = MediaType.parseMediaType("multipart/form-data");
|
||||
headers.setContentType(MediaType.MULTIPART_FORM_DATA); |
||||
ByteArrayResource contentsAsResource = new ByteArrayResource(file) { |
||||
@Override |
||||
public String getFilename() { |
||||
return fileName; |
||||
} |
||||
}; |
||||
//InputStreamResource fileSystemResource = new InputStreamResource(file);
|
||||
MultiValueMap<String, Object> form = new LinkedMultiValueMap(); |
||||
form.add("file", contentsAsResource); |
||||
HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity(form, headers); |
||||
ResponseEntity<Map> responseEntity = restTemplate.postForEntity(url, files, Map.class, new Object[0]); |
||||
FineLoggerFactory.getLogger().info("upload file result is {}", responseEntity); |
||||
Map<String, Object> body = (Map) responseEntity.getBody(); |
||||
Map<String, Object> data = (Map) body.get("data"); |
||||
return (String) data.get("fileName"); |
||||
} |
||||
} |
||||
|
||||
public SendResultDTO sendCommonMessage(SendMessageDTO sendMessageDTO) { |
||||
String url = PropertiesUtils.getProperties("conf").getProperty("common"); |
||||
FineLoggerFactory.getLogger().info("SEND_COMMON_MESSAGE's url is: {}", url); |
||||
FineLoggerFactory.getLogger().info("SEND_COMMON_MESSAGE's params is: {}", sendMessageDTO); |
||||
JSONObject object = JSONObject.mapFrom(sendMessageDTO); |
||||
object.put("isBatchEmail",sendMessageDTO.isBatchEmail()); |
||||
FineLoggerFactory.getLogger().info("SEND_COMMON_MESSAGE's json params is: {}", object); |
||||
RestTemplate restTemplate = new RestTemplate(); |
||||
/*Map<String, Object> result = restTemplate.postForObject(url, object.toString(), Map.class, new Object[0]);*/ |
||||
StringEntity s = new StringEntity(object.toString(), "UTF-8"); |
||||
s.setContentEncoding("UTF-8"); |
||||
s.setContentType("application/json; charset=UTF-8");//发送json数据需要设置contentType
|
||||
String result = null; |
||||
try { |
||||
result = HttpToolbox.executeAndParse(HttpRequest.custom().url(url) |
||||
.post(s) |
||||
.build()); |
||||
} catch (IOException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(),e); |
||||
} |
||||
FineLoggerFactory.getLogger().info("SEND_COMMON_MESSAGE's result is: {}", result); |
||||
return null; |
||||
} |
||||
|
||||
@Override |
||||
public Selector selector() { |
||||
return new Selector() { |
||||
@Override |
||||
public boolean accept(ObjectHolder objectHolder) { |
||||
for (String address : objectHolder.get(String.class).split(",")) { |
||||
if (address.endsWith("@163.com")) { |
||||
FineLoggerFactory.getLogger().error("收件人中有163邮箱,本插件不发送"); |
||||
return false; |
||||
} |
||||
} |
||||
FineLoggerFactory.getLogger().error("收件人中不含163邮箱,经由本插件发送"); |
||||
return true; |
||||
} |
||||
}; |
||||
} |
||||
|
||||
/*public static void main(String[] args) { |
||||
new EmailProvider().getParamMap("[id1:04247d85-5cc5-4b7f-a556-b94c5aaada77;groupCode:7459961;batchEmail:true]\n" + |
||||
"{param1:\"2020-10-15\";param2:\"板卡灯条车间\";param3:\"L201A线\";param4:\"0\";param5:\"0.647073814235174\";param6:\"<a href=http://10.19.32.151:8080/webroot/decision/view/report?viewlet=test%252Fdth%25E7%25BA%25BF%25E4%25BD%2593%25E5%258D%2595%25E5%25B0%258F%25E6%2597%25B6-%25E6%2599%25BA%25E5%258A%25A8%25E7%25B2%25BE%25E5%25B7%25A5-%25E5%25AD%2599%25E6%2598%2580.cpt&ref_t=design&ref_c=681a0a18-557b-4201-a45b-a7788b9a328b>报表链接</a>\";}<br /> <a href=http://finebi.hisense.com:8080/webroot/decision/schedule/result?taskName=%E5%AD%99%E6%98%80DTH&taskType=1&username=&showType=PAGE>定时任务结果链接</a><br /><style type=\"text/css\" id=\"_fr_content_style\">.fh { overflow: hidden; padding: 0; vertical-align: middle; text-align: left; font-size: 9pt; font-family: SimSun }.b0 { border: 0 }.b1 { border: 1px solid rgb(0, 0, 0) }.page-block { float: left }.fwb { font-weight: bold }.bw { word-wrap: break-word }.tac { text-align: center }.pl2 { padding-left: 2px; *padding-left: 0 }.f10-0 { font-size: 10pt }.x-table { overflow: hidden; table-layout: fixed; border-collapse: collapse; *word-break: break-all; *overflow: visible }table.x-table{overflow:visible;line-height:1;}td{line-height:1 !important;}</style><div class=\"pageContentDIV contentMailDIV\" style=\"position:relative;height:760px;\"><div class=\"paper-background\" style=\"background-"); |
||||
String mess = "{\"secretKey\":null,\"sysCode\":\"S0318\",\"msgName\":null,\"frequency\":null,\"num\":null,\"time\":null,\"content\":null,\"subject\":\"A报表\",\"sendType\":\"1\",\"sendTo\":[\"test@test.com\"],\"groupCode\":[\"6959\"],\"user\":null,\"userMap\":null,\"templateCode\":null,\"templateParams\":null,\"emailAccount\":null,\"password\":null,\"userName\":null,\"files\":[\"邮件测试_20210713172955167_57.pdf\"],\"templateCodeEmail\":\"12032ec6-38e7-48b5-a260-0ec305e0ce4d\",\"templateParamsEmail\":{\"reportUrl\":\"<a href=https://10.19.51.242/webroot/decision/schedule/result?taskName=DTH%E9%82%AE%E4%BB%B6%E6%B5%8B%E8%AF%95&taskType=1&username=&showType=PAGE>报表链接</a>\",\"body\":\"\"},\"contentEmail\":null,\"sendToCopy\":null,\"sendToDark\":null,\"groupCodeCopy\":null,\"groupCodeDark\":null,\"smsMessages\":null,\"sendSource\":null,\"templateCodeSms\":null,\"templateParamsSms\":null,\"contentSms\":null,\"type\":null,\"model\":null,\"templateCodeHiChat\":null,\"templateParamsHiChat\":null,\"msgList\":null,\"batchEmail\":true,\"isBatchEmail\":true}"; |
||||
|
||||
StringEntity s = new StringEntity(mess.toString(), "UTF-8"); |
||||
s.setContentEncoding("UTF-8"); |
||||
s.setContentType("application/json; charset=UTF-8");//发送json数据需要设置contentType
|
||||
String result = null; |
||||
try { |
||||
result = HttpToolbox.executeAndParse(HttpRequest.custom().url("https://open-gw.hisense.com:443/message/api/messageInfos/sendCommonMessage?app_id=244b4f0d&app_key=0ef69febea31c6705f0db7b6e7c00e46") |
||||
.post(s) |
||||
.build()); |
||||
} catch (IOException e) { |
||||
FineLoggerFactory.getLogger().error(e.getMessage(),e); |
||||
} |
||||
FineLoggerFactory.getLogger().info("SEND_COMMON_MESSAGE's result is: ", result); |
||||
} |
||||
*/ |
||||
} |
@ -0,0 +1,347 @@
|
||||
package com.fr.plugin.hx.mail; |
||||
|
||||
import com.fr.third.springframework.core.io.Resource; |
||||
import com.fr.third.springframework.http.*; |
||||
import com.fr.third.springframework.http.converter.*; |
||||
import com.fr.third.springframework.util.*; |
||||
|
||||
import java.io.IOException; |
||||
import java.io.OutputStream; |
||||
import java.io.UnsupportedEncodingException; |
||||
import java.net.URLDecoder; |
||||
import java.net.URLEncoder; |
||||
import java.nio.charset.Charset; |
||||
import java.util.*; |
||||
|
||||
/** |
||||
* @Author fr.open |
||||
* @Date 2020/10/29 |
||||
* @Description |
||||
**/ |
||||
public class UTF8FormHttpMessageConverter extends FormHttpMessageConverter { |
||||
private static final byte[] BOUNDARY_CHARS = new byte[]{45, 95, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90}; |
||||
private Charset charset = Charset.forName("UTF-8"); |
||||
private List<MediaType> supportedMediaTypes = new ArrayList(); |
||||
private List<HttpMessageConverter<?>> partConverters = new ArrayList(); |
||||
private final Random random = new Random(); |
||||
|
||||
public UTF8FormHttpMessageConverter() { |
||||
this.supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED); |
||||
this.supportedMediaTypes.add(MediaType.MULTIPART_FORM_DATA); |
||||
this.partConverters.add(new ByteArrayHttpMessageConverter()); |
||||
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); |
||||
stringHttpMessageConverter.setWriteAcceptCharset(false); |
||||
this.partConverters.add(stringHttpMessageConverter); |
||||
this.partConverters.add(new ResourceHttpMessageConverter()); |
||||
} |
||||
|
||||
@Override |
||||
public void setCharset(Charset charset) { |
||||
this.charset = charset; |
||||
} |
||||
@Override |
||||
public void setSupportedMediaTypes(List<MediaType> supportedMediaTypes) { |
||||
this.supportedMediaTypes = supportedMediaTypes; |
||||
} |
||||
@Override |
||||
public List<MediaType> getSupportedMediaTypes() { |
||||
return Collections.unmodifiableList(this.supportedMediaTypes); |
||||
} |
||||
@Override |
||||
public void setPartConverters(List<HttpMessageConverter<?>> partConverters) { |
||||
Assert.notEmpty(partConverters, "'partConverters' must not be empty"); |
||||
this.partConverters = partConverters; |
||||
} |
||||
@Override |
||||
public void addPartConverter(HttpMessageConverter<?> partConverter) { |
||||
Assert.notNull(partConverter, "'partConverter' must not be null"); |
||||
this.partConverters.add(partConverter); |
||||
} |
||||
@Override |
||||
public boolean canRead(Class<?> clazz, MediaType mediaType) { |
||||
if (!MultiValueMap.class.isAssignableFrom(clazz)) { |
||||
return false; |
||||
} else if (mediaType == null) { |
||||
return true; |
||||
} else { |
||||
Iterator var3 = this.getSupportedMediaTypes().iterator(); |
||||
|
||||
MediaType supportedMediaType; |
||||
do { |
||||
if (!var3.hasNext()) { |
||||
return false; |
||||
} |
||||
|
||||
supportedMediaType = (MediaType)var3.next(); |
||||
} while(supportedMediaType.equals(MediaType.MULTIPART_FORM_DATA) || !supportedMediaType.includes(mediaType)); |
||||
|
||||
return true; |
||||
} |
||||
} |
||||
@Override |
||||
public boolean canWrite(Class<?> clazz, MediaType mediaType) { |
||||
if (!MultiValueMap.class.isAssignableFrom(clazz)) { |
||||
return false; |
||||
} else if (mediaType != null && !MediaType.ALL.equals(mediaType)) { |
||||
Iterator var3 = this.getSupportedMediaTypes().iterator(); |
||||
|
||||
MediaType supportedMediaType; |
||||
do { |
||||
if (!var3.hasNext()) { |
||||
return false; |
||||
} |
||||
|
||||
supportedMediaType = (MediaType)var3.next(); |
||||
} while(!supportedMediaType.isCompatibleWith(mediaType)); |
||||
|
||||
return true; |
||||
} else { |
||||
return true; |
||||
} |
||||
} |
||||
@Override |
||||
public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { |
||||
MediaType contentType = inputMessage.getHeaders().getContentType(); |
||||
Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : this.charset; |
||||
String body = StreamUtils.copyToString(inputMessage.getBody(), charset); |
||||
String[] pairs = StringUtils.tokenizeToStringArray(body, "&"); |
||||
MultiValueMap<String, String> result = new LinkedMultiValueMap(pairs.length); |
||||
String[] var8 = pairs; |
||||
int var9 = pairs.length; |
||||
|
||||
for(int var10 = 0; var10 < var9; ++var10) { |
||||
String pair = var8[var10]; |
||||
int idx = pair.indexOf(61); |
||||
if (idx == -1) { |
||||
result.add(URLDecoder.decode(pair, charset.name()), null); |
||||
} else { |
||||
String name = URLDecoder.decode(pair.substring(0, idx), charset.name()); |
||||
String value = URLDecoder.decode(pair.substring(idx + 1), charset.name()); |
||||
result.add(name, value); |
||||
} |
||||
} |
||||
|
||||
return result; |
||||
} |
||||
@Override |
||||
public void write(MultiValueMap<String, ?> map, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { |
||||
if (!this.isMultipart(map, contentType)) { |
||||
this.writeForm(map, contentType, outputMessage); |
||||
} else { |
||||
this.writeMultipart(map, outputMessage); |
||||
} |
||||
|
||||
} |
||||
|
||||
private boolean isMultipart(MultiValueMap<String, ?> map, MediaType contentType) { |
||||
if (contentType != null) { |
||||
return MediaType.MULTIPART_FORM_DATA.equals(contentType); |
||||
} else { |
||||
Iterator var3 = map.keySet().iterator(); |
||||
|
||||
while(var3.hasNext()) { |
||||
String name = (String)var3.next(); |
||||
Iterator var5 = ((List)map.get(name)).iterator(); |
||||
|
||||
while(var5.hasNext()) { |
||||
Object value = var5.next(); |
||||
if (value != null && !(value instanceof String)) { |
||||
return true; |
||||
} |
||||
} |
||||
} |
||||
|
||||
return false; |
||||
} |
||||
} |
||||
|
||||
private void writeForm(MultiValueMap<String, ?> form, MediaType contentType, HttpOutputMessage outputMessage) throws IOException { |
||||
Charset charset; |
||||
if (contentType != null) { |
||||
outputMessage.getHeaders().setContentType(contentType); |
||||
charset = contentType.getCharSet() != null ? contentType.getCharSet() : this.charset; |
||||
} else { |
||||
outputMessage.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED); |
||||
charset = this.charset; |
||||
} |
||||
|
||||
StringBuilder builder = new StringBuilder(); |
||||
Iterator nameIterator = form.keySet().iterator(); |
||||
|
||||
while(nameIterator.hasNext()) { |
||||
String name = (String)nameIterator.next(); |
||||
Iterator valueIterator = ((List)form.get(name)).iterator(); |
||||
|
||||
while(valueIterator.hasNext()) { |
||||
String value = (String)valueIterator.next(); |
||||
builder.append(URLEncoder.encode(name, charset.name())); |
||||
if (value != null) { |
||||
builder.append('='); |
||||
builder.append(URLEncoder.encode(value, charset.name())); |
||||
if (valueIterator.hasNext()) { |
||||
builder.append('&'); |
||||
} |
||||
} |
||||
} |
||||
|
||||
if (nameIterator.hasNext()) { |
||||
builder.append('&'); |
||||
} |
||||
} |
||||
|
||||
byte[] bytes = builder.toString().getBytes(charset.name()); |
||||
outputMessage.getHeaders().setContentLength((long)bytes.length); |
||||
StreamUtils.copy(bytes, outputMessage.getBody()); |
||||
} |
||||
|
||||
private void writeMultipart(MultiValueMap<String, ?> parts, HttpOutputMessage outputMessage) throws IOException { |
||||
byte[] boundary = this.generateMultipartBoundary(); |
||||
Map<String, String> parameters = Collections.singletonMap("boundary", new String(boundary, "US-ASCII")); |
||||
MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters); |
||||
outputMessage.getHeaders().setContentType(contentType); |
||||
this.writeParts(outputMessage.getBody(), (MultiValueMap<String, Object>) parts, boundary); |
||||
writeEnd(outputMessage.getBody(), boundary); |
||||
} |
||||
|
||||
private void writeParts(OutputStream os, MultiValueMap<String, Object> parts, byte[] boundary) throws IOException { |
||||
Iterator var4 = parts.entrySet().iterator(); |
||||
|
||||
while(var4.hasNext()) { |
||||
Map.Entry<String, List<Object>> entry = (Map.Entry)var4.next(); |
||||
String name = (String)entry.getKey(); |
||||
Iterator var7 = ((List)entry.getValue()).iterator(); |
||||
|
||||
while(var7.hasNext()) { |
||||
Object part = var7.next(); |
||||
if (part != null) { |
||||
this.writeBoundary(os, boundary); |
||||
this.writePart(name, this.getHttpEntity(part), os); |
||||
writeNewLine(os); |
||||
} |
||||
} |
||||
} |
||||
|
||||
} |
||||
|
||||
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException { |
||||
Object partBody = partEntity.getBody(); |
||||
Class<?> partType = partBody.getClass(); |
||||
HttpHeaders partHeaders = partEntity.getHeaders(); |
||||
MediaType partContentType = partHeaders.getContentType(); |
||||
Iterator var8 = this.partConverters.iterator(); |
||||
|
||||
HttpMessageConverter messageConverter; |
||||
do { |
||||
if (!var8.hasNext()) { |
||||
throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter found for request type [" + partType.getName() + "]"); |
||||
} |
||||
|
||||
messageConverter = (HttpMessageConverter)var8.next(); |
||||
} while(!messageConverter.canWrite(partType, partContentType)); |
||||
|
||||
HttpOutputMessage multipartMessage = new UTF8FormHttpMessageConverter.MultipartHttpOutputMessage(os); |
||||
multipartMessage.getHeaders().setContentDispositionFormData(name, this.getFilename(partBody)); |
||||
if (!partHeaders.isEmpty()) { |
||||
multipartMessage.getHeaders().putAll(partHeaders); |
||||
} |
||||
|
||||
messageConverter.write(partBody, partContentType, multipartMessage); |
||||
} |
||||
|
||||
protected byte[] generateMultipartBoundary() { |
||||
byte[] boundary = new byte[this.random.nextInt(11) + 30]; |
||||
|
||||
for(int i = 0; i < boundary.length; ++i) { |
||||
boundary[i] = BOUNDARY_CHARS[this.random.nextInt(BOUNDARY_CHARS.length)]; |
||||
} |
||||
|
||||
return boundary; |
||||
} |
||||
@Override |
||||
protected HttpEntity<?> getHttpEntity(Object part) { |
||||
return part instanceof HttpEntity ? (HttpEntity)part : new HttpEntity(part); |
||||
} |
||||
@Override |
||||
protected String getFilename(Object part) { |
||||
if (part instanceof Resource) { |
||||
Resource resource = (Resource)part; |
||||
return resource.getFilename(); |
||||
} else { |
||||
return null; |
||||
} |
||||
} |
||||
|
||||
private void writeBoundary(OutputStream os, byte[] boundary) throws IOException { |
||||
os.write(45); |
||||
os.write(45); |
||||
os.write(boundary); |
||||
writeNewLine(os); |
||||
} |
||||
|
||||
private static void writeEnd(OutputStream os, byte[] boundary) throws IOException { |
||||
os.write(45); |
||||
os.write(45); |
||||
os.write(boundary); |
||||
os.write(45); |
||||
os.write(45); |
||||
writeNewLine(os); |
||||
} |
||||
|
||||
private static void writeNewLine(OutputStream os) throws IOException { |
||||
os.write(13); |
||||
os.write(10); |
||||
} |
||||
|
||||
private static class MultipartHttpOutputMessage implements HttpOutputMessage { |
||||
private final OutputStream outputStream; |
||||
private final HttpHeaders headers = new HttpHeaders(); |
||||
private boolean headersWritten = false; |
||||
|
||||
public MultipartHttpOutputMessage(OutputStream outputStream) { |
||||
this.outputStream = outputStream; |
||||
} |
||||
@Override |
||||
public HttpHeaders getHeaders() { |
||||
return this.headersWritten ? HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers; |
||||
} |
||||
@Override |
||||
public OutputStream getBody() throws IOException { |
||||
this.writeHeaders(); |
||||
return this.outputStream; |
||||
} |
||||
|
||||
private void writeHeaders() throws IOException { |
||||
if (!this.headersWritten) { |
||||
Iterator var1 = this.headers.entrySet().iterator(); |
||||
|
||||
while(var1.hasNext()) { |
||||
Map.Entry<String, List<String>> entry = (Map.Entry)var1.next(); |
||||
byte[] headerName = this.getAsciiBytes((String)entry.getKey()); |
||||
Iterator var4 = ((List)entry.getValue()).iterator(); |
||||
|
||||
while(var4.hasNext()) { |
||||
String headerValueString = (String)var4.next(); |
||||
byte[] headerValue = this.getAsciiBytes(headerValueString); |
||||
this.outputStream.write(headerName); |
||||
this.outputStream.write(58); |
||||
this.outputStream.write(32); |
||||
this.outputStream.write(headerValue); |
||||
UTF8FormHttpMessageConverter.writeNewLine(this.outputStream); |
||||
} |
||||
} |
||||
|
||||
UTF8FormHttpMessageConverter.writeNewLine(this.outputStream); |
||||
this.headersWritten = true; |
||||
} |
||||
|
||||
} |
||||
|
||||
private byte[] getAsciiBytes(String name) { |
||||
try { |
||||
return name.getBytes("UTF-8"); |
||||
} catch (UnsupportedEncodingException var3) { |
||||
throw new IllegalStateException(var3); |
||||
} |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,8 @@
|
||||
##\u4E0A\u4F20\u6587\u4EF6\u63A5\u53E3 |
||||
upload=http://api-gw-test.devapps.hisense.com/message/api/upload/uploadEnclosureFile?app_id=d2dba99d&app_key=53e68bc8afc94918af452b4f69867834 |
||||
##\u6D88\u606F\u63A5\u53E3 |
||||
common=http://api-gw-test.devapps.hisense.com/message/api/messageInfos/sendCommonMessage?app_id=147a1a38&app_key=cac0fc915c405755205b778898eca8bd |
||||
## |
||||
sysCode= |
||||
## |
||||
urlName= |
Loading…
Reference in new issue