Java Code Examples for com.amazon.ask.dispatcher.request.handler.HandlerInput

The following examples show how to use com.amazon.ask.dispatcher.request.handler.HandlerInput. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void testSupportAndResolve() throws NoSuchMethodException {
    MethodParameter methodParameter = new MethodParameter(
            this.getClass().getMethod("testSupportAndResolve"),
            0,
            AttributesManager.class,
            MethodParameter.EMPTY_ANNOTATIONS
    );

    RequestEnvelope envelope = Utils.buildSimpleEnvelope("intent");
    HandlerInput handlerInput = HandlerInput
            .builder()
            .withRequestEnvelope(envelope)
            .build();
    ArgumentResolverContext input = new ArgumentResolverContext(mockSkillContext, methodParameter, handlerInput);

    assertSame(handlerInput.getAttributesManager(), resolver.resolve(input).get());
}
 
Example 2
@Test
public void test_nested_value_doesnt_match() throws Exception {
    Predicate<HandlerInput> predicate = buildPredicate("inSessionNested");

    HandlerInput rootDoesntExist = Utils.buildSimpleSimpleIntentRequest("whatever", "meh", "meh");
    HandlerInput valueDoesntMatch = Utils.buildSimpleSimpleIntentRequest("whatever", "meh", "meh", Collections.singletonMap(
        "a", Collections.singletonMap("b", "INVALID")
    ));
    HandlerInput notNested = Utils.buildSimpleSimpleIntentRequest("whatever", "meh", "meh", Collections.singletonMap(
        "a", "B"
    ));
    HandlerInput keyDoesntExist = Utils.buildSimpleSimpleIntentRequest("whatever", "meh", "meh", Collections.singletonMap(
        "a", Collections.singletonMap("c", "value")
    ));

    assertFalse(predicate.test(rootDoesntExist));
    assertFalse(predicate.test(valueDoesntMatch));
    assertFalse(predicate.test(notNested));
    assertFalse(predicate.test(keyDoesntExist));
}
 
Example 3
Source Project: micronaut-aws   Source File: TestAlexApplication.java    License: Apache License 2.0 5 votes vote down vote up
@IntentHandler("HelloWorldIntent")
public Optional<Response> greet(HandlerInput input) {
    String speechText = "Hello World";
    return input.getResponseBuilder()
            .withSpeech(speechText)
            .withSimpleCard("HelloWorld", speechText)
            .build();
}
 
Example 4
Source Project: micronaut-aws   Source File: AnnotatedRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
default boolean canHandle(HandlerInput handlerInput) {
    final Class<? extends AnnotatedRequestHandler> type = getClass();
    final String annotationMetadata = type.getPackage().getName() + ".$" + type.getSimpleName() + "DefinitionClass";
    final AnnotationMetadata metadata = ClassUtils.forName(annotationMetadata, type.getClassLoader()).flatMap(aClass -> {
        final Object o = InstantiationUtils.tryInstantiate(aClass).orElse(null);
        if (o instanceof AnnotationMetadataProvider) {
            return Optional.of(((AnnotationMetadataProvider) o).getAnnotationMetadata());
        }
        return Optional.empty();
    }).orElse(AnnotationMetadata.EMPTY_METADATA);
    final String[] names = metadata.getValue(IntentHandler.class, String[].class).orElse(StringUtils.EMPTY_STRING_ARRAY);
    return Arrays.stream(names).anyMatch(n -> handlerInput.matches(intentName(n)));
}
 
Example 5
@Override
public final Optional<Response> handle(final HandlerInput input) {
    return input.getResponseBuilder()
            .withSpeech("Goodbye buddy")
            .withSimpleCard("SelfIntro", "Goodbye")
            .build();
}
 
Example 6
@Override
public final Optional<Response> handle(final HandlerInput input) {
    String speechText = "Welcome to the Self Intro Alexa Skill for Heartin, you may say 'please say intro'";
    return input.getResponseBuilder()
            .withSpeech(speechText)
            .withSimpleCard("SelfIntro", speechText)
            .withReprompt(speechText)
            .build();
}
 
Example 7
@Override
public Optional<Response> handle(HandlerInput handlerInput, Throwable throwable) {
    System.out.println("Exception: " + throwable.toString());
    System.out.println("Exception thrown while receiving: " + handlerInput.getRequestEnvelope().getRequest().getType());
    return handlerInput.getResponseBuilder()
            .withSpeech("Sorry. I have problems answering your request. Please try again.")
            .build();
}
 
