001/*
002 *   Copyright 2020 Vonage
003 *
004 *   Licensed under the Apache License, Version 2.0 (the "License");
005 *   you may not use this file except in compliance with the License.
006 *   You may obtain a copy of the License at
007 *
008 *        http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *   Unless required by applicable law or agreed to in writing, software
011 *   distributed under the License is distributed on an "AS IS" BASIS,
012 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *   See the License for the specific language governing permissions and
014 *   limitations under the License.
015 */
016package com.vonage.client.voice.servlet;
017
018import javax.servlet.ServletException;
019import javax.servlet.http.HttpServlet;
020import javax.servlet.http.HttpServletRequest;
021import javax.servlet.http.HttpServletResponse;
022import java.io.IOException;
023
024/**
025 * Useful abstract HttpServlet for implementing NCCO callbacks.
026 * <p>
027 *     Implement {@link #handleRequest(HttpServletRequest)} to return an {@link NccoResponse} and this servlet will
028 *     ensure that the response is serialized correctly for the Vonage Voice API.
029 * </p>
030 */
031public abstract class AbstractAnswerServlet extends HttpServlet {
032    @Override
033    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
034        serializeNccoResponse(resp, this.handleRequest(req));
035    }
036
037    @Override
038    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
039        serializeNccoResponse(resp, this.handleRequest(req));
040    }
041
042    private void serializeNccoResponse(HttpServletResponse httpResponse, NccoResponse nccoResponse) throws IOException {
043        byte[] json = nccoResponse.toJson().getBytes("UTF-8");
044        httpResponse.setCharacterEncoding("UTF-8");
045        httpResponse.setContentType("application/json");
046        httpResponse.setContentLength(json.length);
047        httpResponse.getOutputStream().write(json);
048    }
049
050    /**
051     * Handle a request for NCCO instructions from the Vonage Voice API.
052     * <p>
053     * Implementations should return an NccoResponse object (most easily constructed using {@link NccoResponseBuilder}.
054     *
055     * @param request the HttpServletRequest parsed from the request made by the Vonage Voice API
056     * @return An NccoResponse containing Ncco instructions for the Vonage Voice API
057     */
058    protected abstract NccoResponse handleRequest(HttpServletRequest request);
059}