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 com.fasterxml.jackson.core.JsonProcessingException;
019import com.fasterxml.jackson.databind.ObjectMapper;
020import com.vonage.client.VonageUnexpectedException;
021import com.vonage.client.voice.ncco.Action;
022
023import javax.servlet.http.HttpServletRequest;
024import java.util.ArrayList;
025import java.util.List;
026
027/**
028 * Encapsulates a set of NCCO objects for driving the Vonage Voice API.
029 * <p>
030 * This would usually be returned by {@link AbstractAnswerServlet#handleRequest(HttpServletRequest)}, which serializes
031 * it correctly for the Voice API. {@link NccoResponseBuilder} provides a fluent interface for constructing instances
032 * of this class.
033 */
034public class NccoResponse {
035    // This object has been purposefully designed to be relatively opaque, as
036    // the internal structure of this response may become more complex, and so
037    // we don't want users to become dependent on it being a simple list of
038    // Ncco objects.
039
040    private List<Action> actionList;
041
042    public NccoResponse() {
043        actionList = new ArrayList<>();
044    }
045
046    public void appendNcco(Action action) {
047        this.actionList.add(action);
048    }
049
050    public String toJson() {
051        try {
052            return new ObjectMapper().writeValueAsString(actionList);
053        } catch (JsonProcessingException e) {
054            throw new VonageUnexpectedException("Failed to serialize NccoResponse object.", e);
055        }
056    }
057}