All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.bandwidth.webrtc.controllers.APIController Maven / Gradle / Ivy

Go to download

The official client SDK for Bandwidth's Voice, Messaging, MFA, and WebRTC APIs

There is a newer version: 12.0.0
Show newest version
/*
 * BandwidthLib
 *
 * This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ).
 */

package com.bandwidth.webrtc.controllers;

import com.bandwidth.ApiHelper;
import com.bandwidth.AuthManager;
import com.bandwidth.Configuration;
import com.bandwidth.Server;
import com.bandwidth.controllers.BaseController;
import com.bandwidth.exceptions.ApiException;
import com.bandwidth.http.Headers;
import com.bandwidth.http.client.HttpCallback;
import com.bandwidth.http.client.HttpClient;
import com.bandwidth.http.client.HttpContext;
import com.bandwidth.http.request.HttpRequest;
import com.bandwidth.http.response.ApiResponse;
import com.bandwidth.http.response.HttpResponse;
import com.bandwidth.http.response.HttpStringResponse;
import com.bandwidth.webrtc.exceptions.ErrorException;
import com.bandwidth.webrtc.models.AccountsParticipantsResponse;
import com.bandwidth.webrtc.models.Participant;
import com.bandwidth.webrtc.models.Session;
import com.bandwidth.webrtc.models.Subscriptions;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.io.IOException;
import java.util.AbstractMap.SimpleEntry;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * This class lists all the endpoints of the groups.
 */
public final class APIController extends BaseController {

    /**
     * Initializes the controller.
     * @param config    Configurations added in client.
     * @param httpClient    Send HTTP requests and read the responses.
     * @param authManagers    Apply authorization to requests.
     */
    public APIController(Configuration config, HttpClient httpClient,
            Map authManagers) {
        super(config, httpClient, authManagers);
    }

    /**
     * Initializes the controller with HTTPCallback.
     * @param config    Configurations added in client.
     * @param httpClient    Send HTTP requests and read the responses.
     * @param authManagers    Apply authorization to requests.
     * @param httpCallback    Callback to be called before and after the HTTP call.
     */
    public APIController(Configuration config, HttpClient httpClient,
            Map authManagers, HttpCallback httpCallback) {
        super(config, httpClient, authManagers, httpCallback);
    }