Example 8
@Override
public final Optional<Response> handle(final HandlerInput input) {
    String speechText = "Hello, this is Alexa saying intro for Heartin Kanikathottu. "
            + "Heartin is a senior software engineer and blogger with around 11 years of IT experience. "
            + "He likes to share his technical knowledge through his blogs such as CloudMaterials.com "
            + "and Java J EE dot com. "
            + "He also likes to mentor juniors and take sessions at meetups and conferences.";

    return input.getResponseBuilder()
            .withSpeech(speechText)
            .withSimpleCard("SelfIntro", speechText)
            .build();
}
 
Example 9
@Override
public Optional<Response> handle(HandlerInput handlerInput, Throwable throwable) {
    System.out.println("Exception: " + throwable.toString());
    System.out.println("Exception thrown while receiving: " + handlerInput.getRequestEnvelope().getRequest().getType());
    return handlerInput.getResponseBuilder()
        .withSpeech("Sorry. I have problems answering your request. Please try again")
        .withShouldEndSession(true)
        .build();
}
 
Example 10
@Override
public final Optional<Response> handle(final HandlerInput input) {
    String speechText = "You you may say 'please say intro'!";
    return input.getResponseBuilder()
            .withSpeech(speechText)
            .withSimpleCard("SelfIntro", speechText)
            .withReprompt(speechText)
            .build();
}
 
Example 11
@Override
public final Optional<Response> handle(final HandlerInput input) {
    String speechText = "Sorry buddy, I don't know that. You can say try saying help!";
    return input.getResponseBuilder()
            .withSpeech(speechText)
            .withSimpleCard("SelfIntro", speechText)
            .withReprompt(speechText)
            .build();
}
 
Example 12
@Override
public Optional<Response> handle(HandlerInput handlerInput, Throwable throwable) {
    return handlerInput.getResponseBuilder()
        .withSpeech("Sorry I couldn't understand that. Please try again")
        .withReprompt("Please try again")
        .withShouldEndSession(false)
        .build();
}
 
Example 13
@Override
public Optional<Response> handle(HandlerInput input) {
    try {
        return handle(input, intentReader.read((IntentRequest) input.getRequestEnvelope().getRequest()));
    } catch (IntentParseException ex) {
        String msg = String.format("Failed to read a '%s' from intent request", intentClass.getName());
        logger.error(msg);
        throw new RuntimeException(msg, ex);
    }
}
 
Example 14
@Override
public Optional<Response> handle(HandlerInput handlerInput, Throwable throwable) {
    return handlerInput.getResponseBuilder()
        .withSpeech("Sorry I couldn't understand that. Please try again")
        .withReprompt("Please try again")
        .withShouldEndSession(false)
        .build();
}
 
Example 15
@Override
public void process(HandlerInput input, Optional<Response> response) {
    ArgumentResolver responseResolver = context ->
        context.parameterTypeIsAssignableFrom(Response.class)
            ? Optional.of(response.orElse(null))
            : Optional.empty();

    try {
        invoker.invoke(input, context, responseResolver);
    } catch (Exception ex) {
        logger.error(String.format("[%s] Failed to invoke response interceptor: %s",
            input.getRequestEnvelope().getRequest().getRequestId(), context), ex);
        throw new RuntimeException(ex);
    }
}
 
Example 16
@Override
public Optional<Response> handle(HandlerInput input, Throwable throwable) {
    ArgumentResolver exceptionResolver = context ->
        context.parameterTypeIsAssignableFrom(throwable.getClass())
            ? Optional.of(throwable)
            : Optional.empty();

    try {
        return renderer.render(context, invoker.invoke(input, context, exceptionResolver), input.getRequestEnvelope());
    } catch (Exception ex) {
        logger.error(String.format("[%s] Failed to handle exception in ExceptionHandler: %s",
            input.getRequestEnvelope().getRequest().getRequestId() ,context.getMethod()), ex);
        throw new RuntimeException(ex);
    }
}
 
Example 17
@Override
public void process(HandlerInput input) {
    try {
        invoker.invoke(input, context);
    } catch (Exception ex) {
        logger.error(String.format("[%s] Failed to invoke request interceptor: %s", input.getRequestEnvelope().getRequest().getRequestId(), context), ex);
        throw new RuntimeException(ex);
    }
}
 
