From ff2f944fa929ce68b94c2621b7f7b3d6bb2459bb Mon Sep 17 00:00:00 2001 From: 苗权威 <1160292058@qq.com> Date: Fri, 20 Sep 2019 21:03:16 +0800 Subject: [PATCH] 9.20 --- .idea/compiler.xml | 1 + .idea/workspace.xml | 666 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java | 21 +++++++++++++++++++++ tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java | 11 +++++------ tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java | 9 +++++---- tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java | 43 ++++++++++++++++++++++++++++++++++--------- tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/DelCacheCallbackUrlRequest.java | 16 ++++++++++++++++ tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java | 19 +++---------------- tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/upload/UploadOneSenData.java | 2 ++ tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java | 291 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------------------------------------------------------- tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java | 2 +- tts_service/src/main/resources/application.yml | 3 ++- xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/TestBuild.java | 36 +++++++----------------------------- 13 files changed, 628 insertions(+), 492 deletions(-) create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/DelCacheCallbackUrlRequest.java diff --git a/.idea/compiler.xml b/.idea/compiler.xml index 8c04fd8..3cb42ad 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -2,6 +2,7 @@ + diff --git a/.idea/workspace.xml b/.idea/workspace.xml index ccf257a..adfcde0 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,44 +2,18 @@ + - - - - - - - - - + - - + + - - - - - - - - - - - - - - - - - - - - + @@ -85,8 +59,8 @@ - - + + @@ -97,90 +71,88 @@ - - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - + + - + - - - - - - + + - + - - + + - + - - + + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -199,22 +171,6 @@ - initialize - OFFLINE_2_ONLINE - person - UPLOADED_DIR - dirs - size - npcName - OkHttp3Utils - buildMP3Filename - init_url - requestTemplate方法创建文件 - resCode - resCode:{} - url - DU_ID_2_US_ID - PRODUCT_NAME_DETAIL botAccount HZ1_BOT_TO_NX2 PlayUtils @@ -222,13 +178,29 @@ botName PERSON_MOODURL OFFLINE_SERVER - repeateName2Ids successUpLoadFileIds data - id2Info log.info - del_record_callback_url allRepeateName2Id + nameRepeats + allRepeateId2Info + record_dir + filePath + dirs + offlineCallback: + filename + getOnline + url + folder + allOldname2Id + tts + id2Info + allRepeateName2Info + repeateName2Ids + del_record_callback_url + record_callback_url + buildMp3Response + HttpServletResponse OPENID_CACHE @@ -244,13 +216,6 @@ @@ -327,8 +299,8 @@ - @@ -340,6 +312,7 @@ + @@ -400,7 +373,7 @@ - + @@ -408,24 +381,30 @@ - - - + - + + + + + + + + + + + + - - - - + @@ -435,7 +414,6 @@ - @@ -449,7 +427,7 @@ - + @@ -457,7 +435,7 @@ - + @@ -501,7 +479,7 @@ - + @@ -1016,7 +997,7 @@ - @@ -1028,7 +1009,7 @@ - + @@ -1042,7 +1023,7 @@ - + @@ -1050,7 +1031,7 @@ - + @@ -1059,7 +1040,7 @@ - + @@ -1077,403 +1058,432 @@ - - + - - + + - + - - + + + + + + - + - - + + - + - - + + + + + + + + - - + + + + + + - + - - + + - + + - + - - + + - + - - + + - + - - + + - + - - + + + + + + - + - - + + - + - - + + - + - - + + - + - - + + + + + + - + + - - + + + + + + - + - - + + - + - - - - - - + + - + - - + + - + - - - - - - - - + + - + - - + + - + - - + + - + - - - - - - + + - + - - + + - + - - + + + + + + - + - - + + - + - - + + - + - - - - - - + + - + - - + + - + - - + + - + - - + + + + + - + - - + + - + - - + + - + - - + + - + - - + + - + - - - - - - + + - + - - + + + + + + + - + - - + + - + - - + + - + - - + + - + - - + + - - + + - + - - - - - - - - - - - - + + - + - - + + - + - - + + + + + - + - - + + - + - - + + - + - - - - - + - + - - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - - - - - + + - - + + - - + + diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java index 4ed6cd8..5aa9b97 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java @@ -118,6 +118,27 @@ public class OkHttp3Utils { return null; } + public static Integer doPostJsonStrReturnCode(String url, String requestJsonStr) throws IOException { + Request.Builder builder = new Request.Builder(); + Request request = builder.url(url).build(); + + Headers.Builder headBuilder = request.headers().newBuilder(); + + headBuilder.add("Content-Type","application/json; charset=utf-8"); + + builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr)); + try (Response response = client.newCall(builder.build()).execute()){ + int code = response.code(); + response.body().string(); + return code; + }catch (SocketTimeoutException e) { + log.error("捕获到SocketTimeoutException:{}", e.toString()); + client.dispatcher().cancelAll(); + client.connectionPool().evictAll(); + } + return null; + } + public static ResponseCodeWithData doPostTimeout(String url, Map headers, String requestJsonStr, File file, boolean longTime) throws IOException { OkHttpClient timeoutClient; diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java index 7bfa304..0dd7bc1 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java @@ -1,5 +1,6 @@ package ai.qiwu.com.tts_service.common; +import ai.qiwu.com.tts_service.pojo.TTSRequest; import ai.qiwu.com.tts_service.service.Initialize; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; @@ -135,6 +136,8 @@ public class TTSUtils { return true; } + + public static void deleteFile(File file) { if (!file.exists()) return; if (file.isDirectory()) { @@ -414,11 +417,7 @@ public class TTSUtils { } public static void main(String[] args) { - File deleteBotDir = new File("/home/yf01/springbootdemo"); - File[] needDelete = deleteBotDir.listFiles((dir, name) -> !name.equals("record")); - //System.out.println(needDelete.length); - //System.out.println(Arrays.toString(needDelete)); - - System.out.println(charset(new File("/usr/local/sublimeWorkplace/font/play.json"))); + String test2 = "{\"_type\":\"json\",\"person\":\"A04_offline\",\"tone\":\"正常\",\"text\":\"你认为水星有水存在吗\",\"curDate\":1568879455745,\"botname\":\"6854303973\",\"pitch\":0,\"speed\":1.36,\"volume\":5,\"npcName\":\"旁白\",\"get_online\":false}"; + System.out.println(JSON.parseObject(test2, TTSRequest.class)); } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java index b24fc96..73104a6 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java @@ -6,6 +6,7 @@ import ai.qiwu.com.tts_service.pojo.TTSResponse; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -63,8 +64,8 @@ public class TTServiceUtil { out.write(buffer, 0, ln); } out.flush(); - } catch (Exception e) { - log.error("写入音频流到HttpServletResponse失败:{}", e.toString()); + } catch (IOException e) { + log.error("buildMp3Response:写入音频流到HttpServletResponse失败:{}", ExceptionUtils.getStackTrace(e)); } } } @@ -101,8 +102,8 @@ public class TTServiceUtil { out.write(buffer, 0, ln); } out.flush(); - } catch (Exception e) { - log.error("写入音频流到HttpServletResponse失败:{}", e.toString()); + } catch (IOException e) { + log.error("buildServletResponse:写入音频流到HttpServletResponse失败:{}", ExceptionUtils.getStackTrace(e)); } } else { String ttsResJsonStr = JSON.toJSONString(ttsResponse); diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java index 2300d9d..a4fe52c 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java @@ -8,6 +8,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -46,8 +47,8 @@ public class TTSController { @RequestParam(required = false) String text, @RequestParam(required = false) String botname, @RequestParam(required = false) String _type, @RequestParam(required = false) String volume, @RequestParam(required = false) String pitch, @RequestParam(required = false) String speed, - @RequestParam(required = false) Boolean get_online, HttpServletResponse servletResponse) { - TTSRequest ttsRequest = new TTSRequest(person, text, _type, pitch, tone, botname, volume, speed,get_online); + @RequestParam(required = false) Boolean get_online, @RequestParam(required = false) String npcName,HttpServletResponse servletResponse) { + TTSRequest ttsRequest = new TTSRequest(person, text, _type, pitch, tone, botname, volume, speed,get_online,npcName); ttService.tts(ttsRequest, "GET", servletResponse); } @@ -89,16 +90,40 @@ public class TTSController { response.setStatus(200); } +// @PostMapping("/api/upload/record/one_sen") +// public void uploadOneSen(MultipartFile file, Integer tid, String botName, String npcName, +// String text, HttpServletResponse response) { +// UploadOneSenData data = new UploadOneSenData(tid, botName, npcName, text, file); +// +// ttService.uploadOneSen(data, response); +// } + @PostMapping("/api/upload/record/one_sen") - public void uploadOneSen(MultipartFile file, Integer tid, String botName, String npcName, - String text, HttpServletResponse response) { - UploadOneSenData data = new UploadOneSenData(tid, botName, npcName, text, file); + public void uploadOneSen(HttpServletRequest request, HttpServletResponse response) { + MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request; + MultipartFile file = mulRequest.getFile("file"); + String botName = mulRequest.getParameter("botName"); + String npcName = mulRequest.getParameter("npcName"); + String text = mulRequest.getParameter("text"); + String tid = mulRequest.getParameter("tid"); + UploadOneSenData data = new UploadOneSenData(Integer.valueOf(tid), botName, npcName, text, file); + ttService.uploadOneSen(data, response); } +// @PostMapping("/api/upload/record/one_npc") +// public void uploadOneNpc(MultipartFile file, String botName, String npcName, +// HttpServletResponse response) { +// UploadOneSenData data = new UploadOneSenData(botName, npcName, file); +// ttService.uploadOneNpc(data, response); +// } + @PostMapping("/api/upload/record/one_npc") - public void uploadOneNpc(MultipartFile file, String botName, String npcName, - HttpServletResponse response) { + public void uploadOneNpc(HttpServletRequest request, HttpServletResponse response) { + MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request; + MultipartFile file = mulRequest.getFile("file"); + String botName = mulRequest.getParameter("botName"); + String npcName = mulRequest.getParameter("npcName"); UploadOneSenData data = new UploadOneSenData(botName, npcName, file); ttService.uploadOneNpc(data, response); } @@ -109,8 +134,8 @@ public class TTSController { } @PostMapping("/api/offline_callback") - public void offlineCallback(MultipartFile file, String url, String ids, HttpServletResponse response) { - ttService.offlineCallback(file, url, ids, response); + public void offlineCallback(MultipartFile file, HttpServletResponse response) { + ttService.offlineCallback(file, response); } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/DelCacheCallbackUrlRequest.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/DelCacheCallbackUrlRequest.java new file mode 100644 index 0000000..6782a15 --- /dev/null +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/DelCacheCallbackUrlRequest.java @@ -0,0 +1,16 @@ +package ai.qiwu.com.tts_service.pojo; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * @author 苗权威 + * @dateTime 19-9-20 上午10:03 + */ +@Getter +@Setter +@ToString +public class DelCacheCallbackUrlRequest { + private String botname; +} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java index c7b3adc..7d54e56 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java @@ -1,9 +1,7 @@ package ai.qiwu.com.tts_service.pojo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; +import lombok.*; /** * @author 苗权威 @@ -12,6 +10,8 @@ import lombok.ToString; @Getter @Setter @ToString +@AllArgsConstructor +@NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class TTSRequest { private String person; @@ -24,17 +24,4 @@ public class TTSRequest { private String speed; private Boolean get_online; private String npcName; - - public TTSRequest(String person, String text, String _type, String pitch, - String tone, String botname, String volume, String speed,Boolean get_online) { - this.person = person; - this.text = text; - this._type = _type; - this.pitch = pitch; - this.tone = tone; - this.botname = botname; - this.volume = volume; - this.speed = speed; - this.get_online = get_online; - } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/upload/UploadOneSenData.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/upload/UploadOneSenData.java index 6d3b0ba..c7175da 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/upload/UploadOneSenData.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/upload/UploadOneSenData.java @@ -3,6 +3,7 @@ package ai.qiwu.com.tts_service.pojo.upload; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Getter; import lombok.Setter; +import lombok.ToString; import org.springframework.web.multipart.MultipartFile; /** @@ -11,6 +12,7 @@ import org.springframework.web.multipart.MultipartFile; */ @Getter @Setter +@ToString @JsonIgnoreProperties(ignoreUnknown = true) public class UploadOneSenData { private Integer tid; diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java index ae8dfa8..935e8d9 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java @@ -8,6 +8,7 @@ import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData; import ai.qiwu.com.tts_service.service.baidu.ThirdPartyService; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -16,6 +17,7 @@ import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.*; +import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.*; @@ -100,7 +102,7 @@ public class TTService { } onlineCache.setServer(Initialize.getServerName()); String offlineStr = JSON.toJSONString(onlineCache); - int deleteOfflineResCode; + Integer deleteOfflineResCode; String result = TTSConstants.DELETE_SUCCESS; try { //String url = String.format("%s/online_cache", Initialize.getOfflineServer()); @@ -111,7 +113,11 @@ public class TTService { result = TTSConstants.DELETE_OFFLINE_FAIL; deleteOfflineResCode = 555; }else { - deleteOfflineResCode = OkHttp3Utils.doPostReturnCode(Initialize.getDelCacheCallbackUrl(), new HashMap<>()); + //deleteOfflineResCode = OkHttp3Utils.doPostReturnCode(Initialize.getDelCacheCallbackUrl(), new HashMap<>()); + DelCacheCallbackUrlRequest request = new DelCacheCallbackUrlRequest(); + request.setBotname(botName); + deleteOfflineResCode = OkHttp3Utils.doPostJsonStrReturnCode(Initialize.getDelCacheCallbackUrl(), JSON.toJSONString(request)); + if (deleteOfflineResCode == null) deleteOfflineResCode = 556; } } catch (Exception e) { log.error("删除offline地址的bot请求出错:{},offlineStr:{}", e.toString(),offlineStr); @@ -131,6 +137,13 @@ public class TTService { public void mp3(String dirs, String filename, String _type, HttpServletResponse response) { // 修正dirs的格式 if (dirs != null) { + try { + dirs = URLDecoder.decode(dirs, "UTF-8"); + } catch (UnsupportedEncodingException e) { + log.error("url解码出错:请求目录{},请求文件名:{}",dirs,filename); + TTServiceUtil.buildMp3Response(response, new MP3Response(400), null, 400, false); + return; + } if ("..".equals(dirs) || StringUtils.startsWith(dirs, "/")) { TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,不能包含..或是以/开头"), null, 400, false); @@ -287,7 +300,11 @@ public class TTService { // ResponseCodeWithData data = future.get(60, TimeUnit.SECONDS); ResponseCodeWithData data = future.get(); if (data.getCode() != 200) { - log.error("下载音频失败, status:{}", data.getCode()); + if (data.getCode() == 404) { + log.info("404,音频没有找到"); + }else { + log.error("下载音频失败, status:{}", data.getCode()); + } TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(data.getCode()), null, data.getCode()); return; } @@ -324,8 +341,8 @@ public class TTService { TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(555, "小爱平台的请求,聚合mp3文件失败"), null, 555); } else { String audio = Initialize.getServerUrl()+"/api/tts/get_audio?dirs=%s&filename=%s"; - TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse( String.format(audio, URLEncoder.encode(dirs), - URLEncoder.encode(tmp_name)),200), null, 200); + TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse( String.format(audio, URLEncoder.encode(dirs, "UTF-8"), + tmp_name),200), null, 200); } } catch (Exception e) { log.error("调用python的combine出错:{}", e.toString()); @@ -380,11 +397,24 @@ public class TTService { */ public void tts(TTSRequest ttsRequest, String requestMethod, HttpServletResponse servletResponse) { // 获取person,没有或数据库中不存在,则付值 init_person + //log.info("ttsRequest:{}",ttsRequest); String person = ttsRequest.getPerson(); if (StringUtils.isBlank(person)) person = initialize.getInit_person(); - String moodUrl = null; String mood = ttsRequest.getTone(); + if (StringUtils.isBlank(mood)) mood = initialize.getInit_tone(); + boolean doesThirdPerson = Initialize.getThirdPartyTts().contains(person); + String moodUrl = null; + if (!doesThirdPerson) { + Map map = initialize.getPersonMoodurl().get(person); + if (map != null) moodUrl = map.get(mood); + else { + TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(404, "找不到"+person), null, 404); + return; + } + } else { + mood = "正常"; + } Boolean getOnline = ttsRequest.getGet_online(); if (getOnline == null) getOnline = true; // text字段不能为空 @@ -393,8 +423,7 @@ public class TTService { TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(404, "文本不能为空"), null, 404); return; } - - if (getOnline && !Initialize.getThirdPartyTts().contains(person)) { + if (getOnline && !doesThirdPerson) { if (!initialize.getPersonMoodurl().containsKey(person)) { person = initialize.getInit_person(); } @@ -416,8 +445,6 @@ public class TTService { return; } //log.info("426:moodurl:{}", moodUrl); - } else { - mood = "正常"; } double volume = Double.parseDouble(ttsRequest.getVolume() == null ? "0" : ttsRequest.getVolume()); @@ -433,15 +460,22 @@ public class TTService { // (audio_dir)/botname/person/mood目录 String botFolder = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).toString(); +// log.info("botFolder:{}",botFolder); String folder = StringUtils.join(new String[]{botFolder, person, mood}, File.separator); +// log.info("folder:{}",folder); String fileName = TTSUtils.buildMP3Filename(text); +// log.info("fileName:{}",fileName); String filePath; + String dirs = null; // (audio_dir)/botname/person/mood/xxx.mp3文件路径 if (StringUtils.isNotBlank(npcName) && !"PUT".equals(requestMethod)) { String uploadedFilePath = StringUtils.join(new String[]{botFolder,Initialize.getUploadedDir(),npcName,fileName}, File.separator); +// log.info("uploadedFilePath:{}",uploadedFilePath); if (TTSUtils.doesFileExist(uploadedFilePath)) { filePath = uploadedFilePath; + dirs = String.format("[%s,%s,%s]", botName, Initialize.getUploadedDir(), npcName); } else { +// log.info("文件不存在"); TTSUtils.makedir(folder); filePath = StringUtils.join(new String[]{folder, fileName}, File.separator); } @@ -453,10 +487,10 @@ public class TTService { TTSResponse response = null; // _type为json,则构建请求get_audio接口的信息 if ("json".equals(ttsRequest.get_type())) { - String dirs = String.format("[%s,%s,%s]", botName, person, mood); + if (dirs == null) dirs = String.format("[%s,%s,%s]", botName, person, mood); //http://(server_url)/api/tts/get_audio?dirs=[botname+person,mood]&filename=xxx.mp3 try { - dirs = URLEncoder.encode(dirs, "utf-8"); // 编码URL中的中文 + dirs = URLEncoder.encode(dirs, "UTF-8"); // 编码URL中的中文 String audio = String.format("%s/api/tts/get_audio?dirs=%s&filename=%s", Initialize.getServerUrl(), dirs, fileName); response = new TTSResponse(audio,200); @@ -472,7 +506,11 @@ public class TTService { data.setNpcName(npcName); ResponseCodeWithData codeWithData = generalMP3(moodUrl, data, filePath, requestMethod, getOnline); if (codeWithData.getCode() != 200) { - log.error("下载:{}音频失败", moodUrl); + if (codeWithData.getCode() == 404) { + log.info("404,请求地址不存在"); + }else { + log.error("下载:{}音频失败", moodUrl); + } TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(codeWithData.getCode()), null, codeWithData.getCode()); return; } @@ -504,15 +542,15 @@ public class TTService { if (genRecordWithChange(url, data, filePath, requestMethod, getOnline)) return new ResponseCodeWithData(200); } if (!TTSUtils.doesFileExist(wavFilename)) { - if (url == null) { - res = dealThirdPartyBaiDu(data.getText().trim(), data.getPerson(), wavFilename); + if (Initialize.getThirdPartyTts().contains(data.getPerson())) { + res = dealThirdParty(data.getText().trim(), data.getPerson(), wavFilename); if (res.getCode() != 200) { return res; } } else { data.setFormat("wav"); boolean longTime = true; - if (url.equals(offlineService)) { + if (offlineService.equals(url)) { longTime = false; } //long wavStartTime = System.currentTimeMillis(); @@ -521,7 +559,7 @@ public class TTService { //long wavEndTime = System.currentTimeMillis(); //log.info("wav whole time:{}", (wavEndTime-wavStartTime)/1000.0); if (res.getCode() != 200) { - log.error("请求线上地址,下载音频文件:{},失败:{}",wavFilename,res); + log.info("请求地址不存在,下载音频文件:{},失败:{}",wavFilename,res); return res; } } @@ -592,6 +630,16 @@ public class TTService { return res; } + /** + * 分段方法.text中,AB符号之间的为变量,其余为非变量,首先我们去record下去找非变量部分,若都存在, + * 那么对于变量来说:若其在record下不存在则在调用generalMP3生成,最后合并;若有一个非变量部分不存在则整体调用generalMP3生成 + * @param url + * @param data + * @param personToneFilePath + * @param requestMethod + * @param getOnline + * @return + */ private boolean genRecordWithChange(String url, GeneralMP3Data data, String personToneFilePath, String requestMethod, boolean getOnline) { String text = data.getText(); @@ -649,6 +697,15 @@ public class TTService { return false; } + /** + * 构建sox信息,命令行调用sox命令,将wavFilename转为mp3FilePath + * @param wavFilename wav文件地址 + * @param volume 音量 + * @param speed 速度 + * @param pitch 语调 + * @param mp3FilePath mp3文件地址 + * @return + */ private ResponseCodeWithData changeSound(String wavFilename, double volume, double speed, double pitch, String mp3FilePath) { String executeResult = null; @@ -671,8 +728,7 @@ public class TTService { } /** - * 下载音频文件或只是普通的post请求,失败尝试次数3. - * 线上请求失败尝试三次,线下请求若404则得到其线上地址,没有则置为init_url,获取该线上地址的person与data,向该线上地址发出请求 + * 下载音频文件或只是普通的post请求,失败尝试次数3 * @param url 音频请求地址 * @param data 请求信息 * @param filePath 文件地址 @@ -688,11 +744,6 @@ public class TTService { for (int i = 0; i < 3; i++) { try { if (filePath != null) { -// mp3File = TTSUtils.createFileReturnIts(filePath); -// if (mp3File == null) { -// log.error("requestTemplate方法创建文件:{}失败", filePath); -// return new ResponseCodeWithData(555, "创建文件失败"); -// } res = OkHttp3Utils.doPostTimeout(url, new HashMap<>(), dataStr, new File(filePath), longTime); } else { res = OkHttp3Utils.doPostTimeout(url, new HashMap<>(), dataStr, null, longTime); @@ -711,7 +762,9 @@ public class TTService { return res; } else if (resCode == 404 && url.equals(offlineService)) { + // 明确指定是线下请求的则直接返回404 if (!getOnline) return new ResponseCodeWithData(404, "没有找到该文件"); + // 根据person,toon获取其线上地址 String person = data.getPerson(); String mood = data.getTone(); try { @@ -721,10 +774,12 @@ public class TTService { Integer id; if ((id = moodJumpId.get(mood)) != null) url = Initialize.getOnlineId2Url().get(id); } + // 若线上url地址列表不能包含该地址,则将该地址置为默认地址 if (initialize.doesThisMoodUrlWithOnline0(url)) { url = initialize.getInit_url(); //log.info("requestTemplate方法,init_url:{}",url); } + // 修正data中的person与tone List personTon = Initialize.getUrl2PersonTon(url); data.setPerson(personTon.get(0)); data.setTone(personTon.get(1)); @@ -732,7 +787,8 @@ public class TTService { res = requestLongTimeout(url, dataStr, new File(filePath)); //log.info("requestLongTimeout返回结果:{}",res.getCode()); } catch (Exception e) { - log.error("person:{},mood:{}, url not found", person, mood); + log.error("线下跳转线上地址请求发生错误:person:{},mood:{}, 错误信息:{}", person, mood, + ExceptionUtils.getStackTrace(e)); res = null; } break; @@ -749,7 +805,7 @@ public class TTService { } /** - * 线下请求超时的话尝试将时间延长为12s再次进行请求,失败尝试次数3 + * 线下请求超时的话尝试将时间延长再次进行请求,失败尝试次数3 * @param url 音频请求地址 * @param dataJsonStr 请求信息 * @param file 是否是下载音频文件的请求 @@ -774,22 +830,15 @@ public class TTService { } } if (res == null) { - log.error("请求无法获取到结果:{},该请求信息是:{}", url,dataJsonStr); + log.error("请求无法获取到结果:{}", url); } return res; } - private ResponseCodeWithData dealThirdPartyBaiDu(String text, String person, String filepath) { + private ResponseCodeWithData dealThirdParty(String text, String person, String filepath) { boolean result; -// try { -// result = TTSUtils.createFile(filepath); -// } catch (Exception e) { -// log.error("创建第三方wav文件失败:{}", e.toString()); -// return new ResponseCodeWithData(555, "创建第三方wav文件失败"); -// } -// if (!result) return new ResponseCodeWithData(555, "创建第三方wav文件失败"); - - text = text.replaceAll("\\{/(.+?)/}", ""); + // 去除所有{/../} + text = text.replaceAll("\\{/.*?/}", "").trim(); result = ThirdPartyService.thirdPartyCall(text, Initialize.theThirdPartysPer(person), filepath, person); if (result) { return new ResponseCodeWithData(200, "创建第三方wav文件成功"); @@ -797,6 +846,7 @@ public class TTService { return new ResponseCodeWithData(555, "调用第三方生成wav文件失败"); } + // 更新初始化的信息用 public void updateCache() throws Exception { initialize.afterPropertiesSet(); } @@ -809,7 +859,8 @@ public class TTService { */ public void uploadOneSen(UploadOneSenData data, HttpServletResponse response) { //tid,botName,npcName,text,file皆不能为空,否则返回400 - if (StringUtils.isAnyBlank(String.valueOf(data.getTid()),data.getBotName(), data.getNpcName(), data.getText()) || data.getFile() == null) { + //log.info("UploadOneSenData:{}",data); + if (StringUtils.isAnyBlank(String.valueOf(data.getTid()),data.getBotName(), data.getNpcName(), data.getText()) || data.getFile().getName() == null) { TTServiceUtil.buildUploadResponse(response, new TTSResponse(400, "参数不能为空"), 400); return; } @@ -817,11 +868,15 @@ public class TTService { String folder = StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotName(), Initialize.getUploadedDir(), data.getNpcName()},File.separator); // absolute filepath - String filename = StringUtils.join(new String[]{folder, TTSUtils.buildMP3Filename(data.getText())}, File.separator); + final String filename = StringUtils.join(new String[]{folder, TTSUtils.buildMP3Filename(data.getText())}, File.separator); + //log.info("filepath:{}",filename); // 删除之前已存在的文件 - if (TTSUtils.doesFileExist(filename) && !new File(filename).delete()) { - TTServiceUtil.buildUploadResponse(response, new TTSResponse(555, "删除已存在的文件失败:"+filename), 555); - return; + if (TTSUtils.doesFileExist(filename) ) { + if (!new File(filename).delete()) { + TTServiceUtil.buildUploadResponse(response, new TTSResponse(555, "删除已存在的文件失败:"+filename), 555); + return; + } + POOL.submit(() -> new File(new StringBuilder(filename).append(".b64").toString()).delete()); } // 创建目录 else if (!TTSUtils.makedir(folder)) { @@ -902,62 +957,76 @@ public class TTService { // 所有失败了的id以及失败原因 HashMap allFailUpLoadId2Reason = new HashMap<>(); - // 每句话的id指向它的具体信息, + // 每句话的id->具体信息, HashMap id2Info = new HashMap<>(); - // 修改后的文件名->该句话的id - HashMap allOldname2Id = new HashMap<>(); +// // 修改后的文件名->该句话的id +// HashMap allOldname2Id = new HashMap<>(); + // 指向同一音频文件,且text相同的文件名->id,该信息用来提用户,这种text相同指向文件相同的情况是否是他想要的 - HashMap> allRepeateId2Info = new HashMap<>(); + HashMap> allRepeateName2Info = new HashMap<>(); // 指向相同文件的所有语句id集合 HashMap> repeateName2Ids = new HashMap<>(); // 意料之外的错误发生,无法判断程序进度,记录该种情况最后根据情况返回相应的信息 boolean unExpectException = false; + boolean hasRepeate = false; try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), Charset.forName(encoding)))){ String row = reader.readLine(); // 去掉首行 while ((row = reader.readLine()) != null) { row = TTSUtils.tripEnter(row); // 去掉末尾所有换行符 // id,text,isUpload,filename String[] arr = row.split(","); // 切分 + if (arr.length != 4) continue; String audioFileName = arr[3]; // filename列不为空代表用户为该句指定了文件 if (StringUtils.isNotBlank(audioFileName)) { id2Info.put(arr[0],arr); // 存储该行的详细信息,用于之后展示错误信息使用 // 修正文件名,不包含后缀名的加上.mp3后缀名 audioFileName = StringUtils.endsWith(audioFileName,".mp3") ? audioFileName : audioFileName+".mp3"; - String previousId; +// String previousId; // 若之前已有相同文件名,则将该文件的id加入集合,以该文件名为key - if ((previousId = allOldname2Id.putIfAbsent(audioFileName, arr[0])) != null) { - List repeateIds = repeateName2Ids.computeIfAbsent(audioFileName, s -> new ArrayList<>()); - repeateIds.add(arr[0]); +// (previousId = allOldname2Id.putIfAbsent(audioFileName, arr[0])) != null + List repeateIds = repeateName2Ids.computeIfAbsent(audioFileName, s -> new ArrayList<>()); + if (repeateIds.size() != 0) { +// Set repeateIds = repeateName2Ids.computeIfAbsent(audioFileName, s -> new HashSet<>()); +// repeateIds.add(arr[0]); +// repeateIds.add(previousId); //遍历指向相同文件的语句,生成text与当前一样的语句的提示信息 + boolean beforeSuccess = false; + hasRepeate = true; for (String repeateId: repeateIds) { - if (!repeateId.equals(arr[0]) && arr[1].equals(id2Info.get(repeateId)[1])){ - List repeateInfo = allRepeateId2Info.computeIfAbsent(arr[0], s -> new ArrayList<>()); - repeateInfo.add(String.format("其与id是%s指向同一音频文件,且text相同,这是您想要的结果吗",repeateId)); + if (arr[1].equals(id2Info.get(repeateId)[1])) { + Set textIdEqualIds = allRepeateName2Info.computeIfAbsent(audioFileName, s -> new HashSet<>()); + textIdEqualIds.add(arr[0]); + textIdEqualIds.add(repeateId); + //repeateInfo.add(String.format("其与id是%s指向同一音频文件,且text相同,这是您想要的结果吗",repeateId)); } - } - // repeateName2Ids并不包含首个重复语句的id,所以这里需要再与首个重复id语句进行判断 - if (id2Info.get(previousId)[1].equals(arr[1])) { - List repeateInfo = allRepeateId2Info.computeIfAbsent(arr[0], s -> new ArrayList<>()); - repeateInfo.add(String.format("其与id是%s指向同一音频文件,且text相同,这是您想要的结果吗",previousId)); + if (successUpLoadFileIds.contains(repeateId)) beforeSuccess = true; } // 之前的重复语句并不一定执行成功,若不成功则放行当前的这条重复语句 - if (successUpLoadFileIds.contains(previousId)) { + if (beforeSuccess) { + repeateIds.add(arr[0]); continue; } } - // zip压缩包目录,解压也在该目录下 + repeateIds.add(arr[0]); + // zip压缩包目录,解压也在该目录下;/root/TTS-service/mqwZip/audioFilename String fileInPackage = new StringBuilder(zipFolder).append(File.separator).append(audioFileName).toString(); - String md5Name = TTSUtils.buildMP3Filename(arr[1]); - String usFilename = new StringBuilder(folder).append(File.separator).append(md5Name).toString(); + String md5Name = TTSUtils.buildMP3Filename(arr[1]); //构造mp3文件名 + // audio_dir/botname/record/npcname/xxx.mp3 + final String usFilename = new StringBuilder(folder).append(File.separator).append(md5Name).toString(); + // 压缩包中有该mp3文件 if (TTSUtils.doesFileExist(fileInPackage)) { File usFile = new File(usFilename); boolean result=true; + // 删除之前的旧文件 if (TTSUtils.doesFileExist(usFilename)) { result = usFile.delete(); } + // 删除成功后删除其b64文件,且将压缩包中的文件移到安置目录下,即 + // /root/TTS-service/mqwZip/audioFilename -> audio_dir/botname/record/npcname/xxx.mp3 if (result) { + POOL.submit(() -> new File(new StringBuilder(usFilename).append(".b64").toString()).delete()); if (new File(fileInPackage).renameTo(usFile)) { successUpLoadFileIds.add(arr[0]); } @@ -979,19 +1048,27 @@ public class TTService { String msg = "失败请重新上传;"; //log.info("repeateName2Ids:{}",repeateName2Ids); if (successUpLoadFileIds.size() != 0) { - if (repeateName2Ids.size() != 0) { + if (hasRepeate) { List repeatNameIdList = new ArrayList<>(); for (String successId: successUpLoadFileIds) { String name = id2Info.get(successId)[3]; name = StringUtils.endsWith(name,".mp3") ? name : name+".mp3"; List nameRepeats = repeateName2Ids.get(name); - if (nameRepeats != null && nameRepeats.size()!=0) repeatNameIdList.addAll(nameRepeats); + if (nameRepeats != null && nameRepeats.size()>0) { + nameRepeats.remove(successId); + repeatNameIdList.addAll(nameRepeats); + } } if (repeatNameIdList.size() != 0) successUpLoadFileIds.addAll(repeatNameIdList); + } else { + repeateName2Ids = null; + allRepeateName2Info = null; } POOL.submit(() -> { try { - String str = OkHttp3Utils.doPostJsonStr(Initialize.getRecord_callback_url(), JSON.toJSONString(successUpLoadFileIds)); + String requestCall = JSON.toJSONString(successUpLoadFileIds); + //log.info("requestCall:{}",requestCall); + String str = OkHttp3Utils.doPostJsonStr(Initialize.getRecord_callback_url(), requestCall); if (str != null) { UploadCallbackResponse callbackResponse = JSON.parseObject(str, UploadCallbackResponse.class); if (callbackResponse.getCode() != 200) { @@ -1027,8 +1104,17 @@ public class TTService { .append(";其余部分皆未成功,请重新上传这些失败的文件").toString(); } } - if (allRepeateId2Info.size() != 0) { - msg = new StringBuilder(msg).append(";\n").append("下面为提醒信息,请确认:").append(allRepeateId2Info).toString(); + if (allRepeateName2Info != null && allRepeateName2Info.size() != 0) { + StringBuilder msgBuild = new StringBuilder(msg).append(";\n").append("下面为提醒信息,请确认:"); + for (String id : successUpLoadFileIds) { + String name = id2Info.get(id)[3]; + name = StringUtils.endsWith(name,".mp3") ? name : name+".mp3"; + Set infos = allRepeateName2Info.remove(name); + if (infos != null && infos.size() != 0) msgBuild + .append("下面的id列表,其所代表的语句的text皆为:\"").append(id2Info.get(id)[1]).append("\",且他们指向同一个文件,这是您想要的结果吗?").append(":") + .append(infos).append("; \n"); + } + msg = msgBuild.toString(); } } POOL.submit(() -> TTSUtils.deleteFile(new File(zipFolder))); @@ -1036,42 +1122,65 @@ public class TTService { TTServiceUtil.buildUploadResponse(response, new TTSResponse(200, msg), 200); } + /** + * 删除单个上传音频文件, + * 参数说明:tid:句子id;botName:上传者标识;npcName:npc名称;text:要删除的音频的内容 + * @param data + * @param response + */ public void delOneSen(UploadOneSenData data, HttpServletResponse response) { - if (StringUtils.isAnyBlank(data.getBotName(),data.getNpcName(),data.getText())) { + // 四个参数都不能为空 + if (StringUtils.isAnyBlank(data.getBotName(),data.getNpcName(),data.getText()) || data.getTid() == null) { TTServiceUtil.buildUploadResponse(response, new TTSResponse(400, "参数不对"), 400); return; } - String filePath = StringUtils.join(Arrays.asList(Initialize.getAudioDir(), data.getBotName(), + // audio_dir/botname/record/npcname/xxx.mp3 + final String filePath = StringUtils.join(Arrays.asList(Initialize.getAudioDir(), data.getBotName(), Initialize.getUploadedDir(), data.getNpcName(), TTSUtils.buildMP3Filename(data.getText())), File.separator); - boolean result = true; + boolean result; + // 删除文件 if (TTSUtils.doesFileExist(filePath)) { result = new File(filePath).delete(); - // 目录为空则删除目录 + } else { + log.warn("删除单个上传音频文件不存在:{}", filePath); + TTServiceUtil.buildUploadResponse(response, new TTSResponse(200, "文件不存在"), 200); + return; } + // 删除成功回调接口/text/offline/delUpload/callback if (result) { - String msg=null; - try { - String str = OkHttp3Utils.doPostJsonStr(Initialize.getDelRecordCallbackUrl(), JSON.toJSONString(new int[]{data.getTid()})); - log.info("删除地址回调结果:{}",str); - } catch (Exception e) { - msg = "post del_record_callback error"; - log.error("删除地址回调出错:{}",ExceptionUtils.getStackTrace(e)); - } - TTServiceUtil.buildUploadResponse(response, new TTSResponse(200, msg), 200); + final int tid = data.getTid(); + POOL.submit(() -> { + new File(new StringBuilder(filePath).append(".b64").toString()).delete(); + try { + OkHttp3Utils.doPostJsonStr(Initialize.getDelRecordCallbackUrl(), JSON.toJSONString(new int[]{tid})); + } catch (Exception e) { + log.error("delOneSen删除地址回调出错:{}",e.toString()); + } + }); + TTServiceUtil.buildUploadResponse(response, new TTSResponse(200, "成功"), 200); }else { log.info("delOneSen删除文件失败:{}",filePath); TTServiceUtil.buildUploadResponse(response, new TTSResponse(555, "删除文件失败"), 555); } } - public void offlineCallback(MultipartFile file, String url, String ids, HttpServletResponse response) { - String filename = file.getName(); - if (!StringUtils.endsWith(filename, ".zip") || StringUtils.isAnyBlank(url, ids)) { + /** + * 系统语音合成后回调该接口,目的是将语音文件存放在audio_dir/botname下,压缩包结构:botname/person.. + * @param file + * @param response + */ + public void offlineCallback(MultipartFile file, HttpServletResponse response) { + // zip压缩包 + String filename = file.getOriginalFilename(); + if (!StringUtils.endsWith(filename, ".zip")) { log.info("offlineCallback:{}",filename); TTServiceUtil.buildUploadResponse(response, new TTSResponse(400, "not is zipfile or params is not right"), 400); return; } - String filePath = StringUtils.join(new String[]{Initialize.getZipDir(), filename}, File.separator); + // 因为之后呀删除该压缩包,确保其名字唯一,防止冲突 + filename = new StringBuilder(file.getName()).append(System.currentTimeMillis()) + .append(RandomStringUtils.randomAlphabetic(3)).toString(); + final String filePath = StringUtils.join(new String[]{Initialize.getZipDir(), filename}, File.separator); try { file.transferTo(new File(filePath)); if (!TTSUtils.unZip(Initialize.getAudioDir(), filePath)) { @@ -1080,20 +1189,6 @@ public class TTService { return; } POOL.submit(() -> new File(filePath).delete()); - ids = ids.trim(); - if (StringUtils.isBlank(ids) || ids.length() <= 2) { - TTServiceUtil.buildUploadResponse(response, new TTSResponse(400, "ids为空"), 400); - return; - } - String[] idList = ids.substring(1, ids.length()-1).split(","); - String[] idTrimList = new String[idList.length]; - for (int i = 0; i < idList.length; i++) idTrimList[i] = idList[i].trim(); - try { - String callResponse = OkHttp3Utils.doPostJsonStr(url, JSON.toJSONString(idTrimList)); - log.info("offlineCallback:回调返回{}",callResponse); - } catch (Exception e) { - log.error("offlineCallback回调出错:{}",ExceptionUtils.getStackTrace(e)); - } } catch (Exception e) { log.error("offlineCallback出错:{}",ExceptionUtils.getStackTrace(e)); TTServiceUtil.buildUploadResponse(response, new TTSResponse(555, "程序出错"), 555); diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java index ee26543..d0cfe07 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java @@ -46,7 +46,7 @@ public class ThirdPartyService { options.put("spd", 5); // options.put("pit", correctSoundParams(pitch, true)); options.put("vol", 5); - options.put("aue", 4); + options.put("aue", 6); options.put("per", per); TtsResponse res = CLIENT.synthesis(text, "zh", 1, options); if (res.getResult() == null) { diff --git a/tts_service/src/main/resources/application.yml b/tts_service/src/main/resources/application.yml index 101a10b..43432ac 100644 --- a/tts_service/src/main/resources/application.yml +++ b/tts_service/src/main/resources/application.yml @@ -31,4 +31,5 @@ server: enabled: true pattern: '%h %l %u %t "%r" %s %b bytes %D ms' directory: /home/ubuntu/project/tts/tomcat - #directory: /root/GameEditor/mqw/project/ttsTest/tomcat \ No newline at end of file + #directory: /root/GameEditor/mqw/project/ttsTest/tomcat + connection-timeout: 240000 diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/TestBuild.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/TestBuild.java index 8fca36c..9b1870b 100644 --- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/TestBuild.java +++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/pojo/TestBuild.java @@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject; import com.eclipsesource.json.JsonObject; import lombok.*; +import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.sql.Timestamp; @@ -12,6 +13,7 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; +import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -106,34 +108,10 @@ public class TestBuild { return sb.toString() ; } public static void main(String[] args) { - String s = "\uD83C\uDD70(.*?)\uD83C\uDD71"; - String test = "23424ijoij\uD83C\uDD70\uD83C\uDD71ghoiwugh\uD83C\uDD70oihjoihoih\uD83C\uDD71gerwgwgh"; - String test2 = "342gsegsergh"; - //test = new String(test.getBytes(), Charset.forName("UTF-8")); - Pattern pattern = Pattern.compile(s); - Matcher matcher = pattern.matcher(test2); - //System.out.println(matcher.groupCount()); - System.out.println(matcher.find()); -// while (matcher.find()) { -// System.out.println(matcher.group(1)); -// } - System.out.println(Arrays.toString(pattern.split(test2))); - String test3 = "sgiejogwi{/sgrg/}sgkw{/3432iuh/}sge4g{/sfg/}fs/gerg/}"; - String test4 = "gewgewghwhwh"; - System.out.println(test3.replaceAll("\\{/(.+?)/}", "")); - System.out.println(test3.replaceAll("\\{/(.+?)/\\}", "")); - System.out.println(test4.replaceAll("\\{/(.+?)/}", "")); - System.out.println(test4.replaceAll("\\{/(.+?)/\\}", "")); - System.out.println(JSON.toJSONString(new Long[]{})); - String test5 = "[1, 2, 3]"; - String[] idList = test5.substring(1, test5.length()-1).split(","); - String[] idTrimList = new String[idList.length]; - for (int i = 0; i < idList.length; i++) idTrimList[i] = idList[i].trim(); - System.out.println(JSON.toJSONString(idTrimList)); - String test6 = "[ ]"; - String test7 = ""; - String[] idList2 = test6.substring(1, test6.length()-1).split(","); - System.out.println(Arrays.toString(idList2)); - System.out.println(test6.length()); + String test = "%5B6854303973%2CA04_offline%2C%E6%AD%A3%E5%B8%B8%5D"; + System.out.println(URLDecoder.decode(test)); + String test2 = "{/(sgeg)/}11woier11{/sdg/}11gj{//}23424k11{/234g/}11sg11{/sgg/}"; + System.out.println(test2.replaceAll("\\{/.+?/}", "")); + System.out.println(test2.replaceAll("\\{/.*?/}", "")); } } -- libgit2 0.27.1