content: /**
      Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  
      Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
  
          http://aws.amazon.com/apache2.0/
  
      or in the "license" file accompanying this file. This file 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.
   */
  package com.amazon.asksdk.session;
  
  import java.util.Map;
  
  import org.apache.commons.lang3.StringUtils;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  
  import com.amazon.speech.slu.Intent;
  import com.amazon.speech.slu.Slot;
  import com.amazon.speech.speechlet.IntentRequest;
  import com.amazon.speech.speechlet.LaunchRequest;
  import com.amazon.speech.speechlet.Session;
  import com.amazon.speech.speechlet.SessionEndedRequest;
  import com.amazon.speech.speechlet.SessionStartedRequest;
  import com.amazon.speech.speechlet.SpeechletV2;
  import com.amazon.speech.speechlet.SpeechletResponse;
  import com.amazon.speech.json.SpeechletRequestEnvelope;
  import com.amazon.speech.ui.PlainTextOutputSpeech;
  import com.amazon.speech.ui.Reprompt;
  import com.amazon.speech.ui.SimpleCard;
  
  /**
   * This sample shows how to create a simple speechlet for handling intent requests and managing
   * session interactions.
   */
  public class SessionSpeechlet implements SpeechletV2 {
      private static final Logger log = LoggerFactory.getLogger(SessionSpeechlet.class);
  
      private static final String COLOR_KEY = "COLOR";
      private static final String COLOR_SLOT = "Color";
  
      @Override
      public void onSessionStarted(SpeechletRequestEnvelope<SessionStartedRequest> requestEnvelope) {
          log.info("onSessionStarted requestId={}, sessionId={}", requestEnvelope.getRequest().getRequestId(),
                  requestEnvelope.getSession().getSessionId());
          // any initialization logic goes here
      }
  
      @Override
      public SpeechletResponse onLaunch(SpeechletRequestEnvelope<LaunchRequest> requestEnvelope) {
          log.info("onLaunch requestId={}, sessionId={}", requestEnvelope.getRequest().getRequestId(),
                  requestEnvelope.getSession().getSessionId());
          return getWelcomeResponse();
      }
  
      @Override
      public SpeechletResponse onIntent(SpeechletRequestEnvelope<IntentRequest> requestEnvelope) {
          IntentRequest request = requestEnvelope.getRequest();
          Session session = requestEnvelope.getSession();
          log.info("onIntent requestId={}, sessionId={}", request.getRequestId(), session);
  
          // Get intent from the request object.
          Intent intent = request.getIntent();
          String intentName = (intent != null) ? intent.getName() : null;
  
          // Note: If the session is started with an intent, no welcome message will be rendered;
          // rather, the intent specific response will be returned.
          if ("MyColorIsIntent".equals(intentName)) {
              return setColorInSession(intent, session);
          } else if ("WhatsMyColorIntent".equals(intentName)) {
              return getColorFromSession(intent, session);
          } else {
              String errorSpeech = "This is unsupported.  Please try something else.";
              return getSpeechletResponse(errorSpeech, errorSpeech, true);
          }
      }
  
      @Override
      public void onSessionEnded(SpeechletRequestEnvelope<SessionEndedRequest> requestEnvelope) {
          log.info("onSessionEnded requestId={}, sessionId={}", requestEnvelope.getRequest().getRequestId(),
                  requestEnvelope.getSession().getSessionId());
          // any cleanup logic goes here
      }
  
      /**
       * Creates and returns a {@code SpeechletResponse} with a welcome message.
       *
       * @return SpeechletResponse spoken and visual welcome message
       */
      private SpeechletResponse getWelcomeResponse() {
          // Create the welcome message.
          String speechText =
                  "Welcome to the Alexa Skills Kit sample. Please tell me your favorite color by "
                          + "saying, my favorite color is red";
          String repromptText =
                  "Please tell me your favorite color by saying, my favorite color is red";
  
          return getSpeechletResponse(speechText, repromptText, true);
      }
  
      /**
       * Creates a {@code SpeechletResponse} for the intent and stores the extracted color in the
       * Session.
       *
       * @param intent
       *            intent for the request
       * @return SpeechletResponse spoken and visual response the given intent
       */
      private SpeechletResponse setColorInSession(final Intent intent, final Session session) {
          // Get the slots from the intent.
          Map<String, Slot> slots = intent.getSlots();
  
          // Get the color slot from the list of slots.
          Slot favoriteColorSlot = slots.get(COLOR_SLOT);
          String speechText, repromptText;
  
          // Check for favorite color and create output to user.
          if (favoriteColorSlot != null) {
              // Store the user's favorite color in the Session and create response.
              String favoriteColor = favoriteColorSlot.getValue();
              session.setAttribute(COLOR_KEY, favoriteColor);
              speechText =
                      String.format("I now know that your favorite color is %s. You can ask me your "
                              + "favorite color by saying, what's my favorite color?", favoriteColor);
              repromptText =
                      "You can ask me your favorite color by saying, what's my favorite color?";
  
          } else {
              // Render an error since we don't know what the users favorite color is.
              speechText = "I'm not sure what your favorite color is, please try again";
              repromptText =
                      "I'm not sure what your favorite color is. You can tell me your favorite "
                              + "color by saying, my favorite color is red";
          }
  
          return getSpeechletResponse(speechText, repromptText, true);
      }
  
      /**
       * Creates a {@code SpeechletResponse} for the intent and get the user's favorite color from the
       * Session.
       *
       * @param intent
       *            intent for the request
       * @return SpeechletResponse spoken and visual response for the intent
       */
      private SpeechletResponse getColorFromSession(final Intent intent, final Session session) {
          String speechText;
          boolean isAskResponse = false;
  
          // Get the user's favorite color from the session.
          String favoriteColor = (String) session.getAttribute(COLOR_KEY);
  
          // Check to make sure user's favorite color is set in the session.
          if (StringUtils.isNotEmpty(favoriteColor)) {
              speechText = String.format("Your favorite color is %s. Goodbye.", favoriteColor);
          } else {
              // Since the user's favorite color is not set render an error message.
              speechText =
                      "I'm not sure what your favorite color is. You can say, my favorite color is "
                              + "red";
              isAskResponse = true;
          }
  
          return getSpeechletResponse(speechText, speechText, isAskResponse);
      }
  
      /**
       * Returns a Speechlet response for a speech and reprompt text.
       */
      private SpeechletResponse getSpeechletResponse(String speechText, String repromptText,
              boolean isAskResponse) {
          // Create the Simple card content.
          SimpleCard card = new SimpleCard();
          card.setTitle("Session");
          card.setContent(speechText);
  
          // Create the plain text output.
          PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
          speech.setText(speechText);
  
          if (isAskResponse) {
              // Create reprompt
              PlainTextOutputSpeech repromptSpeech = new PlainTextOutputSpeech();
              repromptSpeech.setText(repromptText);
              Reprompt reprompt = new Reprompt();
              reprompt.setOutputSpeech(repromptSpeech);
  
              return SpeechletResponse.newAskResponse(speech, reprompt, card);
  
          } else {
              return SpeechletResponse.newTellResponse(speech, card);
          }
      }
  }
  