001/*
002 * Copyright (c) 2011-2017 Nexmo Inc
003 *
004 * Permission is hereby granted, free of charge, to any person obtaining a copy
005 * of this software and associated documentation files (the "Software"), to deal
006 * in the Software without restriction, including without limitation the rights
007 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
008 * copies of the Software, and to permit persons to whom the Software is
009 * furnished to do so, subject to the following conditions:
010 *
011 * The above copyright notice and this permission notice shall be included in
012 * all copies or substantial portions of the Software.
013 *
014 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
015 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
016 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
017 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
018 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
019 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
020 * THE SOFTWARE.
021 */
022package com.nexmo.client;
023
024import com.nexmo.client.auth.AuthMethod;
025import org.apache.commons.logging.Log;
026import org.apache.commons.logging.LogFactory;
027import org.apache.http.HttpEntity;
028import org.apache.http.HttpEntityEnclosingRequest;
029import org.apache.http.HttpResponse;
030import org.apache.http.client.HttpClient;
031import org.apache.http.client.entity.UrlEncodedFormEntity;
032import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
033import org.apache.http.client.methods.HttpUriRequest;
034import org.apache.http.client.methods.RequestBuilder;
035import org.apache.http.util.EntityUtils;
036
037import java.io.IOException;
038import java.io.UnsupportedEncodingException;
039import java.nio.charset.Charset;
040import java.util.Collections;
041import java.util.HashSet;
042import java.util.Set;
043
044/**
045 * Abstract class to assist in implementing a call against a REST endpoint.
046 * <p>
047 * Concrete implementations must implement {@link #makeRequest(Object)} to construct a {@link RequestBuilder} from the
048 * provided parameterized request object, and {@link #parseResponse(HttpResponse)} to construct the parameterized {@link
049 * HttpResponse} object.
050 * <p>
051 * The REST call is executed by calling {@link #execute(Object)}.
052 *
053 * @param <RequestT> The type of the method-specific request object that will be used to construct an HTTP request
054 * @param <ResultT>  The type of method-specific response object which will be constructed from the returned HTTP
055 *                   response
056 */
057public abstract class AbstractMethod<RequestT, ResultT> implements Method<RequestT, ResultT> {
058    private static final Log LOG = LogFactory.getLog(AbstractMethod.class);
059
060    protected final HttpWrapper httpWrapper;
061    private Set<Class> acceptable;
062
063    public AbstractMethod(HttpWrapper httpWrapper) {
064        this.httpWrapper = httpWrapper;
065    }
066
067    /**
068     * Execute the REST call represented by this method object.
069     *
070     * @param request A RequestT representing input to the REST call to be made
071     *
072     * @return A ResultT representing the response from the executed REST call
073     *
074     * @throws NexmoClientException if there is a problem parsing the HTTP response
075     */
076    public ResultT execute(RequestT request) throws NexmoResponseParseException, NexmoClientException {
077        try {
078            RequestBuilder requestBuilder = applyAuth(makeRequest(request));
079            HttpUriRequest httpRequest = requestBuilder.build();
080
081            // If we have a URL Encoded form entity, we may need to regenerate it as UTF-8
082            // due to a bug (or two!) in RequestBuilder:
083            //
084            // This fix can be removed when HttpClient is upgraded to 4.5, although 4.5 also
085            // has a bug where RequestBuilder.put(uri) and RequestBuilder.post(uri) use the
086            // wrong encoding, whereas RequestBuilder.put().setUri(uri) uses UTF-8.
087            // - MS 2017-04-12
088            if (httpRequest instanceof HttpEntityEnclosingRequest) {
089                HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) httpRequest;
090                HttpEntity entity = entityRequest.getEntity();
091                if (entity instanceof UrlEncodedFormEntity) {
092                    entityRequest.setEntity(new UrlEncodedFormEntity(requestBuilder.getParameters(),
093                            Charset.forName("UTF-8")
094                    ));
095                }
096            }
097            LOG.debug("Request: " + httpRequest);
098            if (LOG.isDebugEnabled() && httpRequest instanceof HttpEntityEnclosingRequestBase) {
099                HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) httpRequest;
100                LOG.debug(EntityUtils.toString(enclosingRequest.getEntity()));
101            }
102            HttpResponse response = this.httpWrapper.getHttpClient().execute(httpRequest);
103            return parseResponse(response);
104        } catch (UnsupportedEncodingException uee) {
105            throw new NexmoUnexpectedException("UTF-8 encoding is not supported by this JVM.", uee);
106        } catch (IOException io) {
107            throw new NexmoResponseParseException("Unable to parse response.", io);
108        }
109    }
110
111    /**
112     * Apply an appropriate authentication method (specified by {@link #getAcceptableAuthMethods()} to the provided
113     * {@link RequestBuilder}, and return the result.
114     *
115     * @param request A RequestBuilder which has not yet had authentication information applied
116     *
117     * @return A RequestBuilder with appropriate authentication information applied (may or not be the same instance as
118     * <pre>request</pre>)
119     *
120     * @throws NexmoClientException If no appropriate {@link AuthMethod} is available
121     */
122    protected RequestBuilder applyAuth(RequestBuilder request) throws NexmoClientException {
123        return getAuthMethod(getAcceptableAuthMethods()).apply(request);
124    }
125
126    /**
127     * Utility method for obtaining an appropriate {@link AuthMethod} for this call.
128     *
129     * @param acceptableAuthMethods an array of classes, representing authentication methods that are acceptable for
130     *                              this endpoint
131     *
132     * @return An AuthMethod created from one of the provided acceptableAuthMethods.
133     *
134     * @throws NexmoClientException If no AuthMethod is available from the provided array of acceptableAuthMethods.
135     */
136    protected AuthMethod getAuthMethod(Class[] acceptableAuthMethods) throws NexmoClientException {
137        if (acceptable == null) {
138            this.acceptable = new HashSet<>();
139            Collections.addAll(acceptable, acceptableAuthMethods);
140        }
141
142        return this.httpWrapper.getAuthCollection().getAcceptableAuthMethod(acceptable);
143    }
144
145    public void setHttpClient(HttpClient client) {
146        this.httpWrapper.setHttpClient(client);
147    }
148
149    protected abstract Class[] getAcceptableAuthMethods();
150
151    /**
152     * Construct and return a RequestBuilder instance from the provided request.
153     *
154     * @param request A RequestT representing input to the REST call to be made
155     *
156     * @return A ResultT representing the response from the executed REST call
157     *
158     * @throws UnsupportedEncodingException if UTF-8 encoding is not supported by the JVM
159     */
160    public abstract RequestBuilder makeRequest(RequestT request) throws UnsupportedEncodingException;
161
162    /**
163     * Construct a ResultT representing the contents of the HTTP response returned from the Nexmo Voice API.
164     *
165     * @param response An HttpResponse returned from the Nexmo Voice API
166     *
167     * @return A ResultT type representing the result of the REST call
168     *
169     * @throws IOException if a problem occurs parsing the response
170     */
171    public abstract ResultT parseResponse(HttpResponse response) throws IOException;
172}