Example 18
@Override
public Optional<RequestHandlerChain> getRequestHandlerChain(HandlerInput input) {
    if (predicate.test(input)) {
        // Both the CONTROLLER & METHOD predicates must match, so we can slightly
        // optimize a scan by short-circuiting it if the controller's predicate
        // yields false.
        return requestMapper.getRequestHandlerChain(input);
    } else {
        return Optional.empty();
    }
}
 
Example 19
/**
 * Generic procedure for discovering request/exception handlers and request/response interceptors
 * from a controller's methods.
 *
 * Applies method discovery logic consistently for all mapping types:
 * <ul>
 *     <li>resolve a {@link Predicate} of {@link HandlerInput} from the method</li>
 *     <li>delegate responsibility to the underlying handler, but guard it with the predicate</li>
 *     <li>look for the {@link Priority} annotation on each method</li>
 *     <li>order each handler in the controller by its priority</li>
 *     <li>methods not annotated with {@link Priority} are considered to have priority 0</li>
 * </ul>
 *
 * @param controller scanned for methods with mappers
 * @param resolvers set of resolvers
 * @param guardBuilder supplies a {@link Guard.Builder} for this mapping type
 * @param <T> type of handler/interceptor/etc. being discovered, e.g. {@link RequestInterceptor}
 * @param <G> type of guard, e.g. {@link RequestInterceptorGuard}
 * @param <B> type of guard builder, e.g. {@link RequestInterceptorGuard#builder()}
 * @return stream of constructed delegates, ordered by priority
 */
protected <T, G extends Guard<T>, B extends Guard.Builder<B, T, G>> Stream<G> find(
    Object controller,
    Set<? extends Resolver<ControllerMethodContext, T>> resolvers,
    Supplier<B> guardBuilder) {

    return Arrays.stream(controller.getClass().getMethods())
        .map(method -> ControllerMethodContext.builder()
            .withSkillContext(skillContext)
            .withController(controller)
            .withMethod(method)
            .build())
        .flatMap(context -> {
            Predicate<HandlerInput> predicate = findPredicates(context).orElse(TRUE);

            return resolvers.stream()
                .flatMap(resolver -> resolver.resolve(context).map(Stream::of).orElse(Stream.empty()))
                .map(delegate -> guardBuilder.get()
                    .withDelegate(delegate)
                    .withPredicate(predicate)
                    .withPriority(Optional.ofNullable(context.getMethod().getAnnotation(Priority.class))
                        .map(Priority::value)
                        .orElse(0))) // default to the '0' bucket for methods not annotated with Priority
                .map(Guard.Builder::<G>build);
        })
        // sort in descending order, so "higher priority" is more intuitive
        .sorted((a, b) -> -1 * Integer.compare(a.getPriority(), b.getPriority()));
}
 
Example 20
private Predicate<HandlerInput> buildPredicate(String methodName) throws NoSuchMethodException {
    return underTest
        .apply(
            ControllerMethodContext.builder()
                .withSkillContext(mockSkillContext)
                .withController(this)
                .withMethod(getClass().getMethod(methodName))
                .build(),
            getClass().getMethod(methodName).getAnnotation(WhenSessionAttribute.class));
}
 
Example 21
@Test
public void testSupportAndResolve() throws NoSuchMethodException {
    Method method = MappingsController.class.getMethod("handleModelSlot", MappingsController.PetType.class);
    MethodParameter methodParameter = new MethodParameter(
            method,
            0,
            MappingsController.PetType.class,
            method.getParameterAnnotations()[0]
    );

    RequestEnvelope envelope = Utils.buildSimpleEnvelope("PetTypeIntentTwo", "pet", "DRAGON");
    ArgumentResolverContext input = new ArgumentResolverContext(mockSkillContext, methodParameter, HandlerInput.builder().withRequestEnvelope(envelope).build());

    assertEquals(MappingsController.PetType.DRAGON, resolver.resolve(input).get());
}
 
Example 22
@Test
public void testDoesntSupport() throws NoSuchMethodException {
    MethodParameter methodParameter = new MethodParameter(
            this.getClass().getMethod("testSupportAndResolve"),
            0,
            Map.class, //<---- wrong class
            MethodParameter.EMPTY_ANNOTATIONS
    );

    RequestEnvelope envelope = Utils.buildSimpleEnvelope("PetTypeIntent2", "pet", "DRAGON");
    ArgumentResolverContext input = new ArgumentResolverContext(mockSkillContext, methodParameter, HandlerInput.builder().withRequestEnvelope(envelope).build());

    assertFalse(resolver.resolve(input).isPresent());
}
 
