Commit 9ad36030 by 苗权威

7.13

parent 11c28e10
......@@ -8,8 +8,10 @@
<outputRelativeToContentRoot value="true" />
<module name="dingdong" />
<module name="jdwhale" />
<module name="open" />
<module name="ruoqi" />
<module name="spirit" />
<module name="third_party_load" />
<module name="xiaoai" />
<module name="xiaodu" />
<module name="xiaoya" />
......@@ -24,9 +26,11 @@
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="dingdong" options="-parameters" />
<module name="jdwhale" options="-parameters" />
<module name="open" options="-parameters" />
<module name="rokid" options="-parameters" />
<module name="ruoqi" options="-parameters" />
<module name="spirit" options="-parameters -extdirs /usr/local/intellij/workplace/smartbox/spirit/src/main/resources/lib" />
<module name="spirit" options="-parameters -extdirs $PROJECT_DIR$/spirit/src/main/resources/lib" />
<module name="third_party_load" options="-parameters" />
<module name="xiaoai" options="-parameters" />
<module name="xiaodu" options="-parameters" />
<module name="xiaoya" options="-parameters" />
......
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with NO BOM">
<file url="file://$PROJECT_DIR$/RokidBox" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/dingdong" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jdwhale" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/rokid" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/open" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/ruoqi" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/spirit" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/third_party_load" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/xiaoai" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/xiaodu" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/xiaoya" charset="UTF-8" />
......
......@@ -22,6 +22,8 @@
<option value="$PROJECT_DIR$/ruoqi/pom.xml" />
<option value="$PROJECT_DIR$/rokid/pom.xml" />
<option value="$PROJECT_DIR$/jdwhale/pom.xml" />
<option value="$PROJECT_DIR$/open/pom.xml" />
<option value="$PROJECT_DIR$/third_party_load/pom.xml" />
</list>
</option>
</component>
......
......@@ -19,7 +19,7 @@ import org.springframework.web.bind.annotation.*;
public class DingDongController {
@Autowired
private ParseServiceCompromise compromise;
private ParseService parseService;
// @Autowired
// private ParseService parseService;
......@@ -27,6 +27,6 @@ public class DingDongController {
@RequestMapping("/ding")
public @ResponseBody DingDongResponse dingdong(@RequestBody DingDongRequest request) {
//log.info("Request params : "+ request);
return compromise.getResponse(request);
return parseService.getResponse(request);
}
}
......@@ -33,9 +33,9 @@ import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public class ParseService {
private static final ConcurrentHashMap<String, LastResponseTimeAndAudio> REQUEST_TIMESTAMP_INTERVAL= new ConcurrentHashMap<>();
//private static final ConcurrentHashMap<String, LastResponseTimeAndAudio> REQUEST_TIMESTAMP_INTERVAL= new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, Integer> SESSION_ID_WITH_REPEAT_COUNT= new ConcurrentHashMap<>();
//private static final ConcurrentHashMap<String, Integer> SESSION_ID_WITH_REPEAT_COUNT= new ConcurrentHashMap<>();
public DingDongResponse getResponse(DingDongRequest request) {
String userId = null;
......@@ -56,42 +56,43 @@ public class ParseService {
if ("NOTICE".equals(request.getStatus())) {
DingDongResponse noticeResponse = dealWithNoticeStatus(request);
Integer removedRepeatCount = SESSION_ID_WITH_REPEAT_COUNT.remove(userId);
if (removedRepeatCount != null) {
log.info("删除之前的重复次数:"+removedRepeatCount);
}
// Integer removedRepeatCount = SESSION_ID_WITH_REPEAT_COUNT.remove(userId);
// if (removedRepeatCount != null) {
// log.info("删除之前的重复次数:"+removedRepeatCount);
// }
return noticeResponse;
}else if ("END".equals(request.getStatus())) {
DingDongResponse endResponse = dealWithEndStatus(request);
Integer removedRepeatCount = SESSION_ID_WITH_REPEAT_COUNT.remove(userId);
if (removedRepeatCount != null) {
log.info("删除之前的重复次数:"+removedRepeatCount);
}
// Integer removedRepeatCount = SESSION_ID_WITH_REPEAT_COUNT.remove(userId);
// if (removedRepeatCount != null) {
// log.info("删除之前的重复次数:"+removedRepeatCount);
// }
return endResponse;
}
String userWord = request.getInput_text();
log.info("本次传来的话:"+userWord);
String requestVersion = request.getVersionid();
String requestSequence = request.getSequence();
LastResponseTimeAndAudio lastResponseContent = REQUEST_TIMESTAMP_INTERVAL.get(userId);
if (lastResponseContent != null && request.getTimestamp() <= lastResponseContent.getTimeStamp() + 5000) {
Integer previousCount = SESSION_ID_WITH_REPEAT_COUNT.putIfAbsent(userId, 0);
if (previousCount == null || previousCount < 2) {
int currentCount = previousCount == null ? 1 : previousCount+1;
log.info("两次请求过于短暂,可能是叮咚识别了自己的话,播放前一次的语音,重复次数: "+ currentCount);
SESSION_ID_WITH_REPEAT_COUNT.put(userId, currentCount);
if (lastResponseContent.getUrl() == null) {
return buildErrorResponse(requestVersion, requestSequence, userId);
}else {
DingDongResponse response = buildResponse(requestVersion, requestSequence, userId);
response.getDirective().getDirective_items().get(0).setContent(lastResponseContent.getUrl());
return response;
}
}
log.info("重复次数超过两次,不再重复");
}
// LastResponseTimeAndAudio lastResponseContent = REQUEST_TIMESTAMP_INTERVAL.get(userId);
// if (lastResponseContent != null && request.getTimestamp() <= lastResponseContent.getTimeStamp() + 5000) {
// Integer previousCount = SESSION_ID_WITH_REPEAT_COUNT.putIfAbsent(userId, 0);
// if (previousCount == null || previousCount < 2) {
// int currentCount = previousCount == null ? 1 : previousCount+1;
// log.info("两次请求过于短暂,可能是叮咚识别了自己的话,播放前一次的语音,重复次数: "+ currentCount);
// SESSION_ID_WITH_REPEAT_COUNT.put(userId, currentCount);
// if (lastResponseContent.getUrl() == null) {
// return buildErrorResponse(requestVersion, requestSequence, userId);
// }else {
// DingDongResponse response = buildResponse(requestVersion, requestSequence, userId);
// response.getDirective().getDirective_items().get(0).setContent(lastResponseContent.getUrl());
// return response;
// }
// }
// log.info("重复次数超过两次,不再重复");
// }
// slots={focus=Story}
// if (request.getSlots() == null || request.getSlots().size() == 1) {
......@@ -114,19 +115,19 @@ public class ParseService {
// }
if (userWord == null) {
Integer removedRepeatCount = SESSION_ID_WITH_REPEAT_COUNT.remove(userId);
if (removedRepeatCount != null) {
log.info("删除之前的重复次数:"+removedRepeatCount);
}
// Integer removedRepeatCount = SESSION_ID_WITH_REPEAT_COUNT.remove(userId);
// if (removedRepeatCount != null) {
// log.info("删除之前的重复次数:"+removedRepeatCount);
// }
return buildErrorResponse(requestVersion, requestSequence, userId);
}
DingDongResponse response = requestQiWuInterface(userId, userWord, requestVersion, requestSequence);
log.info("RESPONSE : "+response);
Integer removedRepeatCount = SESSION_ID_WITH_REPEAT_COUNT.remove(userId);
if (removedRepeatCount != null) {
log.info("删除之前的重复次数:"+removedRepeatCount);
}
// Integer removedRepeatCount = SESSION_ID_WITH_REPEAT_COUNT.remove(userId);
// if (removedRepeatCount != null) {
// log.info("删除之前的重复次数:"+removedRepeatCount);
// }
return response;
}
......@@ -175,8 +176,8 @@ public class ParseService {
private DingDongResponse addUrlAndTextToResponse(String audioUrl, String text, String version, String sequence, String userId) {
DingDongResponse response = buildResponse(version, sequence, userId);
response.getDirective().getDirective_items().get(0).setContent(audioUrl);
response.getDirective().getDirective_items().get(0).setContent(text);
REQUEST_TIMESTAMP_INTERVAL.get(userId).setUrl(audioUrl);
//response.getDirective().getDirective_items().get(0).setContent(text);
//REQUEST_TIMESTAMP_INTERVAL.get(userId).setUrl(audioUrl);
return response;
}
......@@ -185,13 +186,13 @@ public class ParseService {
response.setVersionid(versionId);
response.setIs_end(false);
LastResponseTimeAndAudio responseContent = REQUEST_TIMESTAMP_INTERVAL.get(userId);
if (responseContent == null) {
responseContent = new LastResponseTimeAndAudio();
REQUEST_TIMESTAMP_INTERVAL.put(userId, responseContent);
}
// LastResponseTimeAndAudio responseContent = REQUEST_TIMESTAMP_INTERVAL.get(userId);
// if (responseContent == null) {
// responseContent = new LastResponseTimeAndAudio();
// REQUEST_TIMESTAMP_INTERVAL.put(userId, responseContent);
// }
Long timeMillis = System.currentTimeMillis();
responseContent.setTimeStamp(timeMillis);
//responseContent.setTimeStamp(timeMillis);
response.setTimestamp(timeMillis);
response.setSequence(sequence);
......@@ -245,7 +246,7 @@ public class ParseService {
}
DingDongResponse response = buildErrorResponse(request.getVersionid(), request.getSequence(), request.getUser().getUser_id());
response.getDirective().getDirective_items().get(0).setContent("我们的作品库在不断扩充,欢迎下次再来玩");
log.info("退出前删除缓存,缓存删除结果:"+(REQUEST_TIMESTAMP_INTERVAL.remove(request.getUser().getUser_id()) != null));
//log.info("退出前删除缓存,缓存删除结果:"+(REQUEST_TIMESTAMP_INTERVAL.remove(request.getUser().getUser_id()) != null));
return response;
}
}
......@@ -26,6 +26,8 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 由于叮咚在播放音频或tts过程中不会关麦,导致其将自身的声音识别为用户的话,以下尝试从几方面来解决这一问题:
......@@ -44,6 +46,13 @@ public class ParseServiceCompromise {
private final static ConcurrentHashMap<String, Holder> USER_LAST_ALL_WORD_AudioUrl = new ConcurrentHashMap<>();
private static final ScheduledThreadPoolExecutor scheduled;
static {
scheduled = new ScheduledThreadPoolExecutor(1);
scheduled.scheduleAtFixedRate(USER_LAST_ALL_WORD_AudioUrl::clear, 2, 2, TimeUnit.MINUTES);
}
/**
* 获取响应
* @param request 请求信息
......
......@@ -60,6 +60,12 @@
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jd.custom/custom-skill-sdk -->
<dependency>
<groupId>com.jd.custom</groupId>
<artifactId>custom-skill-sdk</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
......
package ai.qiwu.mqw.jdwhale.common;
import com.jd.custom.skill.sdk.entity.response.SkillResponse;
import com.jd.custom.skill.sdk.entity.response.SkillResponseDetails;
import com.jd.custom.skill.sdk.entity.response.SkillResponseOutput;
import com.jd.custom.skill.sdk.entity.response.directive.audio.AudioDirective;
import com.jd.custom.skill.sdk.entity.response.directive.audio.AudioStream;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* @author 苗权威
* @dateTime 19-7-8 下午5:11
*/
@Slf4j
public class BuildResponse {
public static SkillResponse getAudioResponse(String audioUrl) {
AudioStream stream = AudioStream.builder()
.url(audioUrl)
.token(getToken(audioUrl))
.build();
AudioDirective directive = AudioDirective.builder()
.type("AudioPlayer.Play")
.playBehavior("REPLACE_ALL")
.audioStream(stream)
.build();
List directives = new ArrayList<>();
directives.add(directive);
return SkillResponse.builder()
.shouldEndSession(true)
.directives(directives)
.build();
}
public static SkillResponse getTextResponse(String text) {
return SkillResponse.builder()
.shouldEndSession(false)
.response(SkillResponseDetails.builder()
.output(SkillResponseOutput.builder()
.text(text)
.build())
.build())
.build();
}
private static String getToken(String audioUrl) {
int lastEqual = audioUrl.lastIndexOf("=");
int lastSpot = audioUrl.indexOf(".", lastEqual);
String token;
try {
token = audioUrl.substring(lastEqual, lastSpot);
} catch (Exception e) {
log.info(Constants.ERROR_MSG.CUT_TOKEN_ERROR);
token = String.valueOf(new Random(47).nextLong());
}
return token;
}
}
......@@ -9,4 +9,22 @@ public interface Constants {
String SERVICE_NAME = "DINGDONG";
String CANCEL_INTENT = "Alpha.CancelIntent";
String HELP_INTENT = "Alpha.HelpIntent";
String DEFAULT_INTENT = "Alpha.DefaultIntent";
String WELCOME_MSG = "欢迎来到互动天地,请说推荐作品";
String EMPTY_AUDIO_RESPONSE = "抱歉我没听清,请再说一遍吧";
String END_BYE = "欢迎下次再来玩";
String CONTENT_TYPE = "application/json;charset=utf-8";
String AUDIO = "audio";
String TEXT = "text";
interface ERROR_MSG {
String CLOSE_CON_FAILED = "关闭与终端的连接出错";
String CUT_TOKEN_ERROR = "截取audio获取token时出错";
String REQUEST_TERMINATE_IOEX = "请求终端出错";
}
interface MY_INTENT {
String MY_HELP_INTENT = "ToHelp";
}
}
......@@ -2,15 +2,16 @@ package ai.qiwu.mqw.jdwhale.controller;
import ai.qiwu.mqw.jdwhale.model.RequestModel.DingDongRequest;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.DingDongResponse;
import ai.qiwu.mqw.jdwhale.service.ParseServiceUseSDK;
import ai.qiwu.mqw.jdwhale.service.ParseServiceWithoutLRU;
import com.alibaba.fastjson.JSON;
import com.jd.custom.skill.sdk.entity.request.SkillData;
import com.jd.custom.skill.sdk.entity.response.SkillResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
/**
* @author 苗权威
......@@ -19,13 +20,26 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class DingDongController {
@Autowired
private ParseServiceWithoutLRU serviceWithoutLRU;
private ParseServiceUseSDK parseService;
@RequestMapping("/dingdong")
public @ResponseBody
DingDongResponse dingdong(@RequestBody DingDongRequest request) {
//log.info("Request params: "+request);
return serviceWithoutLRU.getResponse(request);
@PostMapping(value = "/dingdong", produces = {"application/json;charset=UTF-8"})
public SkillResponse dingdong(@RequestBody String requestBody) {
log.info("请求信息:{}",requestBody);
SkillData data = JSON.parseObject(requestBody, SkillData.class);
SkillResponse response = parseService.handle(data);
log.info("返回信息:{}", JSON.toJSONString(response));
return response;
}
// @Autowired
// private ParseServiceWithoutLRU serviceWithoutLRU;
//
// @RequestMapping("/dingdong")
// public @ResponseBody
// DingDongResponse dingdong(@RequestBody DingDongRequest request) {
// log.info("Request params: "+request);
// return serviceWithoutLRU.getResponse(request);
// }
}
package ai.qiwu.mqw.jdwhale.service;
import ai.qiwu.mqw.jdwhale.common.BuildResponse;
import ai.qiwu.mqw.jdwhale.common.Constants;
import ai.qiwu.mqw.jdwhale.common.Constants.ERROR_MSG;
import ai.qiwu.mqw.jdwhale.common.Constants.MY_INTENT;
import com.jd.custom.skill.sdk.RequestHandler;
import com.jd.custom.skill.sdk.entity.request.SkillData;
import com.jd.custom.skill.sdk.entity.response.SkillResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
/**
* @author 苗权威
* @dateTime 19-7-8 下午3:54
*/
@Service("parseService")
@Slf4j
public class ParseServiceUseSDK extends RequestHandler {
@Override
public SkillResponse onLaunchRequest(SkillData skillData) {
return BuildResponse.getTextResponse(Constants.WELCOME_MSG);
}
@Override
public SkillResponse onIntentRequest(SkillData skillData) {
String intentName = skillData.getRequest().getIntent().getName();
switch (intentName) {
case (MY_INTENT.MY_HELP_INTENT) : return defaultResponse(skillData);
case (Constants.DEFAULT_INTENT) : return defaultResponse(skillData);
case (Constants.CANCEL_INTENT) : return onCancelIntent(skillData);
case (Constants.HELP_INTENT) : return onHelpIntent(skillData);
default: {
log.info("未知的意图");
return BuildResponse.getTextResponse(Constants.EMPTY_AUDIO_RESPONSE);
}
}
}
@Override
public SkillResponse onCancelIntent(SkillData skillData) {
String userId = skillData.getSession().getUser().getUserId();
try {
RequestTerminate.requestQiWuInterface(userId, "退出");
} catch (IOException e) {
}
return BuildResponse.getTextResponse(Constants.END_BYE);
}
@Override
public SkillResponse onHelpIntent(SkillData skillData) {
return defaultResponse(skillData);
}
/**
* 缺省意图的处理
* @param skillData
* @return
*/
@Override
public SkillResponse defaultResponse(SkillData skillData) {
String userId = skillData.getSession().getUser().getUserId();
String userWord = skillData.getRequest().getOriginal();
String audioUrl;
try {
audioUrl = RequestTerminate.requestQiWuInterface(userId, userWord);
} catch (IOException e) {
log.info(ERROR_MSG.REQUEST_TERMINATE_IOEX);
return BuildResponse.getTextResponse(Constants.EMPTY_AUDIO_RESPONSE);
}
return BuildResponse.getAudioResponse(audioUrl);
}
// @Override
// public SkillResponse onAudioPlayerPlaybackFinishedRequest(SkillData skillData) {
// return SkillResponse.builder()
// .shouldEndSession(false)
// .build();
// }
@Override
public void onAudioPlayerPlaybackStoppedRequest(SkillData skillData) {
log.info("当前播放被指令或其他请求打断");
}
// @Override
// public SkillResponse onAudioPlayerPlaybackFailedRequest(SkillData skillData) {
// return SkillResponse.builder()
// .shouldEndSession(false)
// .build();
// }
}
......@@ -79,7 +79,8 @@ public class ParseServiceWithoutLRU {
response.getResponse().getOutput().setText("请明确一些说帮或不帮");
return response;
}
DingDongResponse response = buildResponseInTTS();
//DingDongResponse response = buildResponseInTTS();
DingDongResponse response = buildResponseInDirective();
String userWord = request.getOriginal();
requestQiWuInterface(userId, userWord, response);
return response;
......@@ -87,6 +88,7 @@ public class ParseServiceWithoutLRU {
private void dealSessionEndedRequest(String userId) {
log.info("用户 "+userId+" 会话结束");
requestQiWuInterface(userId, "退出", new DingDongResponse());
}
private void requestQiWuInterface(String userId, String userWord, DingDongResponse response) {
......@@ -131,7 +133,7 @@ public class ParseServiceWithoutLRU {
}
private void addUrlAndTextToResponse(String url, String text, DingDongResponse response) {
response.getResponse().getOutput().setText(text);
//response.getResponse().getOutput().setText(text);
response.getDirectives().get(0).getAudioStream().setUrl(url);
}
......
package ai.qiwu.mqw.jdwhale.service;
import ai.qiwu.mqw.jdwhale.common.Constants;
import ai.qiwu.mqw.jdwhale.common.Constants.ERROR_MSG;
import ai.qiwu.mqw.jdwhale.model.ResponseModel.DingDongResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
/**
* @author 苗权威
* @dateTime 19-7-8 下午4:32
*/
@Slf4j
public class RequestTerminate {
static String requestQiWuInterface(String userId, String userWord) throws IOException {
String audioUrl = "";
String textContent = "";
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(Constants.QI_WU_INTERFACE);
HashMap<String, String> params = new HashMap<>();
params.put("user_id", String.valueOf(userId));
params.put("text", userWord);
params.put("access",Constants.SERVICE_NAME);
String paramsJsonFormat = JSON.toJSONString(params);
StringEntity body = new StringEntity(paramsJsonFormat, StandardCharsets.UTF_8);
post.setHeader("Content-Type", Constants.CONTENT_TYPE);
post.setEntity(body);
httpResponse = httpClient.execute(post);
HttpEntity responseBody = httpResponse.getEntity();
if (responseBody != null) {
String responseContent = EntityUtils.toString(responseBody);
log.info("齐悟接口返回: "+ responseContent);
JSONObject responseJsonFormat = JSONObject.parseObject(responseContent);
audioUrl = (String) responseJsonFormat.get(Constants.AUDIO);
textContent = (String) responseJsonFormat.get(Constants.TEXT);
}
} finally {
try {
if (httpClient != null) httpClient.close();
if (httpResponse != null) httpResponse.close();
} catch (IOException e) {
log.info(ERROR_MSG.CLOSE_CON_FAILED);
}
}
return audioUrl;
}
}
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
echo Found %WRAPPER_JAR%
) else (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
echo Finished downloading %WRAPPER_JAR%
)
@REM End of extension
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ai.qiwu.com</groupId>
<artifactId>open</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>open</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11.1</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package ai.qiwu.com.open;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class OpenApplication {
public static void main(String[] args) {
SpringApplication.run(OpenApplication.class, args);
}
}
package ai.qiwu.com.open.common;
public interface OpenConstants {
String token = "miaoquanwei";
String QI_WU_TERMINATE = "http://aliyun-hz1.chewrobot.com:8070/api/chat";
String DEVICE_NAME = "GONGZHONGHAO";
String CONTENT_TYPE = "application/json;charset=utf-8";
String FILE_ROOT = "/usr/springbootdemo/weChatOpen/";
String MP3_SUFFIX = ".mp3";
Long OBSOLETE_TIME = 600000L; // 10 minute
interface ERROR_MSG {
String QIWU_IO_ERROR = "不好意思,请再说一边吧";
String TERMINATE_IO_EXCEPTION = "请求终端接口时发生IO错误";
String HTTP_CONNECTION_CLOSE_EXCEPTION = "关闭与终端接口链接时出错";
String UN_SUIT_TYPE = "不好意思现在只支持文字和语音";
String AUDIO_MODEL = "已切换到语音模式";
String TEXT_MODEL = "已切换到文字模式";
}
interface OP_INTERFACE {
String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd86491950db60c5e&secret=8f41941e85f77142743cf963fc80ad8b";
String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?type=voice&access_token=";
String REFRESH_VIEW = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
}
interface REQUEST_TYPE {
String TEXT = "text";
String VOICE = "voice";
String IMAGE = "image";
String VIDEO = "video";
String SHORTVIDEO = "shortvideo";
String LOCATION = "location";
String LINK = "link";
String EVENT = "event";
interface EVENT_TYPE {
String VIEW = "VIEW";
String CLICK = "CLICK";
}
}
interface EVENT_KEY {
String AUDIO = "audio";
String TEXT = "text";
}
}
package ai.qiwu.com.open.common.encryption;
@SuppressWarnings("serial")
public class AesException extends Exception {
public final static int OK = 0;
public final static int ValidateSignatureError = -40001;
public final static int ParseXmlError = -40002;
public final static int ComputeSignatureError = -40003;
public final static int IllegalAesKey = -40004;
public final static int ValidateAppidError = -40005;
public final static int EncryptAESError = -40006;
public final static int DecryptAESError = -40007;
public final static int IllegalBuffer = -40008;
//public final static int EncodeBase64Error = -40009;
//public final static int DecodeBase64Error = -40010;
//public final static int GenReturnXmlError = -40011;
private int code;
private static String getMessage(int code) {
switch (code) {
case ValidateSignatureError:
return "签名验证错误";
case ParseXmlError:
return "xml解析失败";
case ComputeSignatureError:
return "sha加密生成签名失败";
case IllegalAesKey:
return "SymmetricKey非法";
case ValidateAppidError:
return "appid校验失败";
case EncryptAESError:
return "aes加密失败";
case DecryptAESError:
return "aes解密失败";
case IllegalBuffer:
return "解密后得到的buffer非法";
// case EncodeBase64Error:
// return "base64加密错误";
// case DecodeBase64Error:
// return "base64解密错误";
// case GenReturnXmlError:
// return "xml生成失败";
default:
return null; // cannot be
}
}
public int getCode() {
return code;
}
AesException(int code) {
super(getMessage(code));
this.code = code;
}
}
package ai.qiwu.com.open.common.encryption;
import java.util.ArrayList;
class ByteGroup {
ArrayList<Byte> byteContainer = new ArrayList<Byte>();
public byte[] toBytes() {
byte[] bytes = new byte[byteContainer.size()];
for (int i = 0; i < byteContainer.size(); i++) {
bytes[i] = byteContainer.get(i);
}
return bytes;
}
public ByteGroup addBytes(byte[] bytes) {
for (byte b : bytes) {
byteContainer.add(b);
}
return this;
}
public int size() {
return byteContainer.size();
}
}
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package ai.qiwu.com.open.common.encryption;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* 提供基于PKCS7算法的加解密接口.
*/
class PKCS7Encoder {
static Charset CHARSET = Charset.forName("utf-8");
static int BLOCK_SIZE = 32;
/**
* 获得对明文进行补位填充的字节.
*
* @param count 需要进行填充补位操作的明文字节个数
* @return 补齐用的字节数组
*/
static byte[] encode(int count) {
// 计算需要填充的位数
int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
if (amountToPad == 0) {
amountToPad = BLOCK_SIZE;
}
// 获得补位所用的字符
char padChr = chr(amountToPad);
String tmp = new String();
for (int index = 0; index < amountToPad; index++) {
tmp += padChr;
}
return tmp.getBytes(CHARSET);
}
/**
* 删除解密后明文的补位字符
*
* @param decrypted 解密后的明文
* @return 删除补位字符后的明文
*/
static byte[] decode(byte[] decrypted) {
int pad = (int) decrypted[decrypted.length - 1];
if (pad < 1 || pad > 32) {
pad = 0;
}
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
}
/**
* 将数字转化成ASCII码对应的字符,用于对明文进行补码
*
* @param a 需要转化的数字
* @return 转化得到的字符
*/
static char chr(int a) {
byte target = (byte) (a & 0xFF);
return (char) target;
}
}
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package ai.qiwu.com.open.common.encryption;
import java.security.MessageDigest;
import java.util.Arrays;
/**
* SHA1 class
*
* 计算公众平台的消息签名接口.
*/
class SHA1 {
/**
* 用SHA1算法生成安全签名
* @param token 票据
* @param timestamp 时间戳
* @param nonce 随机字符串
* @param encrypt 密文
* @return 安全签名
* @throws AesException
*/
public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException
{
try {
String[] array = new String[] { token, timestamp, nonce, encrypt };
StringBuffer sb = new StringBuffer();
// 字符串排序
Arrays.sort(array);
for (int i = 0; i < 4; i++) {
sb.append(array[i]);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.ComputeSignatureError);
}
}
}
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package ai.qiwu.com.open.common.encryption;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* XMLParse class
*
* 提供提取消息格式中的密文及生成回复消息格式的接口.
*/
class XMLParse {
/**
* 提取出xml数据包中的加密消息
* @param xmltext 待提取的xml字符串
* @return 提取出的加密消息字符串
* @throws AesException
*/
public static Object[] extract(String xmltext) throws AesException {
Object[] result = new Object[3];
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader sr = new StringReader(xmltext);
InputSource is = new InputSource(sr);
Document document = db.parse(is);
Element root = document.getDocumentElement();
NodeList nodelist1 = root.getElementsByTagName("Encrypt");
NodeList nodelist2 = root.getElementsByTagName("ToUserName");
result[0] = 0;
result[1] = nodelist1.item(0).getTextContent();
result[2] = nodelist2.item(0).getTextContent();
return result;
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.ParseXmlError);
}
}
/**
* 生成xml消息
* @param encrypt 加密后的消息密文
* @param signature 安全签名
* @param timestamp 时间戳
* @param nonce 随机字符串
* @return 生成的xml字符串
*/
public static String generate(String encrypt, String signature, String timestamp, String nonce) {
String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
return String.format(format, encrypt, signature, timestamp, nonce);
}
}
package ai.qiwu.com.open.common.error;
import com.alibaba.fastjson.JSON;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.StringUtils;
/**
* @author 苗权威
* @dateTime 19-7-9 下午1:29
*/
@Getter
@Setter
public class OpenError {
/**
* 返回的错误信息,之后我们会利用错误码到全局里去查找其中文解释
*/
private String errmsg;
/**
* 返回的错误码
*/
private int errcode;
/**
* 保存原始的错误信息
*/
private String errorMsgOrigin;
public static OpenError fromJson(String json) {
final OpenError openError = JSON.parseObject(json, OpenError.class);
if (!StringUtils.isEmpty(openError.getErrmsg())) {
openError.setErrorMsgOrigin(openError.getErrmsg());
}
String msg = WholeErrorMsgEnum.findMsgByCode(openError.getErrcode());
if (msg != null) openError.setErrmsg(msg);
return openError;
}
@Override
public String toString() {
return "错误码 Code: "+ errcode + ", Msg: "+ errmsg;
}
}
package ai.qiwu.com.open.common.error;
/**
* @author 苗权威
* @dateTime 19-7-9 下午1:49
*/
public class OpenErrorException extends Exception {
private OpenError openError;
public OpenErrorException(OpenError openError) {
super(openError.toString());
this.openError = openError;
}
public OpenError getOpenError() {
return openError;
}
}
package ai.qiwu.com.open.common.error.project;
import lombok.Getter;
/**
* @author 苗权威
* @dateTime 19-7-9 下午3:29
*/
@Getter
public class ActiveGetTokenFailed extends Exception {
private int errorCode;
private String errorMsg;
public ActiveGetTokenFailed(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
public ActiveGetTokenFailed(int errorCode, String errorMsg) {
super(errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
}
package ai.qiwu.com.open.common.error.project;
import lombok.Getter;
/**
* @author 苗权威
* @dateTime 19-7-9 下午2:00
*/
@Getter
public class CreateDirectoryFailed extends Exception {
private String errorMsg;
private int errorCode;
public CreateDirectoryFailed(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
}
package ai.qiwu.com.open.common.error.project;
import lombok.Getter;
/**
* @author 苗权威
* @dateTime 19-7-9 下午2:08
*/
@Getter
public class DownloadFromTerminateFailed extends Exception {
private int errorCode;
private String errorMsg;
public DownloadFromTerminateFailed(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
}
package ai.qiwu.com.open.common.error.project;
/**
* @author 苗权威
* @dateTime 19-7-10 下午1:30
*/
public class ParseRequestXmlDataFailed extends Exception {
private int errorCode;
private String errorMsg;
public ParseRequestXmlDataFailed(int errorCode, String errorMsg) {
super(errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public ParseRequestXmlDataFailed(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
}
package ai.qiwu.com.open.common.error.project;
/**
* @author 苗权威
* @dateTime 19-7-9 下午2:52
*/
public class RequestTerminateFailed extends Exception {
private int errorCode;
private String errorMsg;
public RequestTerminateFailed(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
public RequestTerminateFailed(int errorCode, String errorMsg) {
super(errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
}
package ai.qiwu.com.open.common.error.project;
import lombok.Getter;
/**
* @author 苗权威
* @dateTime 19-7-9 下午4:29
*/
@Getter
public class UploadAudioFileFailed extends Exception {
private int errorCode;
private String errorMsg;
public UploadAudioFileFailed(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
public UploadAudioFileFailed(int errorCode, String errorMsg) {
super(errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
}
package ai.qiwu.com.open.common.utils;
import ai.qiwu.com.open.pojo.request.AudioRequestInfo;
import ai.qiwu.com.open.pojo.request.RequestInfo;
import ai.qiwu.com.open.pojo.request.TextRequestInfo;
import ai.qiwu.com.open.pojo.response.AudioResponse;
import ai.qiwu.com.open.pojo.response.Response;
import ai.qiwu.com.open.pojo.response.TextResponse;
import ai.qiwu.com.open.pojo.response.Voice;
import ai.qiwu.com.open.service.OpenService;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-7-9 下午2:23
*/
public class BuildRequestResponse {
private static void buildRequestInfo(RequestInfo requestInfo, Map<String, String> msgMap) {
requestInfo.setToUserName(msgMap.get("ToUserName"));
requestInfo.setFromUserName(msgMap.get("FromUserName"));
requestInfo.setCreateTime(msgMap.get("CreateTime"));
requestInfo.setMsgType(msgMap.get("MsgType"));
requestInfo.setMsgID(msgMap.get("MsgID"));
}
public static AudioRequestInfo buildAudioRequestInfo(Map<String, String> msgMap) {
AudioRequestInfo audio = new AudioRequestInfo();
buildRequestInfo(audio, msgMap);
audio.setFormat(msgMap.get("Format"));
audio.setMediaID(msgMap.get("MediaID"));
audio.setRecognition(msgMap.get("Recognition"));
return audio;
}
public static TextRequestInfo buildTextRequestInfo(Map<String, String> msgMap) {
TextRequestInfo text = new TextRequestInfo();
buildRequestInfo(text, msgMap);
text.setContent(msgMap.get("Content"));
return text;
}
private static void buildResponse(Response response , String openId, String creator, String msgType) {
String curTime = String.valueOf(System.currentTimeMillis());
OpenService.getOpenidCache().get(openId).setTimeStamp(curTime);
response.setCreateTime(curTime);
response.setFromUserName(creator);
response.setToUserName(openId);
response.setMsgType(msgType);
}
public static AudioResponse buildAudioResponse(String openId, String creator, String mediaId) {
AudioResponse response = new AudioResponse();
buildResponse(response, openId, creator, "voice");
Voice voice = new Voice();
voice.setMediaId(mediaId);
response.setVoice(voice);
return response;
}
public static TextResponse buildTextResponse(String openId, String creator, String content) {
TextResponse response = new TextResponse();
buildResponse(response, openId, creator, "text");
response.setContent(content);
return response;
}
}
package ai.qiwu.com.open.common.utils;
import ai.qiwu.com.open.common.error.project.ParseRequestXmlDataFailed;
import ai.qiwu.com.open.pojo.response.AudioResponse;
import ai.qiwu.com.open.pojo.response.TextResponse;
import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class MessageUtil {
public static Map<String, String> xmlToMap(HttpServletRequest request) throws ParseRequestXmlDataFailed {
Map<String, String> map = new HashMap<>();
SAXReader reader = new SAXReader();
InputStream is = null;
try {
is = request.getInputStream();
Document doc = reader.read(is);
List<Element> elements = doc.getRootElement().elements();
for (Element ele : elements) {
map.put(ele.getName(), ele.getText());
}
} catch (DocumentException | IOException e) {
log.error("解析xml出错,{}",e.toString());
throw new ParseRequestXmlDataFailed("解析xml出错");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.info("关闭ServletRequest流出错");
}
}
}
return map;
}
public static String messageToXml(AudioResponse response) {
XStream xs = new XStream();
xs.alias("xml", response.getClass());
return xs.toXML(response);
}
public static String messageToXml(TextResponse response) {
XStream xs = new XStream();
xs.alias("xml", response.getClass());
return xs.toXML(response);
}
}
package ai.qiwu.com.open.common.utils;
import ai.qiwu.com.open.common.OpenConstants;
import ai.qiwu.com.open.common.OpenConstants.OP_INTERFACE;
import ai.qiwu.com.open.common.error.OpenError;
import ai.qiwu.com.open.common.error.OpenErrorException;
import ai.qiwu.com.open.common.error.project.ActiveGetTokenFailed;
import ai.qiwu.com.open.pojo.AccessToken;
import ai.qiwu.com.open.pojo.AccessTokenResponse;
import ai.qiwu.com.open.pojo.UserCacheHolder;
import ai.qiwu.com.open.service.OpenService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author 苗权威
* @dateTime 19-7-9 上午9:43
*/
@Slf4j
@Component
public class Schedule {
private static final AccessToken ACCESS_TOKEN_HOLDER = new AccessToken();
@Scheduled(fixedDelay = 7100000, initialDelay = 7100000)
public void getAccessToken() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(OP_INTERFACE.ACCESS_TOKEN_URL)
.build();
try {
Response response = client.newCall(request).execute();
AccessTokenResponse accessTokenResponse = JSON.parseObject(response.body().string(), AccessTokenResponse.class);
String accessToken = accessTokenResponse.getAccess_token();
if (accessToken == null) {
log.info("获取Token失败,{}", accessTokenResponse);
}else {
log.info("获取Token成功,{}", accessToken);
ACCESS_TOKEN_HOLDER.setAccessToken(accessToken);
}
} catch (IOException e) {
log.error("定时任务获取ACCESS_TOKEN失败");
}
}
@Scheduled(fixedDelay = 120000, initialDelay = 120000)
public void deleteObsoleteFile() {
long obsoleteBound = System.currentTimeMillis() - OpenConstants.OBSOLETE_TIME;
ConcurrentHashMap<String, UserCacheHolder> timeMap = OpenService.getOpenidCache();
List<String> obsoleteOpenId = new ArrayList<>();
Iterator<Map.Entry<String, UserCacheHolder>> iterator = timeMap.entrySet().iterator();
for (; iterator.hasNext(); ) {
Map.Entry<String, UserCacheHolder> entry = iterator.next();
if (Long.parseLong(entry.getValue().getTimeStamp()) <= obsoleteBound) {
String openId = entry.getKey();
obsoleteOpenId.add(openId);
iterator.remove();
}
}
if (!obsoleteOpenId.isEmpty()) {
log.info("清道夫来也,检测到有用户超过时限未玩");
}
for (String openId: obsoleteOpenId) {
String filePath = new StringBuilder(OpenConstants.FILE_ROOT).append(openId).append(OpenConstants.MP3_SUFFIX).toString();
File file = new File(filePath);
if (file.exists() && file.isFile()) {
file.delete();
log.info("清扫用户:{}的文件成功", openId);
}
}
}
private static String getAccessTokenActive() throws IOException, OpenErrorException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(OpenConstants.OP_INTERFACE.ACCESS_TOKEN_URL)
.build();
String accessToken = null;
try {
okhttp3.Response response = client.newCall(request).execute();
String responseJson = response.body().string();
log.info("主动请求Token返回:{}",responseJson);
AccessTokenResponse accessTokenResponse = JSON.parseObject(responseJson, AccessTokenResponse.class);
accessToken = accessTokenResponse.getAccess_token();
if (accessToken == null) {
throw new OpenErrorException(OpenError.fromJson(responseJson));
}else {
log.info("主动获取Token成功,{}", accessToken);
Schedule.ACCESS_TOKEN_HOLDER.setAccessToken(accessToken);
}
} catch (IOException e) {
log.error("主动获取Token失败,{}", e.toString());
throw e;
}
return accessToken;
}
public static String requireAccessToken() throws ActiveGetTokenFailed {
String accessToken = Schedule.ACCESS_TOKEN_HOLDER.getAccessToken();
if (accessToken == null) {
log.info("定时任务获取Token出现错误,主动获取");
try {
accessToken = Schedule.getAccessTokenActive();
} catch (IOException e) {
throw new ActiveGetTokenFailed("主动获取Access_Token失败");
} catch (OpenErrorException e) {
log.info(e.getOpenError().getErrmsg());
throw new ActiveGetTokenFailed("主动获取Access_Token失败");
}
}
return accessToken;
}
}
package ai.qiwu.com.open.common.utils;
import ai.qiwu.com.open.common.OpenConstants;
import ai.qiwu.com.open.common.error.OpenError;
import ai.qiwu.com.open.common.error.OpenErrorException;
import ai.qiwu.com.open.common.error.project.CreateDirectoryFailed;
import ai.qiwu.com.open.common.error.project.DownloadFromTerminateFailed;
import ai.qiwu.com.open.pojo.TemporaryResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.BufferedSink;
import okio.Okio;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class UpDownloadAudion {
private static final Pattern PATTERN = Pattern.compile(".*filename=(.*).mp3.*");
public static File downloadAudio(String audioUrl, String openId) throws DownloadFromTerminateFailed, IOException, CreateDirectoryFailed {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(audioUrl).get().build();
Response response = client.newCall(request).execute();
String contentType = response.header("Content-Type");
if (contentType != null && contentType.startsWith("application/json")) {
// application/json; encoding=utf-8 下载媒体文件出错
log.error("下载mp3文件出错");
throw new DownloadFromTerminateFailed("下载mp3文件出错");
}
File file = createCustomerFile(openId);
try (BufferedSink sink = Okio.buffer(Okio.sink(file));ResponseBody body = response.body()) {
sink.writeAll(body.source());
}
return file;
}
public static String uploadVoice(String uri, File file) throws IOException, OpenErrorException {
OkHttpClient client = new OkHttpClient();
RequestBody body = new MultipartBody.Builder()
.setType(MediaType.parse("multipart/form-data"))
.addFormDataPart("media", file.getName(),
RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build();
Request request = new Request.Builder().url(uri).post(body).build();
Response response = client.newCall(request).execute();
try (ResponseBody responseBody = response.body()){
String responseContent = responseBody.string();
log.info("临时文件上传接口返回:"+responseContent);
OpenError error = JSON.parseObject(responseContent, OpenError.class);
if (error.getErrcode() != 0) {
throw new OpenErrorException(OpenError.fromJson(responseContent));
}
TemporaryResponse result = JSON.parseObject(responseContent, TemporaryResponse.class);
return result.getMedia_id();
}
}
private static File createCustomerFile(String openId) throws CreateDirectoryFailed {
String filePath = new StringBuilder(OpenConstants.FILE_ROOT).append(openId).append(".mp3").toString();
File file = new File(filePath);
boolean createNewFileSuccess = false;
if (!(file.exists() && file.isFile())) {
try {
createNewFileSuccess = file.createNewFile();
} catch (IOException e) {
log.error("新创建openID.mps失败,{}",e.toString());
throw new CreateDirectoryFailed("新创建openID.mps失败");
}
if (!createNewFileSuccess) {
log.error("新创建openID.mps失败");
throw new CreateDirectoryFailed("新创建openID.mps失败");
}
}
return file;
}
private static File createFile(String audioUrl, String openId) {
Matcher matcher = PATTERN.matcher(audioUrl);
String audioName;
if (matcher.matches()) {
audioName = matcher.group(1);
} else {
audioName = String.valueOf(new Random(47).nextInt());
}
StringBuilder path = new StringBuilder();
String directoryPath = path.append(OpenConstants.FILE_ROOT).append(openId).append("/").toString();
File directory = new File(directoryPath);
boolean isDirectoryCreateSuccess = false;
if (!directory.exists()) {
isDirectoryCreateSuccess = directory.mkdirs();
}
File file = null;
try {
file = File.createTempFile(audioName, ".mp3", directory);
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
public static void deleteFile(File file) {
if (file.exists() && file.isFile()) {
file.delete();
}
}
}
package ai.qiwu.com.open.controller;
import ai.qiwu.com.open.common.OpenConstants;
import ai.qiwu.com.open.service.OpenService;
import ai.qiwu.com.open.service.ParseRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
@RestController
@Slf4j
public class OpenController {
private final HttpServletRequest request;
private final OpenService openService;
private final ParseRequest parseRequest;
@Autowired
public OpenController(HttpServletRequest request,ParseRequest parseRequest, OpenService openService) {
this.request = request;
this.parseRequest = parseRequest;
this.openService = openService;
}
@PostMapping("/open")
public String verify() {
String xmlResponse = openService.dispatch(request, parseRequest);
log.info("XML:{}", xmlResponse);
return xmlResponse;
}
@GetMapping("/open")
public String verify(String timestamp, String nonce, String signature, String echostr) {
String[] arr = new String[] {timestamp, nonce, OpenConstants.token};
Arrays.sort(arr);
StringBuilder builder = new StringBuilder();
for (String str : arr) {
builder.append(str);
}
String str = builder.toString();
StringBuilder hexStr = new StringBuilder();
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
String shaHex;
for (byte bt : digest) {
shaHex = Integer.toHexString(bt & 0xFF);
if (shaHex.length() < 2) {
hexStr.append(0);
}
hexStr.append(shaHex);
}
} catch (NoSuchAlgorithmException e) {
log.info("SHA1加密出错"+e.toString());
}
String verify = hexStr.toString();
if (verify.equals(signature)) {
log.info("验证成功");
}else {
log.info("验证失败,传来的signature:{},计算得到的是:{}",signature, verify);
}
return echostr;
}
}
package ai.qiwu.com.open.front;
import ai.qiwu.com.open.common.OpenConstants.OP_INTERFACE;
import ai.qiwu.com.open.common.error.OpenError;
import ai.qiwu.com.open.common.error.OpenErrorException;
import ai.qiwu.com.open.common.error.project.ActiveGetTokenFailed;
import ai.qiwu.com.open.common.utils.Schedule;
import ai.qiwu.com.open.front.assembly.Element;
import ai.qiwu.com.open.front.assembly.Root;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author 苗权威
* @dateTime 19-7-9 下午8:04
*/
@Slf4j
@Component
public class RefreshView implements InitializingBean {
private void refreshView() throws ActiveGetTokenFailed, IOException, OpenErrorException {
Root button = new Root();
buildView(button, "click", "返回语音", "audio");
buildView(button, "click", "返回文字", "text");
String viewJson = JSON.toJSONString(button);
String token = Schedule.requireAccessToken();
String refreshViewUrl = OP_INTERFACE.REFRESH_VIEW+token;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(refreshViewUrl)
.post(RequestBody.create(
MediaType.parse("application/json; charset=utf-8"), viewJson))
.build();
Response response = client.newCall(request).execute();
try (ResponseBody body = response.body()){
String responseJson = body.string();
OpenError openError = JSON.parseObject(responseJson, OpenError.class);
if (openError.getErrcode() != 0) {
throw new OpenErrorException(OpenError.fromJson(responseJson));
}
}
}
private static void buildView(Root button,String type, String name, String key) {
button.getButton().add(new Element(type, name, key));
}
@Override
public void afterPropertiesSet() throws Exception {
try {
refreshView();
log.info("页面刷新成功");
} catch (ActiveGetTokenFailed activeGetTokenFailed) {
log.error("刷新页面时获取Token失败");
} catch (IOException e) {
log.error("刷新页面时OkHttp发生错误,{}",e.toString());
} catch (OpenErrorException e) {
log.error("刷新页面失败,接口返回的错误信息:{}", e.getOpenError().getErrmsg());
}
}
}
package ai.qiwu.com.open.front.assembly;
import lombok.Data;
import lombok.Getter;
/**
* @author 苗权威
* @dateTime 19-7-9 下午7:57
*/
@Getter
public class Element {
private String type;
private String name;
private String key;
public Element(String type, String name, String key) {
this.type = type;
this.name = name;
this.key = key;
}
}
package ai.qiwu.com.open.front.assembly;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-7-9 下午7:58
*/
@Getter
@Setter
public class Root {
private List<Element> button = new ArrayList<>();
}
package ai.qiwu.com.open.pojo;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class AccessToken {
private volatile String accessToken;
}
package ai.qiwu.com.open.pojo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class AccessTokenResponse {
private String access_token;
private String expires_in;
private String errcode;
private String errmsg;
}
package ai.qiwu.com.open.pojo;
import lombok.Getter;
import org.springframework.stereotype.Service;
@Getter
@Service
public class GetRequestVerify {
private String signature;
private String timestamp;
private String echostr;
private String nonce;
}
package ai.qiwu.com.open.pojo;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-7-8 下午8:10
*/
@Getter
@Setter
public class TemporaryResponse {
private String media_id;
private String type;
private String created_at;
}
package ai.qiwu.com.open.pojo;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-7-10 下午4:31
*/
@Getter
@Setter
public class UserCacheHolder {
/**
* true代表语音,false代表文字,默认语音
*/
private volatile Boolean audioOrText = true;
private volatile String timeStamp;
private volatile String repeatId;
}
package ai.qiwu.com.open.pojo.qiwu;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-7-10 下午2:29
*/
@Getter
@Setter
public class QiWuRequest {
private String user_id;
private String text;
private String access;
}
package ai.qiwu.com.open.pojo.qiwu;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class QiWuResponse {
private String audio;
private String text;
}
package ai.qiwu.com.open.pojo.request;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class AudioRequestInfo extends RequestInfo{
private String MediaID;
private String Format;
private String Recognition;
}
package ai.qiwu.com.open.pojo.request;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RequestInfo {
protected String ToUserName;
protected String FromUserName;
protected String CreateTime;
protected String MsgType;
protected String MsgID;
}
package ai.qiwu.com.open.pojo.request;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class TextRequestInfo extends RequestInfo {
private String Content;
}
package ai.qiwu.com.open.pojo.response;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class AudioResponse extends Response{
private Voice Voice;
}
package ai.qiwu.com.open.pojo.response;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Response {
protected String ToUserName;
protected String FromUserName;
protected String CreateTime;
protected String MsgType;
}
package ai.qiwu.com.open.pojo.response;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-7-9 下午2:25
*/
@Getter
@Setter
public class TextResponse extends Response{
private String Content;
}
package ai.qiwu.com.open.pojo.response;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-7-9 上午9:35
*/
@Getter
@Setter
@ToString
public class Voice {
private String MediaId;
}
package ai.qiwu.com.open.service;
import ai.qiwu.com.open.common.OpenConstants;
import ai.qiwu.com.open.common.OpenConstants.EVENT_KEY;
import ai.qiwu.com.open.common.OpenConstants.REQUEST_TYPE;
import ai.qiwu.com.open.common.OpenConstants.REQUEST_TYPE.EVENT_TYPE;
import ai.qiwu.com.open.common.error.project.ParseRequestXmlDataFailed;
import ai.qiwu.com.open.common.utils.MessageUtil;
import ai.qiwu.com.open.pojo.UserCacheHolder;
import ai.qiwu.com.open.pojo.qiwu.QiWuResponse;
import ai.qiwu.com.open.pojo.response.AudioResponse;
import ai.qiwu.com.open.pojo.response.TextResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static ai.qiwu.com.open.common.utils.BuildRequestResponse.buildTextResponse;
@Service
@Slf4j
public class OpenService {
private static final ConcurrentHashMap<String, UserCacheHolder> OPENID_CACHE = new ConcurrentHashMap<>();
public String dispatch(HttpServletRequest request, ParseRequest parseRequest) {
Map<String, String> msgMap = null;
try {
msgMap = MessageUtil.xmlToMap(request);
} catch (ParseRequestXmlDataFailed parseRequestXmlDataFailed) {
return "success";
}
String userId = msgMap.get("FromUserName");
UserCacheHolder holder = getHolder(userId);
if (doesThisRequestRepeat(getMsgID(msgMap, userId), holder)) return "success";
return dispatchByType(parseRequest, msgMap, holder);
}
private String dispatchByType(ParseRequest parseRequest, Map<String, String> msgMap, UserCacheHolder holder) {
String type = msgMap.get("MsgType");
String userId = msgMap.get("FromUserName");
String creator = msgMap.get("ToUserName");
boolean chooseAudio = holder.getAudioOrText();
String userWord;
switch (type) {
case REQUEST_TYPE.TEXT : {
userWord = msgMap.get("Content");
QiWuResponse terminateResponse;
try {
terminateResponse = RequestQiWu.requestQiWuOkHTTP3(userId, userWord);
} catch (Exception e) {
log.error("请求齐悟接口出错{}", e.toString());
return crateCustomTextResponse(userId, creator, OpenConstants.ERROR_MSG.QIWU_IO_ERROR);
}
if (chooseAudio) {
return dealReturnAudio(parseRequest, terminateResponse, userId, creator, true);
}
else {
TextResponse textResponse = parseRequest.parseTextRequestReturnText(terminateResponse.getText(), userId, creator);
return MessageUtil.messageToXml(textResponse);
}
}
case REQUEST_TYPE.VOICE : {
userWord = msgMap.get("Recognition");
log.info("用户的话:{}", userWord);
QiWuResponse terminateResponse;
try {
terminateResponse = RequestQiWu.requestQiWuOkHTTP3(userId, userWord);
} catch (Exception e) {
log.error("请求齐悟接口出错{}", e.toString());
return crateCustomTextResponse(userId, creator, OpenConstants.ERROR_MSG.QIWU_IO_ERROR);
}
if (chooseAudio) {
return dealReturnAudio(parseRequest, terminateResponse, userId, creator, false);
}
else {
TextResponse textResponse = parseRequest.parseAudioRequestReturnText(userId, creator, terminateResponse.getText());
return MessageUtil.messageToXml(textResponse);
}
}
case OpenConstants.REQUEST_TYPE.EVENT :{
return dealEventInfo(msgMap);
}
default : {
return crateCustomTextResponse(userId, creator, OpenConstants.ERROR_MSG.UN_SUIT_TYPE);
}
}
}
private String dealEventInfo(Map<String, String> msgMap) {
String event = msgMap.get("Event");
switch (event) {
case EVENT_TYPE.CLICK : return dealWithMenulClick(msgMap);
}
return "success";
}
private String dealWithMenulClick(Map<String, String> msgMap) {
String eventKey = msgMap.get("EventKey");
String openID = msgMap.get("FromUserName");
String creator = msgMap.get("ToUserName");
switch (eventKey) {
case EVENT_KEY.AUDIO : {
changeAudioTextResponse(true, openID);
return crateCustomTextResponse(openID, creator, OpenConstants.ERROR_MSG.AUDIO_MODEL);
}
case EVENT_KEY.TEXT : {
changeAudioTextResponse(false, openID);
return crateCustomTextResponse(openID, creator, OpenConstants.ERROR_MSG.TEXT_MODEL);
}
}
return "success";
}
private void changeAudioTextResponse(boolean audioOrText, String userId) {
UserCacheHolder holder = OPENID_CACHE.get(userId);
Boolean chooseAudio = holder.getAudioOrText();
if (audioOrText && !chooseAudio) {
holder.setAudioOrText(true);
log.info("选择缓存由false更改为true");
} else if (!audioOrText && chooseAudio){
holder.setAudioOrText(false);
log.info("选择缓存由true更改为false");
}
}
private String dealReturnAudio(ParseRequest parseRequest, QiWuResponse response, String userId, String creator, boolean isTextRequest) {
AudioResponse audioResponse;
try {
if (isTextRequest) {
audioResponse = parseRequest.parseTextRequestReturnAudio(response.getAudio(), userId, creator);
} else {
audioResponse = parseRequest.parseAudioRequestReturnAudio(response.getAudio(), userId, creator);
}
} catch (Exception e) {
return crateCustomTextResponse(userId, creator, OpenConstants.ERROR_MSG.QIWU_IO_ERROR);
}
return MessageUtil.messageToXml(audioResponse);
}
private String getMsgID(Map<String, String> msgMap, String openId) {
String msgId = msgMap.get("MsgID");
String createTime = msgMap.get("CreateTime");
if (msgId == null) msgId = new StringBuilder(openId).append(createTime).toString();
return msgId;
}
private UserCacheHolder getHolder(String openId) {
UserCacheHolder holder = OPENID_CACHE.get(openId);
if (holder == null) {
holder = new UserCacheHolder();
OPENID_CACHE.put(openId, holder);
}
return holder;
}
private boolean doesThisRequestRepeat(String msgId, UserCacheHolder holder) {
if (msgId.equals(holder.getRepeatId())) {
return true;
}
holder.setRepeatId(msgId);
return false;
}
private String crateCustomTextResponse(String userID, String creator, String customText) {
TextResponse textResponse = buildTextResponse(userID,
creator, customText);
return MessageUtil.messageToXml(textResponse);
}
public static ConcurrentHashMap<String, UserCacheHolder> getOpenidCache() {
return OPENID_CACHE;
}
}
package ai.qiwu.com.open.service;
import ai.qiwu.com.open.common.OpenConstants.OP_INTERFACE;
import static ai.qiwu.com.open.common.utils.BuildRequestResponse.*;
import ai.qiwu.com.open.common.error.OpenErrorException;
import ai.qiwu.com.open.common.error.project.*;
import ai.qiwu.com.open.common.utils.Schedule;
import ai.qiwu.com.open.common.utils.UpDownloadAudion;
import ai.qiwu.com.open.pojo.response.AudioResponse;
import ai.qiwu.com.open.pojo.response.TextResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
@Service
@Slf4j
public class ParseRequest {
public AudioResponse parseAudioRequestReturnAudio(String audioUrl, String openID, String creator) throws RequestTerminateFailed,
CreateDirectoryFailed, DownloadFromTerminateFailed, IOException, ActiveGetTokenFailed, UploadAudioFileFailed {
// 以下是非加密处理方式
File file = downLoadAudioFromQiWu(audioUrl, openID);
String mediaID = getMediaId(file);
return buildAudioResponse(openID, creator, mediaID);
}
public TextResponse parseAudioRequestReturnText(String openID, String creator, String text) {
// 以下是非加密处理方式
return buildTextResponse(openID, creator, text);
}
public AudioResponse parseTextRequestReturnAudio(String audioUrl, String openID, String creator)
throws DownloadFromTerminateFailed, CreateDirectoryFailed, UploadAudioFileFailed,
ActiveGetTokenFailed, IOException {
// 以下是非加密处理方式
File file = downLoadAudioFromQiWu(audioUrl, openID);
String mediaID = getMediaId(file);
return buildAudioResponse(openID, creator, mediaID);
}
public TextResponse parseTextRequestReturnText(String text, String openID, String creator) {
// 以下是非加密处理方式
return buildTextResponse(openID, creator, text);
}
private String getMediaId(File file) throws ActiveGetTokenFailed, UploadAudioFileFailed {
StringBuilder uploadUrl = new StringBuilder();
String accessToken = Schedule.requireAccessToken();
uploadUrl.append(OP_INTERFACE.UPLOAD_URL).append(accessToken);
String mediaid;
try {
mediaid = UpDownloadAudion.uploadVoice(uploadUrl.toString(), file);
} catch (IOException e) {
log.error("上传文件失败,{}",e.toString());
throw new UploadAudioFileFailed("上传文件失败");
} catch (OpenErrorException e) {
log.info("临时文件上传接口请求错误:"+e.getOpenError().getErrmsg());
throw new UploadAudioFileFailed("上传文件失败");
}
log.info("上传文件成功");
return mediaid;
}
private File downLoadAudioFromQiWu(String audioUrl, String openId) throws IOException,
CreateDirectoryFailed, DownloadFromTerminateFailed {
File file;
try {
file = UpDownloadAudion.downloadAudio(audioUrl, openId);
}
// Okhttp下载出错
catch (Exception e) {
log.error("下载文件失败:{}", e.toString());
throw e;
}
log.info("下载文件成功");
return file;
}
}
package ai.qiwu.com.open.service;
import ai.qiwu.com.open.common.OpenConstants;
import ai.qiwu.com.open.common.OpenConstants.ERROR_MSG;
import ai.qiwu.com.open.common.error.project.RequestTerminateFailed;
import ai.qiwu.com.open.pojo.qiwu.QiWuRequest;
import ai.qiwu.com.open.pojo.qiwu.QiWuResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
@Slf4j
class RequestQiWu {
static QiWuResponse requestQiWuOkHTTP3(String userId, String userWord) throws IOException {
QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUser_id(userId);
requestPojo.setAccess(OpenConstants.DEVICE_NAME);
requestPojo.setText(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(OpenConstants.QI_WU_TERMINATE)
.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr))
.build();
Response response = client.newCall(request).execute();
try (ResponseBody body = response.body()){
String responseJson = body.string();
log.info("齐悟接口返回数据,{}", responseJson);
return JSON.parseObject(responseJson, QiWuResponse.class);
}
}
static QiWuResponse requestQiWu(String userId, String userWord) throws RequestTerminateFailed {
String audioUrl = null;
String textContent = null;
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(OpenConstants.QI_WU_TERMINATE);
HashMap<String, String> params = new HashMap<>();
params.put("user_id", userId);
params.put("text", userWord);
params.put("access",OpenConstants.DEVICE_NAME);
String paramsJsonFormat = JSON.toJSONString(params);
StringEntity body = new StringEntity(paramsJsonFormat, StandardCharsets.UTF_8);
post.setHeader("Content-Type", OpenConstants.CONTENT_TYPE);
post.setEntity(body);
httpResponse = httpClient.execute(post);
HttpEntity responseBody = httpResponse.getEntity();
if (responseBody != null) {
String responseContent = EntityUtils.toString(responseBody);
log.info("齐悟接口返回: "+ responseContent);
JSONObject responseJsonFormat = JSONObject.parseObject(responseContent);
audioUrl = (String) responseJsonFormat.get("audio");
textContent = (String) responseJsonFormat.get("text");
}
} catch (IOException e) {
log.error(ERROR_MSG.TERMINATE_IO_EXCEPTION + ",{}", e.toString());
throw new RequestTerminateFailed(ERROR_MSG.TERMINATE_IO_EXCEPTION);
} finally {
try {
if (httpClient != null) httpClient.close();
if (httpResponse != null) httpResponse.close();
} catch (IOException e) {
log.info(ERROR_MSG.HTTP_CONNECTION_CLOSE_EXCEPTION);
}
}
return buildAudioResponse(audioUrl, textContent);
}
private static QiWuResponse buildAudioResponse(String audioUrl, String text) {
QiWuResponse response = new QiWuResponse();
response.setAudio(audioUrl);
response.setText(text);
return response;
}
}
package ai.qiwu.com.open;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class OpenApplicationTests {
@Test
public void contextLoads() {
}
}
package ai.qiwu.com.open.common.encryption;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class WXBizMsgCryptTest {
String encodingAesKey = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
String token = "pamtest";
String timestamp = "1409304348";
String nonce = "xxxxxx";
String appId = "wxb11529c136998cb6";
String replyMsg = "我是中文abcd123";
String xmlFormat = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
String afterAesEncrypt = "jn1L23DB+6ELqJ+6bruv21Y6MD7KeIfP82D6gU39rmkgczbWwt5+3bnyg5K55bgVtVzd832WzZGMhkP72vVOfg==";
String randomStr = "aaaabbbbccccdddd";
String replyMsg2 = "<xml><ToUserName><![CDATA[oia2Tj我是中文jewbmiOUlr6X-1crbLOvLw]]></ToUserName><FromUserName><![CDATA[gh_7f083739789a]]></FromUserName><CreateTime>1407743423</CreateTime><MsgType><![CDATA[video]]></MsgType><Video><MediaId><![CDATA[eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0]]></MediaId><Title><![CDATA[testCallBackReplyVideo]]></Title><Description><![CDATA[testCallBackReplyVideo]]></Description></Video></xml>";
String afterAesEncrypt2 = "jn1L23DB+6ELqJ+6bruv23M2GmYfkv0xBh2h+XTBOKVKcgDFHle6gqcZ1cZrk3e1qjPQ1F4RsLWzQRG9udbKWesxlkupqcEcW7ZQweImX9+wLMa0GaUzpkycA8+IamDBxn5loLgZpnS7fVAbExOkK5DYHBmv5tptA9tklE/fTIILHR8HLXa5nQvFb3tYPKAlHF3rtTeayNf0QuM+UW/wM9enGIDIJHF7CLHiDNAYxr+r+OrJCmPQyTy8cVWlu9iSvOHPT/77bZqJucQHQ04sq7KZI27OcqpQNSto2OdHCoTccjggX5Z9Mma0nMJBU+jLKJ38YB1fBIz+vBzsYjrTmFQ44YfeEuZ+xRTQwr92vhA9OxchWVINGC50qE/6lmkwWTwGX9wtQpsJKhP+oS7rvTY8+VdzETdfakjkwQ5/Xka042OlUb1/slTwo4RscuQ+RdxSGvDahxAJ6+EAjLt9d8igHngxIbf6YyqqROxuxqIeIch3CssH/LqRs+iAcILvApYZckqmA7FNERspKA5f8GoJ9sv8xmGvZ9Yrf57cExWtnX8aCMMaBropU/1k+hKP5LVdzbWCG0hGwx/dQudYR/eXp3P0XxjlFiy+9DMlaFExWUZQDajPkdPrEeOwofJb";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testNormal() throws ParserConfigurationException, SAXException, IOException {
try {
WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
String afterEncrpt = pc.encryptMsg(replyMsg, timestamp, nonce);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader sr = new StringReader(afterEncrpt);
InputSource is = new InputSource(sr);
Document document = db.parse(is);
Element root = document.getDocumentElement();
NodeList nodelist1 = root.getElementsByTagName("Encrypt");
NodeList nodelist2 = root.getElementsByTagName("MsgSignature");
String encrypt = nodelist1.item(0).getTextContent();
String msgSignature = nodelist2.item(0).getTextContent();
String fromXML = String.format(xmlFormat, encrypt);
// 第三方收到公众号平台发送的消息
String afterDecrpt = pc.decryptMsg(msgSignature, timestamp, nonce, fromXML);
assertEquals(replyMsg, afterDecrpt);
} catch (AesException e) {
fail("正常流程,怎么就抛出异常了??????");
}
}
@Test
public void testAesEncrypt() {
try {
WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
assertEquals(afterAesEncrypt, pc.encrypt(randomStr, replyMsg));
} catch (AesException e) {
e.printStackTrace();
fail("no异常");
}
}
@Test
public void testAesEncrypt2() {
try {
WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
assertEquals(afterAesEncrypt2, pc.encrypt(randomStr, replyMsg2));
} catch (AesException e) {
e.printStackTrace();
fail("no异常");
}
}
@Test
public void testIllegalAesKey() {
try {
new WXBizMsgCrypt(token, "abcde", appId);
} catch (AesException e) {
assertEquals(AesException.IllegalAesKey, e.getCode());
return;
}
fail("错误流程不抛出异常???");
}
@Test
public void testValidateSignatureError() throws ParserConfigurationException, SAXException,
IOException {
try {
WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
String afterEncrpt = pc.encryptMsg(replyMsg, timestamp, nonce);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader sr = new StringReader(afterEncrpt);
InputSource is = new InputSource(sr);
Document document = db.parse(is);
Element root = document.getDocumentElement();
NodeList nodelist1 = root.getElementsByTagName("Encrypt");
String encrypt = nodelist1.item(0).getTextContent();
String fromXML = String.format(xmlFormat, encrypt);
pc.decryptMsg("12345", timestamp, nonce, fromXML); // 这里签名错误
} catch (AesException e) {
assertEquals(AesException.ValidateSignatureError, e.getCode());
return;
}
fail("错误流程不抛出异常???");
}
@Test
public void testVerifyUrl() throws AesException {
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt("QDG6eK",
"jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C", "wx5823bf96d3bd56c7");
String verifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3";
String timeStamp = "1409659589";
String nonce = "263014780";
String echoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ==";
wxcpt.verifyUrl(verifyMsgSig, timeStamp, nonce, echoStr);
// 只要不抛出异常就好
}
}
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
echo Found %WRAPPER_JAR%
) else (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
echo Finished downloading %WRAPPER_JAR%
)
@REM End of extension
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ai.qiwu.com</groupId>
<artifactId>third_party_load</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>third_party_load</name>
<description>third party load project</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baidu.bot</groupId>
<artifactId>baidu-sdk</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package ai.qiwu.com.third_party_load;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ThirdPartyLoadApplication {
public static void main(String[] args) {
SpringApplication.run(ThirdPartyLoadApplication.class, args);
}
}
package ai.qiwu.com.third_party_load.pojo;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-7-13 上午10:40
*/
@Getter
@Setter
public class User {
private String userId;
private String userName;
}
package ai.qiwu.com.third_party_load;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ThirdPartyLoadApplicationTests {
@Test
public void contextLoads() {
}
}
......@@ -31,7 +31,7 @@
</exclusions>
</dependency>
<!--添加servlet-api的依赖,用来打war包 -->
<!--添加servlet-api的依赖,用来打war包-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
......@@ -44,16 +44,33 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baidu.dueros</groupId>
<artifactId>bot-sdk</artifactId>
<version>1.1.9</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
</dependencies>
......
......@@ -6,7 +6,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class XiaoduApplication extends SpringBootServletInitializer {
public class XiaoduApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(XiaoduApplication.class, args);
......
......@@ -22,8 +22,8 @@ public class XiaoDuController {
public String chat() {
try {
ResponseEncapsulation response = new ResponseEncapsulation(Utils.getHttpServletRequest());
response.enableVerify();
//response.disableVerify();
//response.enableVerify();
response.disableVerify();
return response.run();
} catch (Exception e) {
logger.info("出现错误 "+e.toString());
......
package ai.qiwu.baidu.xiaodu.pojo;
/**
* @author 苗权威
* @dateTime 19-7-12 下午8:47
*/
public class User {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package ai.qiwu.baidu.xiaodu.pojo.product;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-7-13 下午12:47
*/
@Getter
@Setter
public class CustomProductPrompts {
private String purchasePromptDescription;
private String boughtCardDescription;
}
package ai.qiwu.baidu.xiaodu.pojo.product;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
/**
* @author 苗权威
* @dateTime 19-7-13 下午12:50
*/
@Getter
@Setter
public class Pricing {
private Integer originalPrice;
private Integer price;
}
package ai.qiwu.baidu.xiaodu.pojo.product;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-7-13 下午12:18
*/
@Getter
@Setter
public class Product {
private Enum version;
private String referenceName;
private Enum type;
private PublishingInformation publishingInformation;
}
package ai.qiwu.baidu.xiaodu.pojo.product;
import sun.text.normalizer.VersionInfo;
/**
* @author 苗权威
* @dateTime 19-7-13 下午2:13
*/
public enum ProductEnumItem {
VERSION("1.0"),
;
private String value;
ProductEnumItem(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}}
package ai.qiwu.baidu.xiaodu.pojo.product;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-7-13 下午12:23
*/
@Getter
@Setter
public class PublishingInformation {
private String name;
private String summary;
private String description;
private String smallIconUri;
private String largeIconUri;
private String category;
private List<String> examplePhrases;
private List<String> keywords;
private CustomProductPrompts customProductPrompts;
private Pricing pricing;
private String skillId;
private Enum purchasableState;
}
package ai.qiwu.baidu.xiaodu.service;
import ai.qiwu.baidu.xiaodu.common.Constants;
import ai.qiwu.baidu.xiaodu.common.Constants.ErrorMsg;
import ai.qiwu.baidu.xiaodu.common.Constants.EndMsg;
import ai.qiwu.baidu.xiaodu.common.Constants.WelcomeWord;
import ai.qiwu.baidu.xiaodu.common.Holder;
import ai.qiwu.baidu.xiaodu.common.Utils;
import ai.qiwu.baidu.xiaodu.pojo.AudioUrlAndText;
import com.alibaba.fastjson.JSON;
import com.baidu.dueros.bot.AudioPlayer;
import com.baidu.dueros.data.request.IntentRequest;
import com.baidu.dueros.data.request.LaunchRequest;
import com.baidu.dueros.data.request.Query;
import com.baidu.dueros.data.request.SessionEndedRequest;
import com.baidu.dueros.data.request.*;
import com.baidu.dueros.data.request.audioplayer.event.PlaybackFinishedEvent;
import com.baidu.dueros.data.request.audioplayer.event.PlaybackNearlyFinishedEvent;
import com.baidu.dueros.data.request.audioplayer.event.PlaybackStoppedEvent;
import com.baidu.dueros.data.request.pay.event.ChargeEvent;
import com.baidu.dueros.data.request.pay.event.Payload;
import com.baidu.dueros.data.response.OutputSpeech;
import com.baidu.dueros.data.response.Reprompt;
import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective;
import com.baidu.dueros.data.response.directive.audioplayer.Play;
import com.baidu.dueros.data.response.directive.pay.Buy;
import com.baidu.dueros.data.response.directive.pay.Charge;
import com.baidu.dueros.model.Request;
import com.baidu.dueros.model.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
......@@ -36,7 +36,7 @@ import java.util.concurrent.locks.ReentrantLock;
*/
public class ResponseEncapsulation extends AudioPlayer {
private static final ConcurrentHashMap<String, Holder> USER_TIMESTAMP = new ConcurrentHashMap<>();
//private static final ConcurrentHashMap<String, Holder> USER_TIMESTAMP = new ConcurrentHashMap<>();
private static final Logger logger = LoggerFactory.getLogger(ResponseEncapsulation.class);
......@@ -63,6 +63,21 @@ public class ResponseEncapsulation extends AudioPlayer {
}
@Override
protected Response onChargeEvent(ChargeEvent chargeEvent) {
Payload payload = chargeEvent.getPayload();
if (payload.getPurchaseResult().equals("SUCCESS")) {
logger.info("支付成功,"+payload.getMessage());
logger.info("百度扣款金额:"+chargeEvent.getPayload().getAuthorizationDetails().getCapturedAmount().getAmount());
logger.info("本次交易百度生成的订单ID:"+chargeEvent.getPayload().getBaiduOrderReferenceId());
logger.info("对应支付的订单ID:"+chargeEvent.getPayload().getSellerOrderId());
return buildErrorResponse("恭喜您支付成功,开始体验吧");
}else {
logger.info("支付发生错误,"+payload.getMessage());
return buildErrorResponse("哎呀,没有支付成功");
}
}
@Override
protected Response onInent(IntentRequest intentRequest) {
String userId = getCustomerId();
String timestamp = this.getRequest().getRequest().getTimestamp();
......@@ -74,44 +89,53 @@ public class ResponseEncapsulation extends AudioPlayer {
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
Holder holder = USER_TIMESTAMP.get(userId);
ReentrantLock lock = null;
try {
lock = holder.getFAIR_LOCK();
lock.lock();
if (holder.getFirst() == 0) {
holder.setFirst(1);
Thread.sleep(60);
}
if (lock.hasQueuedThreads()) {
logger.info("由于请求间隔过短,因此认为本次请求为过于的重复请求,"+ "上次请求的时间:"+holder.getTimestamp() +
"这次请求的时间:"+ timestamp+"本次请求内容为:original:"
+intentRequest.getQuery().getOriginal()+"; asrRawResult:"+getAsrRawResult(this.getStrRequest()));
this.waitAnswer();
return new Response();
}
} catch (InterruptedException e) {
logger.info("睡眠中断");
holder.setFirst(0);
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
} catch (NullPointerException e) {
logger.info("锁未初始化");
USER_TIMESTAMP.put(userId, new Holder());
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
} finally {
if (lock != null) lock.unlock();
}
holder.setTimestamp(timestamp);
holder.setFirst(0);
// Holder holder = USER_TIMESTAMP.get(userId);
// ReentrantLock lock = null;
// try {
// lock = holder.getFAIR_LOCK();
// lock.lock();
// if (holder.getFirst() == 0) {
// holder.setFirst(1);
// Thread.sleep(60);
// }
// if (lock.hasQueuedThreads()) {
// logger.info("由于请求间隔过短,因此认为本次请求为过于的重复请求,"+ "上次请求的时间:"+holder.getTimestamp() +
// "这次请求的时间:"+ timestamp+"本次请求内容为:original:"
// +intentRequest.getQuery().getOriginal()+"; asrRawResult:"+getAsrRawResult(this.getStrRequest()));
// this.waitAnswer();
// return new Response();
// }
// } catch (InterruptedException e) {
// logger.info("睡眠中断");
// holder.setFirst(0);
// return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
// } catch (NullPointerException e) {
// logger.info("锁未初始化");
// USER_TIMESTAMP.put(userId, new Holder());
// return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
// } finally {
// if (lock != null) lock.unlock();
// }
// holder.setTimestamp(timestamp);
// holder.setFirst(0);
logger.info("请求消息:"+this.getStrRequest());
AudioUrlAndText data = RequestTerminal.requestTerminate(userWord, userId);
if (data == null) {
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
if (getIntent().getName().equals("buy")) {
String productName = getSlot("sys.wildcard-slot");
logger.info("用户要购买的作品名:"+productName);
String sellerOrderId = "sgaggg"+new Random(47).nextInt(1000)+"aga"+new Random(47).nextInt(765355);
Charge chargeDirective = new Charge("0.01", sellerOrderId,
productName, productName+",这是个非常精彩的故事哦");
addDirective(chargeDirective);
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请到小度APP上去支付");
return new Response(outputSpeech);
}else {
AudioUrlAndText data = RequestTerminal.requestTerminate(userWord, userId);
if (data == null) {
return buildErrorResponse(ErrorMsg.SORRY_UNCATCH);
}
String audioUrl = data.getAudioUrl();
addDirective(buildPlayDirective(audioUrl, AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL));
}
String audioUrl = data.getAudioUrl();
addDirective(buildPlayDirective(audioUrl, AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL));
return new Response();
}
......@@ -167,7 +191,7 @@ public class ResponseEncapsulation extends AudioPlayer {
@Override
public Response onLaunch(LaunchRequest launchRequest) {
logger.info("请求消息:"+this.getStrRequest());
USER_TIMESTAMP.put(getCustomerId(), new Holder());
//USER_TIMESTAMP.put(getCustomerId(), new Holder());
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, WelcomeWord.WELCOME);
Reprompt reprompt = new Reprompt(new OutputSpeech(OutputSpeech.SpeechType.PlainText, WelcomeWord.BEGIN_NO_RESPONSE));
return new Response(outputSpeech, null, reprompt);
......@@ -176,10 +200,10 @@ public class ResponseEncapsulation extends AudioPlayer {
@Override
public Response onSessionEnded(SessionEndedRequest sessionEndedRequest) {
logger.info("触发结束事件,"+this.getStrRequest());
Holder holder = USER_TIMESTAMP.remove(getCustomerId());
if (holder != null) {
logger.info("删除用户:"+getCustomerId()+" 的缓存成功");
}
// Holder holder = USER_TIMESTAMP.remove(getCustomerId());
// if (holder != null) {
// logger.info("删除用户:"+getCustomerId()+" 的缓存成功");
// }
switch (sessionEndedRequest.getReason()) {
case ERROR: dealWithError(sessionEndedRequest); break;
case USER_INITIATED: logger.info(EndMsg.USER_SAY_CANCEL); break;
......@@ -287,4 +311,9 @@ public class ResponseEncapsulation extends AudioPlayer {
int asrWordEnd = requestStr.indexOf('"',asrWordBegin);
return requestStr.substring(asrWordBegin, asrWordEnd);
}
// private void payUseBuyOrder() {
// Buy buy = new Buy();
// SkillInfo
// }
}
logging.path=/usr/mqw/logs/jdwhale
logging.level.root = info
spring.output.ansi.enabled=detect
\ No newline at end of file
#logging.path=/usr/mqw/logs/xiaodu
#logging.level.root = info
#spring.output.ansi.enabled=detect
\ No newline at end of file
logging.path=/usr/mqw/logs/jdwhale
logging.path=/usr/mqw/logs/xiaoya
logging.level.root = info
spring.output.ansi.enabled=detect
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment