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

io.hypertrack.net.HyperTrackClient Maven / Gradle / Ivy

There is a newer version: 1.0.1
Show newest version
package io.hypertrack.net;

import com.google.gson.Gson;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
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.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Created by Arjun on 18/04/16.
 */

public class HyperTrackClient {
    private String endpoint = "https://app.hypertrack.io/api/v1";
    private String VERSION = "0.1.2";
    private String userAgent = "HyperTrack/v1 JavaBindings/" + VERSION;

    private HttpClient httpClient;
    private String publishableKey;
    private String secretKey;

    /**
     *
     * @param publishableKey
     * @param secretKey
     */
    public HyperTrackClient(final String publishableKey, final String secretKey) {
        this(publishableKey, secretKey, null);
    }

    public HyperTrackClient(final String publishableKey, final String secretKey,
                            final String endpoint) {
        this.publishableKey = publishableKey;
        this.secretKey = secretKey;

        if (endpoint != null) {
            this.endpoint = endpoint;
        }

        httpClient = HttpClients.createDefault();
    }

    public String request(final String path, final String method,
                          final Map data) throws Exception {
        Map params = paramsToString(data);
        HttpUriRequest request = setupRequest(path, method, params);
        HttpResponse response;
        try {
            response = httpClient.execute(request);

            if (validateResponse(response)) {
                HttpEntity entity = response.getEntity();
                String responseBody = "";

                if (entity != null) {
                    responseBody = EntityUtils.toString(entity, "UTF-8");
                }

                return responseBody;
            } else {
                throw HyperTrackException.parseResponse(response);
            }
        } catch (final ClientProtocolException e1) {
            throw new ClientProtocolException(e1);
        }
    }

    private HttpUriRequest setupRequest(String path, final String method,
                                        final Map params) {
        String normalizedPath = path.toLowerCase();
        StringBuilder sb = new StringBuilder();

        // If we are given a fully qualified uri then skip building the endpoint
        if (normalizedPath.startsWith("http://") || normalizedPath.startsWith("https://")) {
            sb.append(path);
        } else {
            sb.append(this.endpoint);

            if (!normalizedPath.startsWith("/")) {
                sb.append("/");
            }
            sb.append(path);
        }
        path = sb.toString();
        HttpUriRequest request = buildMethod(path, method, params);

        request.addHeader(new BasicHeader("Authorization", "token " + this.secretKey));
        request.addHeader(new BasicHeader("User-Agent", this.userAgent));
        request.addHeader(new BasicHeader("Accept", "application/json"));
        request.addHeader(new BasicHeader("Content-Type", "application/json"));
        request.addHeader(new BasicHeader("Accept-Charset", "utf-8"));

        return request;
    }

    private HttpUriRequest buildMethod(final String path, final String method,
                                       final Map params) {
        if (method.equalsIgnoreCase("GET")) {
            URI uri = buildUri(path, params);
            return new HttpGet(uri);
        } else if (method.equalsIgnoreCase("POST")) {
            URI uri = buildUri(path, null);
            StringEntity entity = buildEntityBody(params);
            HttpPost post = new HttpPost(uri);
            post.setEntity(entity);
            return post;
        } else {
            throw new IllegalArgumentException("Unknown HTTP method: " + method);
        }
    }

    private URI buildUri(final String path, final Map params) {
        StringBuilder sb = new StringBuilder();
        sb.append(path);

        if (params != null && params.size() > 0) {
            sb.append("?");
            List paramsList = getListFromMap(params);
            sb.append(URLEncodedUtils.format(paramsList, "UTF-8"));
        }

        URI uri;
        try {
            uri = new URI(sb.toString());
        } catch (final URISyntaxException e) {
            throw new IllegalStateException("Invalid uri", e);
        }

        return uri;
    }

    private StringEntity buildEntityBody(final Map params) {
        Gson gson = new Gson();
        String paramsJson = gson.toJson(params);
        try {
            return new StringEntity(paramsJson.toString());
        } catch (final UnsupportedEncodingException e) {
            throw new IllegalArgumentException("Invalid parameters", e);
        }
    }

    private ArrayList getListFromMap(Map params) {
        ArrayList paramsList = new ArrayList();
        for (Map.Entry entry : params.entrySet()) {
            NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
            paramsList.add(pair);
        }
        return paramsList;
    }

    private Map paramsToString(Map params) {
        if (params != null) {
            Map paramsInString = new HashMap<>();
            for (Map.Entry entry : params.entrySet()) {
                paramsInString.put(entry.getKey(), entry.getValue().toString());
            }
            return paramsInString;
        }
        return null;
    }

    private boolean validateResponse(HttpResponse response) {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode >= 200 && statusCode < 300) {
            return true;
        } else {
            return false;
        }
    }

    public String getEndpoint() {
        return endpoint;
    }

    public HttpClient getHttpClient() {
        return httpClient;
    }

    public void setHttpClient(HttpClient httpClient) {
        this.httpClient = httpClient;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy