use of com.ning.http.client.AsyncCompletionHandler in project NabAlive by jcheype.
the class TtsController method init.
@PostConstruct
void init() {
restHandler.get(new Route("/tts/:apikey/:voice") {
@Override
public void handle(Request request, final Response response, Map<String, String> map) throws Exception {
String text = StringEscapeUtils.escapeXml(checkNotNull(request.getParam("text")));
String voice = checkNotNull(map.get("voice"));
if (!text.startsWith("<s>")) {
text = "<s>" + text + "</s>";
}
final String key = text + "|" + voice;
byte[] bytes = ttsCache.asMap().get(key);
if (bytes != null) {
response.write(ChannelBuffers.copiedBuffer(bytes));
return;
}
asyncHttpClient.preparePost(frenchTtsUrl).setBody(text).execute(new AsyncCompletionHandler<com.ning.http.client.Response>() {
@Override
public com.ning.http.client.Response onCompleted(com.ning.http.client.Response asyncResponse) throws Exception {
InputStream inputStream = asyncResponse.getResponseBodyAsStream();
byte[] bytes = ByteStreams.toByteArray(inputStream);
ttsCache.asMap().put(key, bytes);
response.write(bytes);
return asyncResponse;
}
@Override
public void onThrowable(Throwable t) {
logger.error("TTS error", t);
HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
response.write(httpResponse);
}
});
}
}).get(new Route("/tts/:voice") {
@Override
public void handle(Request request, final Response response, Map<String, String> map) throws Exception {
String text = StringEscapeUtils.escapeXml(checkNotNull(request.getParam("text")));
String voice = checkNotNull(map.get("voice"));
if (!text.startsWith("<s>")) {
text = "<s>" + text + "</s>";
}
final String key = text + "|" + voice;
byte[] bytes = ttsCache.asMap().get(key);
if (bytes != null) {
response.write(ChannelBuffers.copiedBuffer(bytes));
return;
}
asyncHttpClient.preparePost(frenchTtsUrl).setBody(text).execute(new AsyncCompletionHandler<com.ning.http.client.Response>() {
@Override
public com.ning.http.client.Response onCompleted(com.ning.http.client.Response asyncResponse) throws Exception {
InputStream inputStream = asyncResponse.getResponseBodyAsStream();
byte[] bytes = ByteStreams.toByteArray(inputStream);
ttsCache.asMap().put(key, bytes);
response.write(bytes);
return asyncResponse;
}
@Override
public void onThrowable(Throwable t) {
logger.error("TTS error", t);
HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
response.write(httpResponse);
}
});
}
});
}
Aggregations