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

com.makitoo.internal.EventSender Maven / Gradle / Ivy

The newest version!
package com.makitoo.internal;

import net.jodah.failsafe.CircuitBreaker;
import net.jodah.failsafe.Failsafe;
import net.jodah.failsafe.function.CheckedRunnable;
import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.makitoo.internal.PropertiesUtils.getIntProp;

/**
 * Created by nicolas on 24/01/17.
 */
public class EventSender {
    private static final Logger LOGGER = Logger.getLogger(EventSender.class.getName());
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private final Properties properties;

    private String application;
    private String environment;

    final OkHttpClient client;
    final CircuitBreaker breaker;

    public EventSender(Properties properties, String application) {
        this(properties, application, null);
    }

    public EventSender(Properties properties, String application, String environment) {
        this.properties = properties;
        this.application = application;
        this.environment = environment;


        client = new OkHttpClient.Builder()
                .connectTimeout(getIntProp(properties, "makitoo.http.connection_timeout", 15), TimeUnit.SECONDS)
                .readTimeout(getIntProp(properties, "makitoo.http.read_timeout", 15), TimeUnit.SECONDS)
                .build();

        breaker = new CircuitBreaker()
                .withFailureThreshold(getIntProp(properties, "makitoo.http.breaker.failures", 1))
                .withSuccessThreshold(getIntProp(properties, "makitoo.http.breaker.success", 3))
                .withTimeout(getIntProp(properties, "makitoo.http.breaker.timeout", 5), TimeUnit.SECONDS);
    }


    public void sendAsyncEvent(final JSONObject content) {
        final String url = getUrl();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "sending event to " + url);
        }
        Failsafe.with(breaker).run(new CheckedRunnable() {
            @Override
            public void run() throws Exception {
                RequestBody body = RequestBody.create(JSON, content.toString());
                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    public void onFailure(Call call, IOException e) {
                        LOGGER.log(Level.WARNING, "unable to send event from " + url);
                    }

                    public void onResponse(Call call, Response response) throws IOException {
                        response.close();
                    }
                });
            }
        });

    }

    public String sendEvent(final JSONObject content) throws IOException {
        return Failsafe
                .with(breaker)
                .get(new Callable() {

                    @Override
                    public String call() throws Exception {
                        String url = getUrl();

                        if (LOGGER.isLoggable(Level.FINE)) {
                            LOGGER.log(Level.FINE, "sending event to " + url);
                        }

                        RequestBody body = RequestBody.create(JSON, content.toString());
                        Request request = new Request.Builder()
                                .url(url)
                                .post(body)
                                .build();
                        Response response = client.newCall(request).execute();

                        if (response.code() == 200) {
                            return response.body().string();
                        }
                        if (response.code() == 204) {
                            response.close();
                            return null;
                        }
                        response.close();
                        throw new IOException("Unexpected response code from makitoo server: " + response.code() + " url : " + url);
                    }
                });
    }

    private String getUrl() {
        String url = properties.getProperty("makitoo.server", "https://features.makitoo.com/api/v1/")
                + String.format("event?application=%s", application);
        if (environment != null) {
            url += "&environment=" + environment;
        }
        return url;
    }

    public void shutdown(int timeout, TimeUnit timeUnit) throws InterruptedException {
        client.dispatcher().executorService().shutdown();
        client.dispatcher().executorService().awaitTermination(timeout, timeUnit);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy