Newer
Older
sendgrid-api / src / main / java / io / ljunggren / sendgrid / api / service / UsageService.java
package io.ljunggren.sendgrid.api.service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;

import io.ljunggren.json.utils.JsonUtils;
import io.ljunggren.sendgrid.api.exception.SendgridException;
import io.ljunggren.sendgrid.api.model.Statistics;

public class UsageService extends BaseService {

	public UsageService(String apiKey) {
		super(apiKey);
	}

	public List<Statistics> getDailyUsage() throws SendgridException {
		List<Statistics> statisticses = getStatistics(0);
		if (statisticses == null) {
			throw new SendgridException("Could not fetch SendGrid statistics");
		}
		return statisticses;
	}
	
	public List<Statistics> getMonthlyStatistics() throws SendgridException {
		int dayOfMonth = LocalDate.now().getDayOfMonth();
		List<Statistics> statisticses = getStatistics(dayOfMonth - 1);
		if (statisticses == null) {
			throw new SendgridException("Could not fetch SendGrid statistics");
		}
		return statisticses;
	}
	
	public List<Statistics> getStatistics(int days) throws SendgridException {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return getStatistics("day",
        		startDate.format(formatter),
        		endDate.format(formatter)
        );
	}
	
	private List<Statistics> getStatistics(String aggregate, String startDate, String endDate) throws SendgridException {
        Request request = new Request();
        request.setMethod(Method.GET);
        request.setEndpoint("stats");
        request.addQueryParam("aggregated_by", aggregate);
        request.addQueryParam("start_date", startDate);
        request.addQueryParam("end_date", endDate);
        try {
            Response response = sendGrid.api(request);
            return JsonUtils.jsonToList(response.getBody(), Statistics.class);
        } catch (Exception e) {
        	throw new SendgridException(e);
        }
	}
    
}