forked from KayLerch/alexa-utterance-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Handler.java
53 lines (51 loc) · 2.57 KB
/
Handler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package io.klerch.alexa.utterances.lambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import io.klerch.alexa.utterances.formatter.Formatter;
import io.klerch.alexa.utterances.formatter.JsonFormatter;
import io.klerch.alexa.utterances.output.MemoryOutputWriter;
import io.klerch.alexa.utterances.processor.Generator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* Lambda request handler for hosting the Generator as a serverless function on AWS
*/
public class Handler implements RequestHandler<Request, Response> {
/**
* Handles the incoming request
* @param request request object
* @param context execution context in Lambda
* @return response object with generation results
*/
@Override
public Response handleRequest(final Request request, final Context context) {
final MemoryOutputWriter outputWriter = new MemoryOutputWriter();
final Formatter formatter = JsonFormatter.create(outputWriter).build();
final List<String> errors = new ArrayList<>();
Optional.ofNullable(request.getLines()).ifPresent(lines -> {
try {
Generator.create().withFormatter(formatter).build().generate(Arrays.asList(lines));
} catch (Throwable ex) {
errors.add(ex.getMessage());
}
});
if (!errors.isEmpty()) {
final StringBuilder errorPayload = new StringBuilder("{ 'errors' : [");
errorPayload.append("'" + errors.get(0) + "'");
errorPayload.append("]}");
return new Response(500).withBody(errorPayload.toString());
}
return new Response(200)
.withBody(outputWriter.getOutput())
.withHeader("BuiltinIntents", outputWriter.getGeneration().getNumberOfBuiltinIntents())
.withHeader("CustomIntents", outputWriter.getGeneration().getNumberOfCustomIntents())
.withHeader("Intents", outputWriter.getGeneration().getNumberOfIntents())
.withHeader("Slots", outputWriter.getGeneration().getNumberOfSlots())
.withHeader("SlotTypes", outputWriter.getGeneration().getNumberOfSlotTypes())
.withHeader("SlotValues", outputWriter.getGeneration().getNumberOfSlotValues())
.withHeader("SlotValuesWithSynonyms", outputWriter.getGeneration().getNumberOfSlotValuesWithSynonyms())
.withHeader("Utterances", outputWriter.getGeneration().getNumberOfUtterances());
}
}