co.tuzza.clicksend4j.client.ClickSendSmsClient.java Source code

Java tutorial

Introduction

Here is the source code for co.tuzza.clicksend4j.client.ClickSendSmsClient.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package co.tuzza.clicksend4j.client;

import co.tuzza.clicksend4j.http.HttpClientUtils;
import co.tuzza.clicksend4j.utils.Definitions;
import co.tuzza.clicksend4j.utils.JsonParser;
import co.tuzza.clicksend4j.utils.SMS;
import co.tuzza.clicksend4j.utils.SmsResult;
import co.tuzza.clicksend4j.utils.SmsResults;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.message.BasicNameValuePair;

/**
 *
 * @author dylan
 */
public class ClickSendSmsClient {

    private static final Log log = LogFactory.getLog(ClickSendSmsClient.class);

    private final String authHeader;
    private final int connectionTimeout;
    private final int socketTimeout;
    private final boolean useSsl;
    private final String baseUrl;

    private HttpClient httpClient = null;

    /**
     * Initialize a new ClickSendSmsClient instance that will communicate using
     * the supplied credentials.
     *
     * @param apiUsername Your ClickSend account username
     * @param apiPassword Your ClickSend account api password
     * @throws java.lang.Exception
     */
    public ClickSendSmsClient(final String apiUsername, final String apiPassword) throws Exception {
        this(apiUsername, apiPassword, true, Definitions.DEFAULT_CONNECTION_TIMEOUT,
                Definitions.DEFAULT_SOCKET_TIMEOUT);
    }

    /**
     * Initialize a new ClickSendSmsClient instance that will communicate using
     * the supplied credentials, and will use the supplied connection and read
     * timeout values.
     *
     * @param apiUsername Your ClickSend account username
     * @param apiPassword Your ClickSend account api password
     * @param connectionTimeout over-ride the default connection timeout with
     * this value (in milliseconds)
     * @param socketTimeout over-ride the default read-timeout with this value
     * (in milliseconds)
     * @throws java.lang.Exception
     */
    public ClickSendSmsClient(final String apiUsername, final String apiPassword, final int connectionTimeout,
            final int socketTimeout) throws Exception {
        this(apiUsername, apiPassword, true, connectionTimeout, socketTimeout);
    }

    /**
     * Initialize a new ClickSendSmsClient instance that will communicate using
     * the supplied credentials, and will use the supplied connection and read
     * timeout values.<br>
     *
     * @param apiUsername Your ClickSend account username
     * @param apiPassword Your ClickSend account api password
     * @param connectionTimeout over-ride the default connection timeout with
     * this value (in milliseconds)
     * @param socketTimeout over-ride the default read-timeout with this value
     * (in milliseconds)
     * @param useSsl do we use a SSL / HTTPS connection for submitting requests
     * @throws java.lang.Exception
     */
    public ClickSendSmsClient(final String apiUsername, final String apiPassword, boolean useSsl,
            final int connectionTimeout, final int socketTimeout) throws Exception {
        this.connectionTimeout = connectionTimeout;
        this.socketTimeout = socketTimeout;
        this.useSsl = useSsl;

        if (this.useSsl) {
            this.baseUrl = Definitions.BASE_URL_SECURE;
        } else {
            this.baseUrl = Definitions.BASE_URL_NONSECURE;
        }

        this.authHeader = Base64.encodeBase64String((apiUsername + ":" + apiPassword).getBytes("UTF-8"));

    }

    public SmsResults sendSms(SMS sms) throws Exception {
        List<NameValuePair> params = parseSMS(sms);
        String response = null;
        for (int pass = 1; pass <= 3; pass++) {
            HttpUriRequest method;
            HttpPost httpPost = new HttpPost(baseUrl + Definitions.SEND_SMS_URL_JSON);
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            httpPost.setHeader("Authorization", "Basic " + this.authHeader);
            method = httpPost;
            String url = baseUrl + "?" + URLEncodedUtils.format(params, "utf-8");
            try {
                if (httpClient == null) {
                    httpClient = HttpClientUtils.getInstance(connectionTimeout, socketTimeout).getHttpClient();
                }
                HttpResponse httpResponse = httpClient.execute(method);
                int status = httpResponse.getStatusLine().getStatusCode();
                if (status != 200) {
                    if (status == 401) {
                        throw new Exception("got a 401 response from ClickSend-HTTP for url [ " + url
                                + " ] - Authorisation failed");
                    }
                    throw new Exception("got a non-200 response [ " + status + " ] from ClickSend-HTTP for url [ "
                            + url + " ] ");
                }
                response = new BasicResponseHandler().handleResponse(httpResponse);
                log.info("SMS SEND CLICKSEND-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
                break;
            } catch (Exception ex) {
                method.abort();
                log.info("communication failure", ex);
                String exceptionMsg = ex.getMessage();
                if (exceptionMsg.contains("Read timed out")) {
                    log.info(
                            "we're still connected, but the target did not respond in a timely manner ..  drop ...");
                } else {
                    if (pass < 2) {
                        log.info("... re-establish http client ...");
                        this.httpClient = null;
                        continue;
                    }
                }
                SmsResults results = new SmsResults();
                SmsResult smsResult = new SmsResult();

                smsResult.setResult("LOCAL500");
                smsResult.setErrorText("Failed to communicate with CLICKSEND-HTTP url [ " + url + " ] ..." + ex);
                smsResult.setStatusDescription(Definitions.SEND_SMS_RESPONSE_CODES_MAP.get("LOCAL500"));

                results.addSmsResult(smsResult);
                return results;
            }
        }

        JsonParser jsonParser = new JsonParser();
        SmsResults smsResults = jsonParser.parseJson(response, SmsResults.class);

        return smsResults;
    }

    private List<NameValuePair> parseSMS(SMS sms) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("method", Definitions.API_TYPE));
        params.add(new BasicNameValuePair("to", sms.getTo()));
        params.add(new BasicNameValuePair("message", sms.getMessage()));

        if (sms.getSenderId() != null) {
            params.add(new BasicNameValuePair("senderid", sms.getSenderId()));
        }

        if (sms.getSchedule() != null) {
            params.add(new BasicNameValuePair("schedule", sms.getSchedule()));
        }

        if (sms.getCustomString() != null) {
            params.add(new BasicNameValuePair("customstring", sms.getCustomString()));
        }

        if (sms.getReturnURL() != null) {
            params.add(new BasicNameValuePair("return", sms.getReturnURL()));
        }

        return params;
    }

}