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.verify.endpoints;
023
024import com.nexmo.client.HttpWrapper;
025import com.nexmo.client.NexmoClientException;
026import com.nexmo.client.NexmoResponseParseException;
027import com.nexmo.client.auth.SignatureAuthMethod;
028import com.nexmo.client.auth.TokenAuthMethod;
029import com.nexmo.client.legacyutils.XmlParser;
030import com.nexmo.client.legacyutils.XmlUtil;
031import com.nexmo.client.verify.BaseResult;
032import com.nexmo.client.verify.CheckRequest;
033import com.nexmo.client.verify.CheckResult;
034import com.nexmo.client.voice.endpoints.AbstractMethod;
035import org.apache.commons.logging.Log;
036import org.apache.commons.logging.LogFactory;
037import org.apache.http.HttpResponse;
038import org.apache.http.client.methods.RequestBuilder;
039import org.apache.http.impl.client.BasicResponseHandler;
040import org.w3c.dom.Document;
041import org.w3c.dom.Element;
042import org.w3c.dom.Node;
043import org.w3c.dom.NodeList;
044
045import java.io.IOException;
046import java.io.UnsupportedEncodingException;
047
048/**
049 * @deprecated Relies on XML Endpoint, use {@link com.nexmo.client.verify.CheckMethod}
050 */
051@Deprecated
052public class VerifyCheckMethod extends AbstractMethod<CheckRequest, CheckResult> {
053    private static final Log log = LogFactory.getLog(VerifyCheckMethod.class);
054    private static final Class[] ALLOWED_AUTH_METHODS = new Class[]{SignatureAuthMethod.class, TokenAuthMethod.class};
055
056    private static final String DEFAULT_URI = "https://api.nexmo.com/verify/check/xml";
057
058    private XmlParser xmlParser = new XmlParser();
059    private String uri = DEFAULT_URI;
060
061    public VerifyCheckMethod(HttpWrapper httpWrapper) {
062        super(httpWrapper);
063    }
064
065    @Override
066    protected Class[] getAcceptableAuthMethods() {
067        return ALLOWED_AUTH_METHODS;
068    }
069
070    @Override
071    public RequestBuilder makeRequest(CheckRequest request) throws NexmoClientException, UnsupportedEncodingException {
072        if (request.getRequestId() == null || request.getCode() == null)
073            throw new IllegalArgumentException("request ID and code parameters are mandatory.");
074
075        RequestBuilder result = RequestBuilder.post(this.uri).addParameter("request_id", request.getRequestId())
076
077                .addParameter("code", request.getCode());
078        if (request.getIpAddress() != null) result.addParameter("ip_address", request.getIpAddress());
079
080        return result;
081    }
082
083    @Override
084    public CheckResult parseResponse(HttpResponse response) throws IOException {
085        String body = new BasicResponseHandler().handleResponse(response);
086        return parseCheckResponse(body);
087    }
088
089    private CheckResult parseCheckResponse(String response) throws NexmoResponseParseException {
090        Document doc = xmlParser.parseXml(response);
091
092        Element root = doc.getDocumentElement();
093        if (!"verify_response".equals(root.getNodeName()))
094            throw new NexmoResponseParseException("No valid response found [ " + response + "] ");
095
096        String eventId = null;
097        int status = -1;
098        float price = -1;
099        String currency = null;
100        String errorText = null;
101
102        NodeList fields = root.getChildNodes();
103        for (int i = 0; i < fields.getLength(); i++) {
104            Node node = fields.item(i);
105            if (node.getNodeType() != Node.ELEMENT_NODE) continue;
106
107            String name = node.getNodeName();
108            if ("event_id".equals(name)) {
109                eventId = XmlUtil.stringValue(node);
110            } else if ("status".equals(name)) {
111                String str = XmlUtil.stringValue(node);
112                try {
113                    if (str != null) status = Integer.parseInt(str);
114                } catch (NumberFormatException e) {
115                    log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
116                    status = BaseResult.STATUS_INTERNAL_ERROR;
117                }
118            } else if ("price".equals(name)) {
119                String str = XmlUtil.stringValue(node);
120                try {
121                    if (str != null) price = Float.parseFloat(str);
122                } catch (NumberFormatException e) {
123                    log.error("xml parser .. invalid value in <price> node [ " + str + " ] ");
124                }
125            } else if ("currency".equals(name)) {
126                currency = XmlUtil.stringValue(node);
127            } else if ("error_text".equals(name)) {
128                errorText = XmlUtil.stringValue(node);
129            }
130        }
131
132        if (status == -1) throw new NexmoResponseParseException("Xml Parser - did not find a <status> node");
133
134        // Is this a temporary error ?
135        boolean temporaryError = (status == BaseResult.STATUS_THROTTLED || status == BaseResult.STATUS_INTERNAL_ERROR);
136
137        return new CheckResult(status, eventId, price, currency, errorText, temporaryError);
138    }
139}