Example 23
@Test
public void testSupportAndResolve() throws NoSuchMethodException {
    MethodParameter methodParameter = new MethodParameter(
            this.getClass().getMethod("testSupportAndResolve"),
            0,
            MappingsController.PetTypeIntent.class,
            MethodParameter.EMPTY_ANNOTATIONS
    );

    RequestEnvelope envelope = Utils.buildSimpleEnvelope("PetTypeIntent", "pet", "DRAGON");
    ArgumentResolverContext input = new ArgumentResolverContext(mockSkillContext, methodParameter, HandlerInput.builder().withRequestEnvelope(envelope).build());

    Object resolved = resolver.resolve(input).get();
    assertTrue(resolved instanceof MappingsController.PetTypeIntent);
}
 
Example 24
@Test
public void testDoesntSupport() throws NoSuchMethodException {
    MethodParameter methodParameter = new MethodParameter(
            this.getClass().getMethod("testSupportAndResolve"),
            0,
            Map.class, //<---- wrong class
            MethodParameter.EMPTY_ANNOTATIONS
    );

    RequestEnvelope envelope = Utils.buildSimpleEnvelope("PetTypeIntent", "pet", "DRAGON");
    ArgumentResolverContext input = new ArgumentResolverContext(mockSkillContext, methodParameter, HandlerInput.builder().withRequestEnvelope(envelope).build());

    Optional<Object> result = resolver.resolve(input);
    assertFalse(result.isPresent());
}
 
Example 25
@Override
public Optional<Response> handle(HandlerInput handlerInput, Throwable throwable) {
    System.out.println("Exception: " + throwable.toString());
    System.out.println("Exception thrown while receiving: " + handlerInput.getRequestEnvelope().getRequest().getType());
    return handlerInput.getResponseBuilder()
        .withSpeech("Sorry. I have problems answering your request. Please try again")
        .withShouldEndSession(true)
        .build();
}
 
Example 26
@Test
public void testDoesntSupport() throws NoSuchMethodException {
    MethodParameter methodParameter = new MethodParameter(
            this.getClass().getMethod("testSupportAndResolve"),
            0,
            Object.class, //<---- wrong class
            MethodParameter.EMPTY_ANNOTATIONS
    );

    RequestEnvelope envelope = Utils.buildSimpleEnvelope("intent");
    ArgumentResolverContext input = new ArgumentResolverContext(mockSkillContext, methodParameter, HandlerInput.builder().withRequestEnvelope(envelope).build());

    assertFalse(resolver.resolve(input).isPresent());
}
 
Example 27
@Override
public Optional<Response> handle(HandlerInput handlerInput, Throwable throwable) {
    System.out.println("Exception: " + throwable.toString());
    System.out.println("Exception thrown while receiving: " + handlerInput.getRequestEnvelope().getRequest().getType());
    return handlerInput.getResponseBuilder()
        .withSpeech("Sorry. I have problems answering your request. Please try again")
        .withShouldEndSession(true)
        .build();
}
 
Example 28
@Test
public void testDoesntSupport() throws NoSuchMethodException {
    MethodParameter methodParameter = new MethodParameter(
        this.getClass().getMethod("testSupportAndResolve"),
        0,
        Object.class, //<---- wrong class
        MethodParameter.EMPTY_ANNOTATIONS
    );

    RequestEnvelope envelope = Utils.buildSimpleEnvelope("intent");
    ArgumentResolverContext input = new ArgumentResolverContext(mockSkillContext, methodParameter, HandlerInput.builder().withRequestEnvelope(envelope).build());

    assertFalse(resolver.resolve(input).isPresent());
}
 
Example 29
@Test
public void testSupportAndResolve() throws NoSuchMethodException {
    MethodParameter methodParameter = new MethodParameter(
            this.getClass().getMethod("testSupportAndResolve"),
            0,
            IntentRequest.class,
            MethodParameter.EMPTY_ANNOTATIONS
    );

    RequestEnvelope envelope = Utils.buildSimpleEnvelope("intent");
    ArgumentResolverContext input = new ArgumentResolverContext(mockSkillContext, methodParameter, HandlerInput.builder().withRequestEnvelope(envelope).build());

    assertSame(envelope.getRequest(), resolver.resolve(input).get());
}
 
Example 30
@Override
public Optional<Response> handle(HandlerInput handlerInput, Throwable throwable) {
    return handlerInput.getResponseBuilder()
        .withSpeech("Sorry. I couldn't understand that. Please try again")
        .withReprompt("Please try again")
        .withShouldEndSession(false)
        .build();
}