com.threewks.analytics.client.AnalyticsClient.java Source code

Java tutorial

Introduction

Here is the source code for com.threewks.analytics.client.AnalyticsClient.java

Source

/*
 * This file is a component of 3wks Analytics, a software library from 3wks.
 * Copyright (C) 2013 3wks, <support@3wks.com.au>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.threewks.analytics.client;

import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;

import org.apache.commons.io.IOUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.threewks.analytics.model.Event;
import com.threewks.analytics.model.HttpRequest;
import com.threewks.analytics.model.HttpResponse;

public class AnalyticsClient implements Analytics {

    private static final Logger logger = Logger.getLogger("3wks-analytics");

    private static final String API_KEY_HEADER = "apiKey";
    private static final String CONTENT_TYPE_HEADER = "Content-Type";
    private static final String JSON_CONTENT_TYPE = "application/json";

    private String apiKey;
    private String trackRequestUrl;
    private String trackResponseUrl;
    private String trackEventUrl;
    private Gson gson;

    public AnalyticsClient(String apiKey, String url) {
        this.apiKey = apiKey;
        this.trackRequestUrl = String.format("%s/request", url);
        this.trackResponseUrl = String.format("%s/response", url);
        this.trackEventUrl = String.format("%s/event", url);
        this.gson = new GsonBuilder().create();
    }

    @Override
    public void trackRequest(HttpRequest request) {
        postJson(trackRequestUrl, gson.toJson(request));
    }

    @Override
    public void trackResponse(HttpResponse response) {
        postJson(trackResponseUrl, gson.toJson(response));
    }

    @Override
    public void trackEvent(Event event) {
        postJson(trackEventUrl, gson.toJson(event));
    }

    /**
     * Post JSON a URL. Ignore (but log) any errors.
     * 
     * @param url the URL to post the data to.
     * @param json the JSON data to post.
     */
    void postJson(String url, String json) {
        PrintWriter writer = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setDoOutput(true);
            connection.setRequestProperty(API_KEY_HEADER, apiKey);
            connection.setRequestProperty(CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE);
            writer = new PrintWriter(connection.getOutputStream(), true);
            writer.append(json);
            writer.close();

            int responseCode = connection.getResponseCode();
            if (responseCode != 200) {
                logger.warning(String.format(
                        "Analytics server returned HTTP response code: %s when posting data to url: %s",
                        responseCode, url));
            }
        } catch (Exception e) {
            logger.warning(String.format("Error sending data to url: %s, error: %s", url, e.getMessage()));
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }
}