    /**
     * Create a new participant under this account. Participants are idempotent, so relevant
     * parameters must be set in this function if desired.
     * @param  accountId  Required parameter: Account ID
     * @param  body  Optional parameter: Participant parameters
     * @return    Returns the AccountsParticipantsResponse wrapped in ApiResponse response from the API call
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse createParticipant(
            final String accountId,
            final Participant body) throws ApiException, IOException {
        HttpRequest request = buildCreateParticipantRequest(accountId, body);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleCreateParticipantResponse(context);
    }

    /**
     * Create a new participant under this account. Participants are idempotent, so relevant
     * parameters must be set in this function if desired.
     * @param  accountId  Required parameter: Account ID
     * @param  body  Optional parameter: Participant parameters
     * @return    Returns the AccountsParticipantsResponse wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> createParticipantAsync(
            final String accountId,
            final Participant body) {
        return makeHttpCallAsync(() -> buildCreateParticipantRequest(accountId, body),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleCreateParticipantResponse(context));
    }

    /**
     * Builds the HttpRequest object for createParticipant.
     */
    private HttpRequest buildCreateParticipantRequest(
            final String accountId,
            final Participant body) throws JsonProcessingException {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/participants");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("accept", "application/json");
        headers.add("content-type", "application/json");

        //prepare and invoke the API call request to fetch the response
        String bodyJson = ApiHelper.serialize(body);
        HttpRequest request = getClientInstance().postBody(queryBuilder, headers, null, bodyJson);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for createParticipant.
     * @return An object of type AccountsParticipantsResponse
     */
    private ApiResponse handleCreateParticipantResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 400) {
            throw new ApiException("Bad Request", context);
        }
        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        //extract result from the http response
        String responseBody = ((HttpStringResponse) response).getBody();
        AccountsParticipantsResponse result = ApiHelper.deserialize(responseBody,
                AccountsParticipantsResponse.class);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), result);
    }

    /**
     * Get participant by ID.
     * @param  accountId  Required parameter: Account ID
     * @param  participantId  Required parameter: Participant ID
     * @return    Returns the Participant wrapped in ApiResponse response from the API call
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse getParticipant(
            final String accountId,
            final String participantId) throws ApiException, IOException {
        HttpRequest request = buildGetParticipantRequest(accountId, participantId);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleGetParticipantResponse(context);
    }

    /**
     * Get participant by ID.
     * @param  accountId  Required parameter: Account ID
     * @param  participantId  Required parameter: Participant ID
     * @return    Returns the Participant wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> getParticipantAsync(
            final String accountId,
            final String participantId) {
        return makeHttpCallAsync(() -> buildGetParticipantRequest(accountId, participantId),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleGetParticipantResponse(context));
    }

    /**
     * Builds the HttpRequest object for getParticipant.
     */
    private HttpRequest buildGetParticipantRequest(
            final String accountId,
            final String participantId) {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/participants/{participantId}");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        templateParameters.put("participantId",
                new SimpleEntry(participantId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("accept", "application/json");

        //prepare and invoke the API call request to fetch the response
        HttpRequest request = getClientInstance().get(queryBuilder, headers, null, null);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for getParticipant.
     * @return An object of type Participant
     */
    private ApiResponse handleGetParticipantResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if (responseCode == 404) {
            throw new ApiException("Not Found", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        //extract result from the http response
        String responseBody = ((HttpStringResponse) response).getBody();
        Participant result = ApiHelper.deserialize(responseBody,
                Participant.class);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), result);
    }

    /**
     * Delete participant by ID.
     * @param  accountId  Required parameter: Account ID
     * @param  participantId  Required parameter: Example:
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse deleteParticipant(
            final String accountId,
            final String participantId) throws ApiException, IOException {
        HttpRequest request = buildDeleteParticipantRequest(accountId, participantId);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleDeleteParticipantResponse(context);
    }

    /**
     * Delete participant by ID.
     * @param  accountId  Required parameter: Account ID
     * @param  participantId  Required parameter: Example:
     * @return    Returns the Void wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> deleteParticipantAsync(
            final String accountId,
            final String participantId) {
        return makeHttpCallAsync(() -> buildDeleteParticipantRequest(accountId, participantId),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleDeleteParticipantResponse(context));
    }

    /**
     * Builds the HttpRequest object for deleteParticipant.
     */
    private HttpRequest buildDeleteParticipantRequest(
            final String accountId,
            final String participantId) {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/participants/{participantId}");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        templateParameters.put("participantId",
                new SimpleEntry(participantId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);

        //prepare and invoke the API call request to fetch the response
        HttpRequest request = getClientInstance().delete(queryBuilder, headers, null, null);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for deleteParticipant.
     * @return An object of type void
     */
    private ApiResponse handleDeleteParticipantResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if (responseCode == 404) {
            throw new ApiException("Not Found", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), null);
    }

    /**
     * Create a new session. Sessions are idempotent, so relevant parameters must be set in this
     * function if desired.
     * @param  accountId  Required parameter: Account ID
     * @param  body  Optional parameter: Session parameters
     * @return    Returns the Session wrapped in ApiResponse response from the API call
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse createSession(
            final String accountId,
            final Session body) throws ApiException, IOException {
        HttpRequest request = buildCreateSessionRequest(accountId, body);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleCreateSessionResponse(context);
    }

    /**
     * Create a new session. Sessions are idempotent, so relevant parameters must be set in this
     * function if desired.
     * @param  accountId  Required parameter: Account ID
     * @param  body  Optional parameter: Session parameters
     * @return    Returns the Session wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> createSessionAsync(
            final String accountId,
            final Session body) {
        return makeHttpCallAsync(() -> buildCreateSessionRequest(accountId, body),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleCreateSessionResponse(context));
    }

    /**
     * Builds the HttpRequest object for createSession.
     */
    private HttpRequest buildCreateSessionRequest(
            final String accountId,
            final Session body) throws JsonProcessingException {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/sessions");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("accept", "application/json");
        headers.add("content-type", "application/json");

        //prepare and invoke the API call request to fetch the response
        String bodyJson = ApiHelper.serialize(body);
        HttpRequest request = getClientInstance().postBody(queryBuilder, headers, null, bodyJson);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for createSession.
     * @return An object of type Session
     */
    private ApiResponse handleCreateSessionResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 400) {
            throw new ApiException("Bad Request", context);
        }
        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        //extract result from the http response
        String responseBody = ((HttpStringResponse) response).getBody();
        Session result = ApiHelper.deserialize(responseBody,
                Session.class);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), result);
    }

    /**
     * Get session by ID.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @return    Returns the Session wrapped in ApiResponse response from the API call
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse getSession(
            final String accountId,
            final String sessionId) throws ApiException, IOException {
        HttpRequest request = buildGetSessionRequest(accountId, sessionId);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleGetSessionResponse(context);
    }

    /**
     * Get session by ID.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @return    Returns the Session wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> getSessionAsync(
            final String accountId,
            final String sessionId) {
        return makeHttpCallAsync(() -> buildGetSessionRequest(accountId, sessionId),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleGetSessionResponse(context));
    }

    /**
     * Builds the HttpRequest object for getSession.
     */
    private HttpRequest buildGetSessionRequest(
            final String accountId,
            final String sessionId) {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/sessions/{sessionId}");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        templateParameters.put("sessionId",
                new SimpleEntry(sessionId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("accept", "application/json");

        //prepare and invoke the API call request to fetch the response
        HttpRequest request = getClientInstance().get(queryBuilder, headers, null, null);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for getSession.
     * @return An object of type Session
     */
    private ApiResponse handleGetSessionResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if (responseCode == 404) {
            throw new ApiException("Not Found", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        //extract result from the http response
        String responseBody = ((HttpStringResponse) response).getBody();
        Session result = ApiHelper.deserialize(responseBody,
                Session.class);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), result);
    }

    /**
     * Delete session by ID.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse deleteSession(
            final String accountId,
            final String sessionId) throws ApiException, IOException {
        HttpRequest request = buildDeleteSessionRequest(accountId, sessionId);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleDeleteSessionResponse(context);
    }

    /**
     * Delete session by ID.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @return    Returns the Void wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> deleteSessionAsync(
            final String accountId,
            final String sessionId) {
        return makeHttpCallAsync(() -> buildDeleteSessionRequest(accountId, sessionId),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleDeleteSessionResponse(context));
    }

    /**
     * Builds the HttpRequest object for deleteSession.
     */
    private HttpRequest buildDeleteSessionRequest(
            final String accountId,
            final String sessionId) {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/sessions/{sessionId}");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        templateParameters.put("sessionId",
                new SimpleEntry(sessionId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);

        //prepare and invoke the API call request to fetch the response
        HttpRequest request = getClientInstance().delete(queryBuilder, headers, null, null);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for deleteSession.
     * @return An object of type void
     */
    private ApiResponse handleDeleteSessionResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if (responseCode == 404) {
            throw new ApiException("Not Found", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), null);
    }

    /**
     * List participants in a session.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @return    Returns the List of Participant wrapped in ApiResponse response from the API call
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse> listSessionParticipants(
            final String accountId,
            final String sessionId) throws ApiException, IOException {
        HttpRequest request = buildListSessionParticipantsRequest(accountId, sessionId);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleListSessionParticipantsResponse(context);
    }

    /**
     * List participants in a session.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @return    Returns the List of Participant wrapped in ApiResponse response from the API call
     */
    public CompletableFuture>> listSessionParticipantsAsync(
            final String accountId,
            final String sessionId) {
        return makeHttpCallAsync(() -> buildListSessionParticipantsRequest(accountId, sessionId),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleListSessionParticipantsResponse(context));
    }

    /**
     * Builds the HttpRequest object for listSessionParticipants.
     */
    private HttpRequest buildListSessionParticipantsRequest(
            final String accountId,
            final String sessionId) {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/sessions/{sessionId}/participants");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        templateParameters.put("sessionId",
                new SimpleEntry(sessionId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("accept", "application/json");

        //prepare and invoke the API call request to fetch the response
        HttpRequest request = getClientInstance().get(queryBuilder, headers, null, null);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for listSessionParticipants.
     * @return An object of type List of Participant
     */
    private ApiResponse> handleListSessionParticipantsResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if (responseCode == 404) {
            throw new ApiException("Not Found", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        //extract result from the http response
        String responseBody = ((HttpStringResponse) response).getBody();
        List result = ApiHelper.deserializeArray(responseBody,
                Participant[].class);
        return new ApiResponse>(response.getStatusCode(), response.getHeaders(), result);
    }

    /**
     * Add a participant to a session. Subscriptions can optionally be provided as part of this
     * call.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @param  participantId  Required parameter: Participant ID
     * @param  body  Optional parameter: Subscriptions the participant should be created with
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse addParticipantToSession(
            final String accountId,
            final String sessionId,
            final String participantId,
            final Subscriptions body) throws ApiException, IOException {
        HttpRequest request = buildAddParticipantToSessionRequest(accountId, sessionId,
                participantId, body);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleAddParticipantToSessionResponse(context);
    }

    /**
     * Add a participant to a session. Subscriptions can optionally be provided as part of this
     * call.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @param  participantId  Required parameter: Participant ID
     * @param  body  Optional parameter: Subscriptions the participant should be created with
     * @return    Returns the Void wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> addParticipantToSessionAsync(
            final String accountId,
            final String sessionId,
            final String participantId,
            final Subscriptions body) {
        return makeHttpCallAsync(() -> buildAddParticipantToSessionRequest(accountId, sessionId,
                participantId, body),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleAddParticipantToSessionResponse(context));
    }

    /**
     * Builds the HttpRequest object for addParticipantToSession.
     */
    private HttpRequest buildAddParticipantToSessionRequest(
            final String accountId,
            final String sessionId,
            final String participantId,
            final Subscriptions body) throws JsonProcessingException {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/sessions/{sessionId}/participants/{participantId}");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        templateParameters.put("sessionId",
                new SimpleEntry(sessionId, false));
        templateParameters.put("participantId",
                new SimpleEntry(participantId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("content-type", "application/json");

        //prepare and invoke the API call request to fetch the response
        String bodyJson = ApiHelper.serialize(body);
        HttpRequest request = getClientInstance().putBody(queryBuilder, headers, null, bodyJson);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for addParticipantToSession.
     * @return An object of type void
     */
    private ApiResponse handleAddParticipantToSessionResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if (responseCode == 404) {
            throw new ApiException("Not Found", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), null);
    }

    /**
     * Remove a participant from a session. This will automatically remove any subscriptions the
     * participant has associated with this session.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @param  participantId  Required parameter: Participant ID
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse removeParticipantFromSession(
            final String accountId,
            final String sessionId,
            final String participantId) throws ApiException, IOException {
        HttpRequest request = buildRemoveParticipantFromSessionRequest(accountId, sessionId,
                participantId);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleRemoveParticipantFromSessionResponse(context);
    }

    /**
     * Remove a participant from a session. This will automatically remove any subscriptions the
     * participant has associated with this session.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @param  participantId  Required parameter: Participant ID
     * @return    Returns the Void wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> removeParticipantFromSessionAsync(
            final String accountId,
            final String sessionId,
            final String participantId) {
        return makeHttpCallAsync(() -> buildRemoveParticipantFromSessionRequest(accountId,
                sessionId, participantId),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleRemoveParticipantFromSessionResponse(context));
    }

    /**
     * Builds the HttpRequest object for removeParticipantFromSession.
     */
    private HttpRequest buildRemoveParticipantFromSessionRequest(
            final String accountId,
            final String sessionId,
            final String participantId) {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/sessions/{sessionId}/participants/{participantId}");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        templateParameters.put("sessionId",
                new SimpleEntry(sessionId, false));
        templateParameters.put("participantId",
                new SimpleEntry(participantId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);

        //prepare and invoke the API call request to fetch the response
        HttpRequest request = getClientInstance().delete(queryBuilder, headers, null, null);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for removeParticipantFromSession.
     * @return An object of type void
     */
    private ApiResponse handleRemoveParticipantFromSessionResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if (responseCode == 404) {
            throw new ApiException("Not Found", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), null);
    }

    /**
     * Get a participant's subscriptions.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @param  participantId  Required parameter: Participant ID
     * @return    Returns the Subscriptions wrapped in ApiResponse response from the API call
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse getParticipantSubscriptions(
            final String accountId,
            final String sessionId,
            final String participantId) throws ApiException, IOException {
        HttpRequest request = buildGetParticipantSubscriptionsRequest(accountId, sessionId,
                participantId);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleGetParticipantSubscriptionsResponse(context);
    }

    /**
     * Get a participant's subscriptions.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @param  participantId  Required parameter: Participant ID
     * @return    Returns the Subscriptions wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> getParticipantSubscriptionsAsync(
            final String accountId,
            final String sessionId,
            final String participantId) {
        return makeHttpCallAsync(() -> buildGetParticipantSubscriptionsRequest(accountId, sessionId,
                participantId),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleGetParticipantSubscriptionsResponse(context));
    }

    /**
     * Builds the HttpRequest object for getParticipantSubscriptions.
     */
    private HttpRequest buildGetParticipantSubscriptionsRequest(
            final String accountId,
            final String sessionId,
            final String participantId) {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/sessions/{sessionId}/participants/{participantId}/subscriptions");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        templateParameters.put("sessionId",
                new SimpleEntry(sessionId, false));
        templateParameters.put("participantId",
                new SimpleEntry(participantId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("accept", "application/json");

        //prepare and invoke the API call request to fetch the response
        HttpRequest request = getClientInstance().get(queryBuilder, headers, null, null);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for getParticipantSubscriptions.
     * @return An object of type Subscriptions
     */
    private ApiResponse handleGetParticipantSubscriptionsResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if (responseCode == 404) {
            throw new ApiException("Not Found", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        //extract result from the http response
        String responseBody = ((HttpStringResponse) response).getBody();
        Subscriptions result = ApiHelper.deserialize(responseBody,
                Subscriptions.class);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), result);
    }

    /**
     * Update a participant's subscriptions. This is a full update that will replace the
     * participant's subscriptions. First call `getParticipantSubscriptions` if you need the current
     * subscriptions. Call this function with no `Subscriptions` object to remove all subscriptions.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @param  participantId  Required parameter: Participant ID
     * @param  body  Optional parameter: Initial state
     * @throws    ApiException    Represents error response from the server.
     * @throws    IOException    Signals that an I/O exception of some sort has occurred.
     */
    public ApiResponse updateParticipantSubscriptions(
            final String accountId,
            final String sessionId,
            final String participantId,
            final Subscriptions body) throws ApiException, IOException {
        HttpRequest request = buildUpdateParticipantSubscriptionsRequest(accountId, sessionId,
                participantId, body);
        authManagers.get("webRtc").apply(request);

        HttpResponse response = getClientInstance().execute(request, false);
        HttpContext context = new HttpContext(request, response);

        return handleUpdateParticipantSubscriptionsResponse(context);
    }

    /**
     * Update a participant's subscriptions. This is a full update that will replace the
     * participant's subscriptions. First call `getParticipantSubscriptions` if you need the current
     * subscriptions. Call this function with no `Subscriptions` object to remove all subscriptions.
     * @param  accountId  Required parameter: Account ID
     * @param  sessionId  Required parameter: Session ID
     * @param  participantId  Required parameter: Participant ID
     * @param  body  Optional parameter: Initial state
     * @return    Returns the Void wrapped in ApiResponse response from the API call
     */
    public CompletableFuture> updateParticipantSubscriptionsAsync(
            final String accountId,
            final String sessionId,
            final String participantId,
            final Subscriptions body) {
        return makeHttpCallAsync(() -> buildUpdateParticipantSubscriptionsRequest(accountId,
                sessionId, participantId, body),
            req -> authManagers.get("webRtc").applyAsync(req)
                .thenCompose(request -> getClientInstance()
                        .executeAsync(request, false)),
            context -> handleUpdateParticipantSubscriptionsResponse(context));
    }

    /**
     * Builds the HttpRequest object for updateParticipantSubscriptions.
     */
    private HttpRequest buildUpdateParticipantSubscriptionsRequest(
            final String accountId,
            final String sessionId,
            final String participantId,
            final Subscriptions body) throws JsonProcessingException {
        //the base uri for api requests
        String baseUri = config.getBaseUri(Server.WEBRTCDEFAULT);

        //prepare query string for API call
        final StringBuilder queryBuilder = new StringBuilder(baseUri
                + "/accounts/{accountId}/sessions/{sessionId}/participants/{participantId}/subscriptions");

        //process template parameters
        Map> templateParameters = new HashMap<>();
        templateParameters.put("accountId",
                new SimpleEntry(accountId, false));
        templateParameters.put("sessionId",
                new SimpleEntry(sessionId, false));
        templateParameters.put("participantId",
                new SimpleEntry(participantId, false));
        ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters);

        //load all headers for the outgoing API request
        Headers headers = new Headers();
        headers.add("user-agent", BaseController.userAgent);
        headers.add("content-type", "application/json");

        //prepare and invoke the API call request to fetch the response
        String bodyJson = ApiHelper.serialize(body);
        HttpRequest request = getClientInstance().putBody(queryBuilder, headers, null, bodyJson);

        // Invoke the callback before request if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onBeforeRequest(request);
        }

        return request;
    }

    /**
     * Processes the response for updateParticipantSubscriptions.
     * @return An object of type void
     */
    private ApiResponse handleUpdateParticipantSubscriptionsResponse(
            HttpContext context) throws ApiException, IOException {
        HttpResponse response = context.getResponse();

        //invoke the callback after response if its not null
        if (getHttpCallback() != null) {
            getHttpCallback().onAfterResponse(context);
        }

        //Error handling using HTTP status codes
        int responseCode = response.getStatusCode();

        if (responseCode == 400) {
            throw new ApiException("Bad Request", context);
        }
        if (responseCode == 401) {
            throw new ApiException("Unauthorized", context);
        }
        if (responseCode == 403) {
            throw new ApiException("Access Denied", context);
        }
        if (responseCode == 404) {
            throw new ApiException("Not Found", context);
        }
        if ((responseCode < 200) || (responseCode > 208)) {
            throw new ErrorException("Unexpected Error", context);
        }
        //handle errors defined at the API level
        validateResponse(response, context);

        return new ApiResponse(response.getStatusCode(), response.getHeaders(), null);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy